//------------------------------------------------------------------
//
//
//
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 5
#property indicator_color1  clrSlateGray
#property indicator_color2  clrBlue
#property indicator_color3  clrRed
#property indicator_color4  clrRed
#property indicator_color5  clrSlateGray
#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             = 16;
extern ENUM_APPLIED_PRICE MaPrice            = PRICE_CLOSE;
extern int                TemaLength         = 1;
extern int                PostLength         = 4;
extern int                PostTemaLength     = 1;
extern double             Smooth             = 4;
extern int                SmoothPhase        = 0;
extern bool               SmoothDouble       = false;
input double              SigPer             = 6;                 // Signal period
enum  enMaTypes
      {
         ma_sma,     // Simple moving average
         ma_ema,     // Exponential moving average
         ma_smma,    // Smoothed MA
         ma_lwma,    // Linear weighted MA
      };
input enMaTypes           MaMethod           = ma_ema;            // Signal moving average type
extern int                DzLookBackBars     = 50;
enum  enColorOn
      {
        col_onSlope,                                              // Change color on slope change
        col_onZero,                                               // Change color on zero cross
        col_onSig,                                                // Change color on signal cross
        col_noChange,                                             // No color change
      };
input enColorOn           inpColorOn         = col_onSlope;       // Color change mode 
extern bool               arrowsVisible      = false;
extern string             arrowsIdentifier   = "MaAtrNmaArrows";
extern color              arrowsUpColor      = clrBlue;
extern color              arrowsDnColor      = clrRed;
extern double             arrowsUpperGap     = 0.75;
extern double             arrowsLowerGap     = 0.75;
extern bool               alertsOn           = false;
extern bool               alertsOnCurrent    = true;
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 avg[],vala[],valb[],zli[],sig[],trend[],count[];
string indicatorFileName;
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Length,MaPrice,TemaLength,PostLength,PostTemaLength,Smooth,SmoothPhase,SmoothDouble,SigPer,MaMethod,DzLookBackBars,inpColorOn,arrowsVisible,arrowsIdentifier,arrowsUpColor,arrowsDnColor,arrowsUpperGap,arrowsLowerGap,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,_buff,_ind)

//------------------------------------------------------------------
//
//------------------------------------------------------------------

int init()
{
   if (!IsDllsAllowed())
   {
      Alert("Please enable dll imports in the indicators properties");
      Alert("This indicator needs to have dll import option allowed in order to work");
      return(INIT_FAILED);
   }    
   IndicatorBuffers(7);
   SetIndexBuffer(0,zli);  SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(1,avg);  SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(2,vala); SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(3,valb); SetIndexStyle(3,DRAW_LINE); 
   SetIndexBuffer(4,sig);  SetIndexStyle(4,DRAW_LINE);
   SetIndexBuffer(5,trend);
   SetIndexBuffer(6,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(6,0)*TimeFrame/_Period));
               if (trend[limit]==-1) CleanPoint(limit,vala,valb);
               for (i=limit;i>=0 && !_StopFlag; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                     zli[i]   = _mtfCall(0,y);
                     avg[i]   = _mtfCall(1,y);
                     sig[i]   = _mtfCall(4,y);
                     vala[i]  = valb[i]  = EMPTY_VALUE;
                     trend[i] = _mtfCall(5,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(zli);
                              _interpolate(avg);
                              _interpolate(sig);
                           }
                                                    
              }   
              for (i=limit; i >= 0; i--) if (trend[i]==-1) PlotPoint(i,vala,valb,avg);
   return(0);
   }
      
   //
   //
   //
   
   if (trend[limit]==-1) CleanPoint(limit,vala,valb);
   for(i=limit; i>=0; i--)
   {
      double cl = iClose(NULL,0,i);
      double pr = iMA(NULL,0,1,0,MODE_SMA,MaPrice,i);
      double ma = iNma(pr,iTema(pr,TemaLength,i,Bars,0),Length,i,Bars,0);
      double tr = iATR(NULL,0,Length, i);
      double val = 0;
      if (tr > 0.0) 
      {
         val = 100.0 * NormalizeDouble(fabs(cl-ma)/tr,2);
            if (cl<ma) val *= -1.0;
      }
      avg[i] = iDSmooth(iNma(val,iTema(val,PostTemaLength,i,Bars,1),PostLength,i,Bars,1),Smooth,SmoothPhase,SmoothDouble,i);
      zli[i] = dzSellP(avg,0.5,DzLookBackBars,Bars,i,0.001);
      sig[i] = iCustomMa(MaMethod,avg[i],SigPer,i,Bars); 
      switch (inpColorOn)
      {
         case col_onSlope : trend[i] = (i<Bars-1) ? (avg[i]>avg[i+1]) ? 1 : (avg[i]<avg[i+1]) ? -1 : trend[i+1] : 0; break;
         case col_onZero  : trend[i] = (i<Bars-1) ? (avg[i]>zli[i])   ? 1 : (avg[i]<zli[i])   ? -1 : trend[i+1] : 0; break;
         case col_onSig   : trend[i] = (i<Bars-1) ? (avg[i]>sig[i])   ? 1 : (avg[i]<sig[i])   ? -1 : trend[i+1] : 0; break;
         default :          trend[i] = 0;
      }      
      if (trend[i]==-1) PlotPoint(i,vala,valb,avg); else vala[i] = valb[i] = EMPTY_VALUE;
      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 bars, 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 += fabs(workNma[i-k][instanceNo+_Mom]);
            momRatio +=         workNma[i-k][instanceNo+_Mom]*(sqrt(k+1)-sqrt(k));
         }
         if (sumMomen != 0) ratio = fabs(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 bars, 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]));
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------

string getAverageName(int method)
{
      switch(method)
      {
         case ma_ema:    return("EMA");
         case ma_lwma:   return("LWMA");
         case ma_sma:    return("SMA");
         case ma_smma:   return("SMMA");
      }
return("");      
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------

#define _maInstances 1
#define _maWorkBufferx1 1*_maInstances
#define _maWorkBufferx2 2*_maInstances
#define _maWorkBufferx3 3*_maInstances

double iCustomMa(int mode, double price, double length, int r, int bars, int instanceNo=0)
{
   r = bars-r-1;
   switch (mode)
   {
      case ma_sma   : return(iSma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_ema   : return(iEma(price,length,r,bars,instanceNo));
      case ma_smma  : return(iSmma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_lwma  : return(iLwma(price,(int)ceil(length),r,bars,instanceNo));
      default       : return(price);
   }
}

//
//
//
//
//

double workSma[][_maWorkBufferx1];
double iSma(double price, int period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= _bars) ArrayResize(workSma,_bars);

   workSma[r][instanceNo+0] = price;
   double tavg = price; int k=1;  for(; k<period && (r-k)>=0; k++) tavg += workSma[r-k][instanceNo+0];  
   return(tavg/(double)k);
}

//
//
//
//
//

double workEma[][_maWorkBufferx1];
double iEma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= _bars) ArrayResize(workEma,_bars);

   workEma[r][instanceNo] = price;
   if (r>0 && period>1)
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+(2.0/(1.0+period))*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//
//
//
//
//

double workSmma[][_maWorkBufferx1];
double iSmma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSmma,0)!= _bars) ArrayResize(workSmma,_bars);

   workSmma[r][instanceNo] = price;
   if (r>1 && period>1)
          workSmma[r][instanceNo] = workSmma[r-1][instanceNo]+(price-workSmma[r-1][instanceNo])/period;
   return(workSmma[r][instanceNo]);
}

//
//
//
//
//

double workLwma[][_maWorkBufferx1];
double iLwma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workLwma,0)!= _bars) ArrayResize(workLwma,_bars);
   
   workLwma[r][instanceNo] = price; if (period<=1) return(price);
      double sumw = period;
      double sum  = period*price;

      for(int k=1; k<period && (r-k)>=0; k++)
      {
         double weight = period-k;
                sumw  += weight;
                sum   += weight*workLwma[r-k][instanceNo];  
      }             
      return(sum/sumw);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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("");
}