//+------------------------------------------------------------------+
//|                                                  BB Macd nrp.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 6
#property indicator_color1  clrDimGray
#property indicator_color2  clrDimGray
#property indicator_color3  clrDimGray
#property indicator_color4  clrDeepSkyBlue
#property indicator_color5  clrPaleVioletRed
#property indicator_color6  clrPaleVioletRed
#property indicator_width4  2
#property indicator_width5  2
#property indicator_width6  2
#property indicator_style3  STYLE_DOT

//
//
//
//
//

#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; // Time frame to use
extern string          ForSymbol              = "";
extern double          FastCycles             = 0.5;
extern int             FastFilter             = 1.0;
extern double          SlowCycles             = 1.0;
extern int             SlowFilter             = 1.0;
extern enPrices        AppliedPrice           = 0;              // Price to use
extern int             DzLookBackBars         = 35;
extern double          DzStartBuyProbability  = 0.90;
extern double          DzStartSellProbability = 0.90;
extern bool            arrowsVisible          = false;
extern bool            arrowsOnFirst          = false;
extern bool            arrowsShowBreakOut     = true;
extern bool            arrowsShowRetrace      = true;
extern string          arrowsIdentifier       = "dz pa macd arrows";
extern double          arrowsUpperGap         = 0.5;
extern double          arrowsLowerGap         = 0.5;
extern color           arrowsUpColor          = clrLimeGreen;
extern color           arrowsDnColor          = clrRed;
extern int             arrowsUpCode           = 241;
extern int             arrowsDnCode           = 242;
extern bool            alertsOn               = true;
extern bool            alertsOnCurrent        = false;
extern bool            alertsMessage          = true;
extern bool            alertsSound            = false;
extern bool            alertsNotify           = false;
extern bool            alertsEmail            = false;
extern string          soundFile              = "alert2.wav";
extern bool            Interpolate            = true;
extern bool            drawDots               = false;

//
//
//
//
//

double buffer1[];
double buffer2[];
double buffer3[];
double bbMacd[];
double buffer4[];
double buffer5[];
double trendSlope[];
double trendValue[];
string indicatorFileName;
bool   returnBars;


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

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0, buffer1);
   SetIndexBuffer(1, buffer2);
   SetIndexBuffer(2, buffer3);
   SetIndexBuffer(3, bbMacd);
   SetIndexBuffer(4, buffer4);
   SetIndexBuffer(5, buffer5);
   SetIndexBuffer(6, trendSlope);
   SetIndexBuffer(7, trendValue);
      if (drawDots) 
      {
         SetIndexStyle(3, DRAW_ARROW); SetIndexArrow(3, 159);
         SetIndexStyle(4, DRAW_ARROW); SetIndexArrow(4, 159);
         SetIndexStyle(5, DRAW_NONE);
      }
      else
      {
         SetIndexStyle(3, DRAW_LINE);
         SetIndexStyle(4, DRAW_LINE);
         SetIndexStyle(5, DRAW_LINE);
      }

      //
      //
      //
      //
      //
      
            indicatorFileName = WindowExpertName();
            returnBars        = TimeFrame==-99;
            TimeFrame         = MathMax(TimeFrame,_Period);
      
      //
      //
      //
      //
      //
         
   IndicatorDigits(5);
   if (ForSymbol=="") ForSymbol = Symbol();
   IndicatorShortName(ForSymbol+" "+timeFrameToString(TimeFrame)+" PA Macd (" + DoubleToStr(FastCycles,2) + "," + DoubleToStr(SlowCycles,2) + "," + DzLookBackBars+")");
      SetIndexLabel(0, "Upperband");
      SetIndexLabel(1, "Lowerband");  
      SetIndexLabel(2, "Macd");
      SetIndexLabel(3, NULL);
      SetIndexLabel(4, NULL);
   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);
}

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

double work[][2];

int start()
{
   int i,r,limit,counted_bars = IndicatorCounted();

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
       limit = MathMin(Bars - counted_bars,Bars-1);
       if (returnBars) { buffer1[0] = limit+1; return(0); }


   //
   //
   //
   //
   //

   if (ForSymbol == Symbol() && TimeFrame == Period()) 
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      if (!drawDots) if (trendSlope[limit]==-1) CleanPoint(limit,buffer4,buffer5);
      
      //
      //
      //
      //
      //
      
      for(i = limit,r=Bars-i-1; i >= 0 ; i--,r++)
      {
         double price  = getPrice(AppliedPrice,Open,Close,High,Low,i);
         double alphaf = 2.0 / (1.0 + iHilbertPhase(price,FastFilter,FastCycles,i,0));
         double alphas = 2.0 / (1.0 + iHilbertPhase(price,SlowFilter,SlowCycles,i,1));
   
            if (r<=1)
               {
                  work[r][0] = price;
                  work[r][1] = price;
                  continue;
               }
            
         work[r][0] = work[r-1][0]+alphaf*(price-work[r-1][0]);
         work[r][1] = work[r-1][1]+alphas*(price-work[r-1][1]);
         bbMacd[i]  = work[r][0]-work[r][1];
         
         //
         //
         //
         //
         //
         
         if (DzStartBuyProbability >0) buffer1[i] = dzBuyP (bbMacd, DzStartBuyProbability,  DzLookBackBars, Bars, i, 0.0001);
         if (DzStartSellProbability>0) buffer2[i] = dzSellP(bbMacd, DzStartSellProbability, DzLookBackBars, Bars, i, 0.0001);
                                       buffer3[i] = dzSellP(bbMacd, 0.5                   , DzLookBackBars, Bars, i, 0.0001);
         
         buffer4[i]    = EMPTY_VALUE;
         buffer5[i]    = EMPTY_VALUE;
         trendSlope[i] = trendSlope[i+1];
         trendValue[i] = trendValue[i+1];
            if (bbMacd[i]>bbMacd[i+1])                        trendSlope[i] =  1;
            if (bbMacd[i]<bbMacd[i+1])                        trendSlope[i] = -1;
            if (bbMacd[i]>buffer1[i])                         trendValue[i] =  1;
            if (bbMacd[i]<buffer2[i])                         trendValue[i] = -1;
            if (bbMacd[i]<buffer1[i] && bbMacd[i]>buffer2[i]) trendValue[i] =  0;
            if (trendSlope[i]==-1)
               if (drawDots)     buffer4[i] = bbMacd[i];
               else  PlotPoint(i,buffer4,buffer5,bbMacd);
         
            
            
            //
            //
            //
            //
            //
            
            if (arrowsVisible && ForSymbol==Symbol())
            {
               ObjectDelete(arrowsIdentifier+":"+Time[i]);
               if (trendValue[i]!=trendValue[i+1])
               {
                 if (arrowsShowBreakOut && trendValue[i] == 1)                        drawArrow(i,arrowsUpColor,arrowsUpCode,false);
                 if (arrowsShowBreakOut && trendValue[i] ==-1)                        drawArrow(i,arrowsDnColor,arrowsDnCode,true);
                 if (arrowsShowRetrace  && trendValue[i] == 0 && trendValue[i+1]== 1) drawArrow(i,arrowsDnColor,arrowsDnCode,true);
                 if (arrowsShowRetrace  && trendValue[i] == 0 && trendValue[i+1]==-1) drawArrow(i,arrowsUpColor,arrowsUpCode,false);
               }
            }
      }
      
      //
      //
      //
      //
      //
      
      if (alertsOn)
      {
        if (alertsOnCurrent)
             int whichBar = 0;
        else     whichBar = 1; 
        if (trendValue[whichBar] != trendValue[whichBar+1])
        {
           if (trendValue[whichBar] == 1)                               doAlert(whichBar,"up");
           if (trendValue[whichBar] ==-1)                               doAlert(whichBar,"down");
           if (trendValue[whichBar] == 0 && trendValue[whichBar+1]== 1) doAlert(whichBar,"back from up into zone");
           if (trendValue[whichBar] ==-0 && trendValue[whichBar+1]==-1) doAlert(whichBar,"back from down into zone");
        }         
      }
      return(0);
   }      

   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(ForSymbol,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   if (!drawDots) if (trendSlope[limit]==-1) CleanPoint(limit,buffer4,buffer5);
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(ForSymbol,TimeFrame,Time[i]);
         buffer1[i]    = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,AppliedPrice,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,0,y);
         buffer2[i]    = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,AppliedPrice,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,1,y);
         buffer3[i]    = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,AppliedPrice,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,2,y);
         bbMacd[i]     = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,AppliedPrice,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,3,y);
         trendSlope[i] = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,AppliedPrice,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,6,y);
         buffer4[i]    = EMPTY_VALUE;
         buffer5[i]    = EMPTY_VALUE;
            
         if (drawDots && trendSlope[i]==-1) buffer4[i] = bbMacd[i];
            
         //
         //
         //
         //
         //
      
         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 k = 1; k < n; k++)
            {
               bbMacd[i+k]  = bbMacd[i]  + (bbMacd[i+n] -bbMacd[i]) * k/n;
               buffer1[i+k] = buffer1[i] + (buffer1[i+n]-buffer1[i])* k/n;
               buffer2[i+k] = buffer2[i] + (buffer2[i+n]-buffer2[i])* k/n;
               if (buffer4[i+k] != EMPTY_VALUE) buffer4[i+k] = bbMacd[i+k];
            }               
   }
   if (!drawDots) for (i=limit;i>=0;i--) if (trendSlope[i]==-1) PlotPoint(i,buffer4,buffer5,bbMacd);
return(0);
}

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

double workHil[][18];
#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 filter, 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.0-workHil[r][s+_phase];
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 180.0+workHil[r][s+_phase];
         if (workHil[r][s+_I1]>0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 360.0-workHil[r][s+_phase];

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

         if (workHil[r-1][s+_phase]<90.0 && workHil[r][s+_phase]>270.0)
             workHil[r][s+_deltaPhase] = 360.0+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(filter,1));
            double phaseSum = 0; for (int k=0; phaseSum<cyclesToReach*360.0 && (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);
}

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

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("");
}

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = 3.0*iATR(NULL,0,20,i)/4.0;   
   int    add  = 0; if (!arrowsOnFirst) add = _Period*60-1;
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i]+add,0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i]+ arrowsUpperGap * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i] - arrowsLowerGap * gap);
}

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

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)," Dynamic zones pa Macd ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Dynamic zones pa Macd "),message);
             if (alertsNotify)  SendNotification(message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

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

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i]   = 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 (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;
      }
}
