//+------------------------------------------------------------------+
//|                                   hilbert transform adaptive EMA |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_chart_window
#property indicator_buffers 8
#property indicator_color1 LimeGreen
#property indicator_color2 Orange
#property indicator_color3 Orange
#property indicator_color4 DeepSkyBlue
#property indicator_color5 DeepSkyBlue
#property indicator_color6 PaleVioletRed
#property indicator_color7 PaleVioletRed
#property indicator_color8 Peru
#property indicator_width1 2
#property indicator_width2 2
#property indicator_width3 2
#property indicator_style5 STYLE_DOT
#property indicator_style6 STYLE_DOT
#property indicator_style8 STYLE_DASH

//
//
//
//
//

#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

//
//
//
//
//

//
//
//
//
//

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_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
};

extern ENUM_TIMEFRAMES TimeFrame               = PERIOD_CURRENT;
extern enPrices        AppliedPrice            = pr_hamedian;
extern double          filter                  = 1;
extern double          cycles                  = 1.0;
extern bool            ShowMiddleLine          = true;           // dz middle line on/off
extern int             DzLookBackBars          = 35;             // dz look back 
extern double          DzStartBuyProbability1  = 0.10;           // dz outside buy 1 solid line
extern double          DzStartBuyProbability2  = 0.25;           // dx inside buy 2 dotted line
extern double          DzStartSellProbability1 = 0.10;           // dz outside sell 1 solid line
extern double          DzStartSellProbability2 = 0.25;           // dz inside sell 2 dotted line
extern bool            Interpolate             = true;           // Interpolation in multi time frame mode

//
//
//
//
//

double ema[];
double emada[];
double emadb[];
double bl1[];
double bl2[];
double sl1[];
double sl2[];
double zli[];
double slope[];
string indicatorFileName;
bool   returnBars;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init() 
{
   IndicatorBuffers(9);
   SetIndexBuffer(0,ema); 
   SetIndexBuffer(1,emada); 
   SetIndexBuffer(2,emadb); 
   SetIndexBuffer(3,bl1);
   SetIndexBuffer(4,bl2);
   SetIndexBuffer(5,sl2);
   SetIndexBuffer(6,sl1);
   SetIndexBuffer(7,zli);
   SetIndexBuffer(8,slope); 
   
   indicatorFileName = WindowExpertName();
   returnBars        = TimeFrame==-99;
   TimeFrame         = MathMax(TimeFrame,_Period);
   
   IndicatorShortName(timeFrameToString(TimeFrame)+" dynamic zones of phase accumulation ema");
return (0);
}
int deinit(){return (0);}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int start(void)
{    
   int counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit=MathMin(Bars,Bars-1);
         if (returnBars) { ema[0] = MathMin(limit+1,Bars-1); return(0); }
         if (TimeFrame!=_Period)
         {
               limit = (int)MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
               if (slope[limit]==-1) CleanPoint(limit,emada,emadb);
               for(int i=limit; i>=0; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                     ema[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AppliedPrice,filter,cycles,ShowMiddleLine,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,0,y);
                     bl1[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AppliedPrice,filter,cycles,ShowMiddleLine,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,3,y);
                     bl2[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AppliedPrice,filter,cycles,ShowMiddleLine,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,4,y);
                     sl2[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AppliedPrice,filter,cycles,ShowMiddleLine,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,5,y);
                     sl1[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AppliedPrice,filter,cycles,ShowMiddleLine,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,6,y);
                     zli[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AppliedPrice,filter,cycles,ShowMiddleLine,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,7,y);
                     slope[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AppliedPrice,filter,cycles,ShowMiddleLine,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,8,y);
                     emada[i] = EMPTY_VALUE;
                     emadb[i] = EMPTY_VALUE;
                     
                     //
                     //
                     //
                     //
                     //
            
                     if (!Interpolate || y==iBarShift(NULL,TimeFrame,Time[i-1])) continue;

                     //
                     //
                     //
                     //
                     //

                     datetime time = iTime(NULL,TimeFrame,y);
                        for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;
                        for(int s = 1; s < n; s++) 
                        {
  	                        ema[i+s] = ema[i] + (ema[i+n] - ema[i]) * s/n;
  	                        bl1[i+s] = bl1[i] + (bl1[i+n] - bl1[i]) * s/n;
  	                        bl2[i+s] = bl2[i] + (bl2[i+n] - bl2[i]) * s/n;
  	                        sl2[i+s] = sl2[i] + (sl2[i+n] - sl2[i]) * s/n;
  	                        sl1[i+s] = sl1[i] + (sl1[i+n] - sl1[i]) * s/n;
  	                        zli[i+s] = zli[i] + (zli[i+n] - zli[i]) * s/n;
                        }
         }
         for(i=limit; i>=0; i--) if (slope[i]==-1) PlotPoint(i,emada,emadb,ema);
   return(0);
   }
   
   //
   //
   //
   //
   //
   
   if (slope[limit]==-1) CleanPoint(limit,emada,emadb);         
   for(i=limit; i>=0; i--)
   {
      double prc = getPrice(AppliedPrice,Open,Close,High,Low,i);
         if (i==Bars-1)
         {
            ema[i] = prc;
            continue;
         }
      double alpha = 2.0/(1.0+iHilbertPhase(prc,filter,cycles,i));
      ema[i] = ema[i+1]+alpha*(prc-ema[i+1]);
         if (DzStartBuyProbability1 >0) bl1[i] = dzBuyP (ema, DzStartBuyProbability1,  DzLookBackBars, Bars, i, 0.0001);
         if (DzStartBuyProbability2 >0) bl2[i] = dzBuyP (ema, DzStartBuyProbability2,  DzLookBackBars, Bars, i, 0.0001);
         if (DzStartSellProbability1>0) sl1[i] = dzSellP(ema, DzStartSellProbability1, DzLookBackBars, Bars, i, 0.0001);
         if (DzStartSellProbability2>0) sl2[i] = dzSellP(ema, DzStartSellProbability2, DzLookBackBars, Bars, i, 0.0001);
         if (ShowMiddleLine)            zli[i] = dzSellP(ema, 0.5                    , DzLookBackBars, Bars, i, 0.0001);
         emada[i] = EMPTY_VALUE;
         emadb[i] = EMPTY_VALUE;
         slope[i] = slope[i+1];
            if (ema[i]>ema[i+1]) slope[i] =  1;
            if (ema[i]<ema[i+1]) slope[i] = -1;
            if (slope[i]==-1) PlotPoint(i,emada,emadb,ema);
   }      
   return (0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double workHil[][9];
#define _price      0
#define _smooth     1
#define _detrender  2
#define _period     3
#define _instPeriod 4
#define _phase      5
#define _deltaPhase 6
#define _Q1         7
#define _I1         8

#define Pi 3.14159265358979323846264338327950288

//
//
//
//
//

double iHilbertPhase(double price, double tfilter, double cyclesToReach, int i, int s=0)
{
   if (ArrayRange(workHil,0)!=Bars) ArrayResize(workHil,Bars);
   int r = Bars-i-1; s = s*9;
      
   //
   //
   //
   //
   //
      
      workHil[r][s+_price]      = price;
      workHil[r][s+_smooth]     = (4.0*workHil[r][s+_price]+3.0*workHil[r-1][s+_price]+2.0*workHil[r-2][s+_price]+workHil[r-3][s+_price])/10.0;
      workHil[r][s+_detrender]  = calcComp(r,_smooth,s);
      workHil[r][s+_Q1]         = 0.15*calcComp(r,_detrender,s)  +0.85*workHil[r-1][s+_Q1];
      workHil[r][s+_I1]         = 0.15*workHil[r-3][s+_detrender]+0.85*workHil[r-1][s+_I1];
      workHil[r][s+_phase]      = workHil[r-1][s+_phase];
      workHil[r][s+_instPeriod] = workHil[r-1][s+_instPeriod];

      //
      //
      //
      //
      //
           
         if (MathAbs(workHil[r][s+_I1])>0)
                     workHil[r][s+_phase] = 180.0/Pi*MathArctan(MathAbs(workHil[r][s+_Q1]/workHil[r][s+_I1]));
           
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]>0) workHil[r][s+_phase] = 180-workHil[r][s+_phase];
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 180+workHil[r][s+_phase];
         if (workHil[r][s+_I1]>0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 360-workHil[r][s+_phase];

      //
      //
      //
      //
      //
                        
      workHil[r][s+_deltaPhase] = workHil[r-1][s+_phase]-workHil[r][s+_phase];

         if (workHil[r-1][s+_phase]<90 && workHil[r][s+_phase]>270)
             workHil[r][s+_deltaPhase] = 360+workHil[r-1][s+_phase]-workHil[r][s+_phase];
             workHil[r][s+_deltaPhase] = MathMax(MathMin(workHil[r][s+_deltaPhase],60),7);
      
            //
            //
            //
            //
            //
                  
            double alpha    = 2.0/(1.0+MathMax(tfilter,1));
            double phaseSum = 0; for (int k=0; phaseSum<cyclesToReach*360 && (r-k)>0; k++) phaseSum += workHil[r-k][s+_deltaPhase];
         
               if (k>0) workHil[r][s+_instPeriod]= k;
                  workHil[r][s+_period] = workHil[r-1][s+_period]+alpha*(workHil[r][s+_instPeriod]-workHil[r-1][s+_period]);
   return (workHil[r][s+_period]);
}

//
//
//
//
//

double calcComp(int r, int from, int s)
{
   return((0.0962*workHil[r  ][s+from] + 
           0.5769*workHil[r-2][s+from] - 
           0.5769*workHil[r-4][s+from] - 
           0.0962*workHil[r-6][s+from]) * (0.075*workHil[r-1][s+_period] + 0.54));
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//
//

double workHa[][4];
double getPrice(int price, const double& open[], const double& close[], const double& high[], const double& low[], int i, int instanceNo=0)
{
  if (price>=pr_haclose && price<=pr_hatbiased)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars);
         int r = Bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen;
         if (r>0)
                haOpen  = (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0;
         else   haOpen  = (open[i]+close[i])/2;
         double haClose = (open[i] + high[i] + low[i] + close[i]) / 4.0;
         double haHigh  = MathMax(high[i], MathMax(haOpen,haClose));
         double haLow   = MathMin(low[i] , MathMin(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 (price)
         {
            case pr_haclose:     return(haClose);
            case pr_haopen:      return(haOpen);
            case pr_hahigh:      return(haHigh);
            case pr_halow:       return(haLow);
            case pr_hamedian:    return((haHigh+haLow)/2.0);
            case pr_hamedianb:   return((haOpen+haClose)/2.0);
            case pr_hatypical:   return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:  return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:   return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (price)
   {
      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);        
   }
   return(0);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if (i>Bars-2) 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-3) 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("");
}