//------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 8
#property indicator_color1  clrLimeGreen
#property indicator_color2  clrOrange
#property indicator_color3  clrOrange
#property indicator_color4  clrDeepSkyBlue
#property indicator_color5  clrDeepSkyBlue
#property indicator_color6  clrPaleVioletRed
#property indicator_color7  clrPaleVioletRed
#property indicator_color8  clrDimGray
#property indicator_style5  STYLE_DOT
#property indicator_style6  STYLE_DOT
#property indicator_style8  STYLE_DASH
#property strict

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuyP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision);
   double dzSellP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision);
#import

//33 enPrices
enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_tbiased2,   // Trend biased (extreme) price
   pr_haclose,    // Heiken ashi close
   pr_haopen,     // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased,  // Heiken ashi trend biased price
   pr_hatbiased2, // Heiken ashi trend biased (extreme) price
   pr_habclose,   // Heiken ashi (better formula) close
   pr_habopen,    // Heiken ashi (better formula) open
   pr_habhigh,    // Heiken ashi (better formula) high
   pr_hablow,     // Heiken ashi (better formula) low
   pr_habmedian,  // Heiken ashi (better formula) median
   pr_habtypical, // Heiken ashi (better formula) typical
   pr_habweighted,// Heiken ashi (better formula) weighted
   pr_habaverage, // Heiken ashi (better formula) average
   pr_habmedianb, // Heiken ashi (better formula) median body
   pr_habtbiased, // Heiken ashi (better formula) trend biased price
   pr_habtbiased2 // Heiken ashi (better formula) trend biased (extreme) price
};

enum enDoWhat
{
   do_cci,  // Make cci using nma as price filter
   do_nma   // Make nma smoothed cci
};

extern ENUM_TIMEFRAMES TimeFrame               = PERIOD_CURRENT;// Time frame to use
extern int             pperiod                 = 14;            // Calculating period
extern enPrices        pprice                  = pr_close;      // Price
extern int             filter                  = 40;            // Nma period 
extern int             filterTema              = 10;            // Nma tema period
extern enDoWhat        doWhat                  = do_nma;        // Make what?
extern int             DzLookBackBars          = 70;            // dynamic zone look back
extern double          DzStartBuyProbability1  = 0.10;          // dynamic zone buy
extern double          DzStartBuyProbability2  = 0.25;          // dynamic zone buy
extern double          DzStartSellProbability1 = 0.10;          // dynamic zone sell
extern double          DzStartSellProbability2 = 0.25;          // dynamic zone sell
extern bool            alertsOn                = true;          // Turn alerts on
extern bool            alertsOnCurrent         = false;         // Alerts on current (still opened) bar
extern bool            alertsMessage           = true;          // Alerts should display alert message
extern bool            alertsNotification      = false;         // Alerts should send alert notification
extern bool            alertsSound             = false;         // Alerts should play alert sound
extern bool            alertsEmail             = false;         // Alerts should send alert email?
extern bool            Interpolate             = true;          // Interpolate in multi time frame mode?
extern int             linesWidth              =  3;            // Lines width


double buffer[], bufferda[], bufferdb[], bl1[], bl2[], sl1[], sl2[], zl1[], trend[], work[], pricef[];
string indicatorFileName;
bool   returnBars;

//------------------------------------------------------------------
int OnInit()
{
   IndicatorBuffers(11);
   SetIndexBuffer(0, buffer,  INDICATOR_DATA); SetIndexStyle(0,EMPTY,EMPTY,linesWidth);
   SetIndexBuffer(1, bufferda,INDICATOR_DATA); SetIndexStyle(1,EMPTY,EMPTY,linesWidth);
   SetIndexBuffer(2, bufferdb,INDICATOR_DATA); SetIndexStyle(2,EMPTY,EMPTY,linesWidth);
   SetIndexBuffer(3, bl1,     INDICATOR_DATA);
   SetIndexBuffer(4, bl2,     INDICATOR_DATA);
   SetIndexBuffer(5, sl2,     INDICATOR_DATA);
   SetIndexBuffer(6, sl1,     INDICATOR_DATA);
   SetIndexBuffer(7, zl1,     INDICATOR_DATA);
   SetIndexBuffer(8, trend   ,INDICATOR_CALCULATIONS);
   SetIndexBuffer(9, work    ,INDICATOR_CALCULATIONS);
   SetIndexBuffer(10,pricef  ,INDICATOR_CALCULATIONS);
   
   indicatorFileName = WindowExpertName();
   returnBars        = TimeFrame==-99;
   TimeFrame         = MathMax(TimeFrame,_Period);
   
   IndicatorShortName(timeFrameToString(TimeFrame)+" dynamic double zone cci nma ("+(string)pperiod+","+(string)filter+")");
return(0);
}
//------------------------------------------------------------------
int start()
{
   int counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
            int limit=MathMin(Bars-counted_bars,Bars-2);
            if (returnBars) { buffer[0] = MathMin(limit+1,Bars-1); return(0); }
            if (TimeFrame != Period())
            {
               if (trend[limit]==-1) CleanPoint(limit,bufferda,bufferdb);
               for(int i=limit; i>=0; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                  buffer[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,pperiod,pprice,filter,filterTema,doWhat,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,0,y);
                  bl1[i]      = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,pperiod,pprice,filter,filterTema,doWhat,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,3,y);
                  bl2[i]      = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,pperiod,pprice,filter,filterTema,doWhat,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,4,y);
                  sl2[i]      = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,pperiod,pprice,filter,filterTema,doWhat,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,5,y);
                  sl1[i]      = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,pperiod,pprice,filter,filterTema,doWhat,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,6,y);
                  zl1[i]      = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,pperiod,pprice,filter,filterTema,doWhat,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,7,y);
                  trend[i]    = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,pperiod,pprice,filter,filterTema,doWhat,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,8,y);
                  bufferda[i] = EMPTY_VALUE;
                  bufferdb[i] = EMPTY_VALUE;
                  if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,Time[i-1]))) continue;
                  
                  //
                  //
                  //
                  //
                  //
                  
                  int n,k; datetime time = iTime(NULL,TimeFrame,y);
                     for(n = 1; (i+n)<Bars && Time[i+n] >= time; n++) continue;	
                     for(k = 1; k<n && (i+n)<Bars && (i+k)<Bars; k++)
                     { 
                        buffer[i+k] = buffer[i] + (buffer[i+n] - buffer[i]) * k/n;
                        bl1[i+k]    = bl1[i]    + (bl1[i+n]    - bl1[i])    * k/n;
                        bl2[i+k]    = bl2[i]    + (bl2[i+n]    - bl2[i])    * k/n;
                        sl2[i+k]    = sl2[i]    + (sl2[i+n]    - sl2[i])    * k/n;
                        sl1[i+k]    = sl1[i]    + (sl1[i+n]    - sl1[i])    * k/n;
                        zl1[i+k]    = zl1[i]    + (zl1[i+n]    - zl1[i])    * k/n;
                     }
               }
               for(int i=limit; i>=0; i--) if (trend[i] == -1) PlotPoint(i,bufferda,bufferdb,buffer);
               return(0);
            }

   if (trend[limit]==-1) CleanPoint(limit,bufferda,bufferdb);
   for(int i=limit; i>=0; i--)
   {
      if (doWhat==do_cci)
            pricef[i] = iNma(getPrice(pprice,Open,Close,High,Low,i,Bars),filter,filterTema,i);
      else  pricef[i] = getPrice(pprice,Open,Close,High,Low,i,Bars);
      double avg = 0; for(int k=0; k<pperiod && (i+k)<Bars; k++) avg +=         pricef[i+k];      avg /= pperiod;
      double dev = 0; for(int k=0; k<pperiod && (i+k)<Bars; k++) dev += MathAbs(pricef[i+k]-avg); dev /= pperiod;
         if (dev!=0)
               work[i] = (pricef[i]-avg)/(0.015*dev);
         else  work[i] = 0;
         if (doWhat==do_cci)
                  buffer[i] = work[i];
         else     buffer[i] = iNma(work[i],filter,filterTema,i);
         
         if (DzStartBuyProbability1  > 0) bl1[i] = dzBuyP (buffer,DzStartBuyProbability1, DzLookBackBars,Bars,i,0.0001);
         if (DzStartBuyProbability2  > 0) bl2[i] = dzBuyP (buffer,DzStartBuyProbability2, DzLookBackBars,Bars,i,0.0001);
         if (DzStartSellProbability1 > 0) sl1[i] = dzSellP(buffer,DzStartSellProbability1,DzLookBackBars,Bars,i,0.0001);
         if (DzStartSellProbability2 > 0) sl2[i] = dzSellP(buffer,DzStartSellProbability2,DzLookBackBars,Bars,i,0.0001);
                                          zl1[i] = dzSellP(buffer,0.5                    ,DzLookBackBars,Bars,i,0.0001);
         bufferda[i] = EMPTY_VALUE;
         bufferdb[i] = EMPTY_VALUE;
         trend[i]    = trend[i+1];
         
         if (buffer[i]>buffer[i+1]) trend[i] =  1;
         if (buffer[i]<buffer[i+1]) trend[i] = -1;
         if (trend[i] == -1) PlotPoint(i,bufferda,bufferdb,buffer);
   } 
   
   if (alertsOn)
      {
         int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
         if (trend[whichBar] != trend[whichBar+1])
         if (trend[whichBar] == 1)
               doAlert("sloping up");
         else  doAlert("sloping down");       
      }   
   return(0);
}
//------------------------------------------------------------------
#define _nmaInstances 1
#define _nmaPrice     3
#define _nmaMom       4
#define _nmaValue     5
double workNma[][_nmaInstances*6];

double iNma(double price, int period, int temaperiod, int i, int instanceNo=0)
{
   if (period<=1) return(price);
   if (ArrayRange(workNma,0)!=Bars) ArrayResize(workNma,Bars); i = Bars-i-1; instanceNo*=6;

   double alpha = 2.0 /(1.0 + temaperiod);
   if (i < 1)
   {
      workNma[i][instanceNo+_nmaPrice] = price;
      workNma[i][instanceNo+_nmaValue] = price;
      workNma[i][instanceNo+_nmaMom]   = 0;
      workNma[i][instanceNo+0]         = price;
      workNma[i][instanceNo+1]         = price;
      workNma[i][instanceNo+2]         = price;
   }
   else
   {
      workNma[i][instanceNo+0]         = workNma[i-1][instanceNo+0]+alpha*(price                   -workNma[i-1][instanceNo+0]);
      workNma[i][instanceNo+1]         = workNma[i-1][instanceNo+1]+alpha*(workNma[i][instanceNo+0]-workNma[i-1][instanceNo+1]);
      workNma[i][instanceNo+2]         = workNma[i-1][instanceNo+2]+alpha*(workNma[i][instanceNo+1]-workNma[i-1][instanceNo+2]);
      workNma[i][instanceNo+_nmaPrice] = 3*workNma[i][instanceNo+0] - 3*workNma[i][instanceNo+1] + workNma[i][instanceNo+2];
      workNma[i][instanceNo+_nmaMom]   = workNma[i][instanceNo+_nmaPrice]-workNma[i-1][instanceNo+_nmaPrice];
   
      double momRatio = 0.00;
      double sumMomen = 0.00;
      double ratio    = 0.00;
      
      for (int k = 0; k<period && (i-k)>=0; k++)
      {
         sumMomen += MathAbs(workNma[i-k][instanceNo+_nmaMom]);
         momRatio +=         workNma[i-k][instanceNo+_nmaMom]*(MathSqrt(k+1)-MathSqrt(k));
      }
      if (sumMomen != 0) ratio = MathAbs(momRatio)/sumMomen;
      workNma[i][instanceNo+_nmaValue] =  workNma[i-1][instanceNo+_nmaValue]+ratio*(price-workNma[i-1][instanceNo+_nmaValue]);
   }         
   return(workNma[i][instanceNo+_nmaValue]);
}
//-------------------------------------------------------------------
void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}
//-------------------------------------------------------------------
void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (i>=Bars-2) return;
   if (first[i+1] == EMPTY_VALUE)
         {
            if (first[i+2] == EMPTY_VALUE) 
                  { first[i]  = from[i]; first[i+1]  = from[i+1]; second[i] = EMPTY_VALUE; }
            else  { second[i] = from[i]; second[i+1] = from[i+1]; first[i]  = EMPTY_VALUE; }
         }
   else  { first[i] = from[i]; second[i] = EMPTY_VALUE; }
}
//-------------------------------------------------------------------
string sTfTable[] = {"M1","M5","M10","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,10,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}
//------------------------------------------------------------------
void doAlert(string doIt)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
      if (previousAlert != doIt || previousTime != Time[0]) {
          previousAlert  = doIt;
          previousTime   = Time[0];

          //
          //
          //
          //
          //

          message = StringConcatenate(Symbol()," ",timeFrameToString(_Period)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," DZ cci + nma ",doIt);
             if (alertsMessage)      Alert(message);
             if (alertsNotification) SendNotification(message);
             if (alertsEmail)        SendMail(StringConcatenate(Symbol()," DZ cci + nma "),message);
             if (alertsSound)        PlaySound("alert2.wav");
      }
}
//-------------------------------------------------------------------
#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     1
#define _priceInstancesSize 4
double workHa[][_priceInstances*_priceInstancesSize];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars, int instanceNo=0)
{
  if (tprice>=pr_haclose)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars); instanceNo*=_priceInstancesSize; int r = bars-i-1;
         
         double haOpen  = (r>0) ? (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0 : (open[i]+close[i])/2;;
         double haClose = (open[i]+high[i]+low[i]+close[i]) / 4.0;
         if (_prHABF(tprice))
               if (high[i]!=low[i])
                     haClose = (open[i]+close[i])/2.0+(((close[i]-open[i])/(high[i]-low[i]))*MathAbs((close[i]-open[i])/2.0));
               else  haClose = (open[i]+close[i])/2.0; 
         double haHigh  = fmax(high[i], fmax(haOpen,haClose));
         double haLow   = fmin(low[i] , fmin(haOpen,haClose));
         
         if(haOpen<haClose) { workHa[r][instanceNo+0] = haLow;  workHa[r][instanceNo+1] = haHigh; } 
         else               { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow;  } 
                              workHa[r][instanceNo+2] = haOpen;
                              workHa[r][instanceNo+3] = haClose;
         
         switch (tprice)
         {
            case pr_haclose:
            case pr_habclose:    return(haClose);
            case pr_haopen:   
            case pr_habopen:     return(haOpen);
            case pr_hahigh: 
            case pr_habhigh:     return(haHigh);
            case pr_halow:    
            case pr_hablow:      return(haLow);
            case pr_hamedian:
            case pr_habmedian:   return((haHigh+haLow)/2.0);
            case pr_hamedianb:
            case pr_habmedianb:  return((haOpen+haClose)/2.0);
            case pr_hatypical:
            case pr_habtypical:  return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:
            case pr_habweighted: return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:  
            case pr_habaverage:  return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
            case pr_habtbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
            case pr_hatbiased2:
            case pr_habtbiased2:
               if (haClose>haOpen)  return(haHigh);
               if (haClose<haOpen)  return(haLow);
                                    return(haClose);        
         }
   }
   
   
   switch (tprice)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
      case pr_tbiased2:   
               if (close[i]>open[i]) return(high[i]);
               if (close[i]<open[i]) return(low[i]);
                                     return(close[i]);        
   }
   return(0);
}
//------------------------------------------------------------------
