//------------------------------------------------------------------
//
//
//
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  clrGray
#property indicator_color2  clrBlue
#property indicator_color3  clrRed
#property indicator_color4  clrRed
#property indicator_width2  2
#property indicator_width3  2
#property indicator_width4  2

#import "dynamicZone.dll"
   double dzSellP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision);
#import

extern ENUM_TIMEFRAMES    TimeFrame          = PERIOD_CURRENT;    // Time frame
extern int                Length             = 40;
extern ENUM_APPLIED_PRICE MaPrice            = PRICE_CLOSE;
extern int                TemaLength         = 1;
extern int                PostLength         = 10;
extern int                PostTemaLength     = 1;
extern double             Smooth             = 8;
extern int                SmoothPhase        = 0;
extern bool               SmoothDouble       = false;
extern int                DzLookBackBars     = 50;
extern bool               arrowsVisible      = false;
extern string             arrowsIdentifier   = "MaAtrNmaArrows";
extern color              arrowsUpColor      = clrDeepSkyBlue;
extern color              arrowsDnColor      = clrRed;
extern double             arrowsUpperGap     = 0.75;
extern double             arrowsLowerGap     = 0.75;
extern bool               alertsOn           = true;
extern bool               alertsOnCurrent    = false;
extern bool               alertsMessage      = true;
extern bool               alertsNotification = false;
extern bool               alertsSound        = false;
extern bool               alertsEmail        = false;
extern bool               Interpolate        = true;              // Interpolate in mtf mode?

double MA[],buffer2[],buffer3[],zeroLine[],trend[],count[];
string indicatorFileName;
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Length,MaPrice,TemaLength,PostLength,PostTemaLength,Smooth,SmoothPhase,SmoothDouble,DzLookBackBars,arrowsVisible,arrowsIdentifier,arrowsUpColor,arrowsDnColor,arrowsUpperGap,arrowsLowerGap,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,_buff,_ind)

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   for (int i=0; i<indicator_buffers; i++) SetIndexStyle(i,DRAW_LINE);
   IndicatorBuffers(6);
   SetIndexBuffer(0,zeroLine);
   SetIndexBuffer(1,MA);
   SetIndexBuffer(2,buffer2);
   SetIndexBuffer(3,buffer3); 
   SetIndexBuffer(4,trend);
   SetIndexBuffer(5,count);

   indicatorFileName = WindowExpertName();
   TimeFrame         = fmax(TimeFrame,_Period);  
         
   IndicatorShortName(timeFrameToString(TimeFrame)+" dz nma atr ("+(string)Length+")");
return(0);
}
int deinit()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
   return(0);
}

//
//
//
//
//

int start()
{
   int i,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = fmin(Bars-counted_bars,Bars-1); count[0]=limit;
            if (TimeFrame!=_Period)
            {
               limit = (int)fmax(limit,fmin(Bars-1,_mtfCall(5,0)*TimeFrame/_Period));
               if (trend[limit]==-1) CleanPoint(limit,buffer2,buffer3);
               for (i=limit;i>=0 && !_StopFlag; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                     zeroLine[i] = _mtfCall(0,y);
                     MA[i]       = _mtfCall(1,y);
                     buffer2[i]  = EMPTY_VALUE;
                     buffer3[i]  = EMPTY_VALUE;
                     trend[i]    = _mtfCall(4,y);
                 
                     //
                     //
                     //
                     //
                     //
                     
                     if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,Time[i-1]))) continue;
                        #define _interpolate(buff) buff[i+k] = buff[i]+(buff[i+n]-buff[i])*k/n
                        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++)  
                           {
                              _interpolate(zeroLine);
                              _interpolate(MA);
                           }
                                                    
              }   
              for (i=limit; i >= 0; i--) if (trend[i]==-1) PlotPoint(i,buffer2,buffer3,MA);
   return(0);
   }
      
   //
   //
   //
   //
   //
   
   if (trend[limit]==-1) CleanPoint(limit,buffer2,buffer3);
   for(i=limit; i>=0; i--)
   {
      double close = iClose(NULL,0,i);
      double price = iMA(NULL,0,1,0,MODE_SMA,MaPrice,i);
      double ma    = iNma(price,iTema(price,TemaLength,i,0),Length,i,0);
      double atr   = iATR(NULL,0, Length, i);
      double value = 0;
      if (atr > 0.0) 
      {
         value = 100.0 * NormalizeDouble(MathAbs(close - ma)/atr,2);
            if (close < ma) value *= -1.0;
      }
      MA[i]=iDSmooth(iNma(value,iTema(value,PostTemaLength,i,1),PostLength,i,1),Smooth,SmoothPhase,SmoothDouble,i);
      zeroLine[i] = dzSellP(MA,0.5,DzLookBackBars, Bars, i, 0.001);
      
      buffer2[i]  = EMPTY_VALUE;
      buffer3[i]  = EMPTY_VALUE;
      trend[i]    = trend[i+1];
         if (MA[i]>zeroLine[i]) trend[i] =  1;
         if (MA[i]<zeroLine[i]) trend[i] = -1;
         if (trend[i]==-1) PlotPoint(i,buffer2,buffer3,MA);
         manageArrow(i);
   }
   manageAlerts();
   return(0);
}



//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//

double workNma[][6];
#define _Prc 0
#define _Mom 1
#define _Nma 2

double iNma(double rawPrice, double price, int period, int i, int instanceNo=0)
{
   if (ArrayRange(workNma,0) != Bars) ArrayResize(workNma,Bars); i = Bars-i-1; instanceNo *= 3;
   
      workNma[i][instanceNo+_Prc] = price;
      workNma[i][instanceNo+_Mom] = workNma[i][instanceNo+_Prc]-workNma[i-1][instanceNo+_Prc];

      //
      //
      //
      //
      //
      
      double momRatio = 0.00;
      double sumMomen = 0.00;
      double ratio    = 0.00;
      
         for (int k = 0; k<period; k++)
         {
            sumMomen += MathAbs(workNma[i-k][instanceNo+_Mom]);
            momRatio +=         workNma[i-k][instanceNo+_Mom]*(MathSqrt(k+1)-MathSqrt(k));
         }
         if (sumMomen != 0) ratio = MathAbs(momRatio)/sumMomen;      
         workNma[i][instanceNo+_Nma] = workNma[i-1][instanceNo+_Nma]+ratio*(rawPrice-workNma[i-1][instanceNo+_Nma]);
   return(workNma[i][instanceNo+_Nma]);
}

//
//
//
//
//

double workTema[][6];
#define _ema1 0
#define _ema2 1
#define _ema3 2

double iTema(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workTema,0)!= Bars) ArrayResize(workTema,Bars); instanceNo*=3; r=Bars-r-1;

   //
   //
   //
   //
   //
      
   double alpha = 2.0 / (1.0+period);
          workTema[r][_ema1+instanceNo] = workTema[r-1][_ema1+instanceNo]+alpha*(price                        -workTema[r-1][_ema1+instanceNo]);
          workTema[r][_ema2+instanceNo] = workTema[r-1][_ema2+instanceNo]+alpha*(workTema[r][_ema1+instanceNo]-workTema[r-1][_ema2+instanceNo]);
          workTema[r][_ema3+instanceNo] = workTema[r-1][_ema3+instanceNo]+alpha*(workTema[r][_ema2+instanceNo]-workTema[r-1][_ema3+instanceNo]);
   return(workTema[r][_ema3+instanceNo]+3.0*(workTema[r][_ema1+instanceNo]-workTema[r][_ema2+instanceNo]));
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void manageArrow(int i)
{
   if (arrowsVisible )
   {
         string lookFor = arrowsIdentifier+":"+Time[i]; ObjectDelete(lookFor);
         if (trend[i]!=trend[i+1])
         {
            if (trend[i] == 1) drawArrow(i,arrowsUpColor,241,false);
            if (trend[i] ==-1) drawArrow(i,arrowsDnColor,242,true);
         }
   }
}               

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = iATR(NULL,0,20,i);
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i]+gap*arrowsUpperGap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i] -gap*arrowsLowerGap);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
            int forBar = 0;
      else      forBar = 1; 
      if (trend[forBar]!=trend[forBar+1])
      {
         if (trend[forBar]== 1) doAlert(0,"up");
         if (trend[forBar]==-1) doAlert(0,"down");
      }            
   }
} 
void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
      if (previousAlert != doWhat || previousTime != Time[forBar]) {
          previousAlert  = doWhat;
          previousTime   = Time[forBar];

          //
          //
          //
          //
          //

          message =  StringConcatenate(Symbol()," ",timeFrameToString(Period())," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," dz ma atr - nma trend changed trend to ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsNotification) SendNotification(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," dz ma atr - nma trend"),message);
             if (alertsSound)   PlaySound("alert2.wav");
      }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double wrk[][20];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

double iDSmooth(double price, double length, double phase, bool isDouble, int i, int s=0){
   if (isDouble)
         return (iSmooth(iSmooth(price,MathSqrt(length),phase,i,s),MathSqrt(length),phase,i,s+10));
   else  return (iSmooth(price,length,phase,i,s));
}

double iSmooth(double price, double length, double phase, int i, int s=0){
   if (length <=1) return(price);
   if (ArrayRange(wrk,0) != Bars) ArrayResize(wrk,Bars);
   
   int r = Bars-i-1; 
      if (r==0) { for(int k=0; k<7; k++) wrk[r][k+s]=price; for(; k<10; k++) wrk[r][k+s]=0; return(price); }
   
      double len1   = MathMax(MathLog(MathSqrt(0.5*(length-1)))/MathLog(2.0)+2.0,0);
      double pow1   = MathMax(len1-2.0,0.5);
      double del1   = price - wrk[r-1][bsmax+s];
      double del2   = price - wrk[r-1][bsmin+s];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = MathMin(r,10);
	
         wrk[r][volty+s] = 0;
               if(MathAbs(del1) > MathAbs(del2)) wrk[r][volty+s] = MathAbs(del1); 
               if(MathAbs(del1) < MathAbs(del2)) wrk[r][volty+s] = MathAbs(del2); 
         wrk[r][vsum+s] =	wrk[r-1][vsum+s] + (wrk[r][volty+s]-wrk[r-forBar][volty+s])*div;
         wrk[r][avolty+s] = wrk[r-1][avolty+s]+(2.0/(MathMax(4.0*length,30)+1.0))*(wrk[r][vsum+s]-wrk[r-1][avolty+s]);
            if (wrk[r][avolty+s] > 0)
               double dVolty = wrk[r][volty+s]/wrk[r][avolty+s]; else dVolty = 0;   
	               if (dVolty > MathPow(len1,1.0/pow1)) dVolty = MathPow(len1,1.0/pow1);
                  if (dVolty < 1)                      dVolty = 1.0;
	        
   	double pow2 = MathPow(dVolty, pow1);
      double len2 = MathSqrt(0.5*(length-1))*len1;
      double Kv   = MathPow(len2/(len2+1), MathSqrt(pow2));

         if (del1 > 0) wrk[r][bsmax+s] = price; else wrk[r][bsmax+s] = price - Kv*del1;
         if (del2 < 0) wrk[r][bsmin+s] = price; else wrk[r][bsmin+s] = price - Kv*del2;
      
      double R     = MathMax(MathMin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = MathPow(beta,pow2);

         wrk[r][0+s] = price + alpha*(wrk[r-1][0+s]-price);
         wrk[r][1+s] = (price - wrk[r][0+s])*(1-beta) + beta*wrk[r-1][1+s];
         wrk[r][2+s] = (wrk[r][0+s] + R*wrk[r][1+s]);
         wrk[r][3+s] = (wrk[r][2+s] - wrk[r-1][4+s])*MathPow((1-alpha),2) + MathPow(alpha,2)*wrk[r-1][3+s];
         wrk[r][4+s] = (wrk[r-1][4+s] + wrk[r][3+s]); 

   return(wrk[r][4+s]);
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if (i>=Bars-3) return;
   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","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,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("");
}