//------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-station.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 8
#property indicator_color1  clrSilver
#property indicator_color2  clrDeepSkyBlue
#property indicator_color3  clrDeepSkyBlue
#property indicator_color4  clrSandyBrown
#property indicator_color5  clrSandyBrown
#property indicator_color6  clrLimeGreen
#property indicator_color7  clrRed
#property indicator_color8  clrDimGray
#property indicator_width1  3
#property indicator_width2  3
#property indicator_width3  3
#property indicator_width4  3
#property indicator_width5  3
#property indicator_style6  STYLE_DOT
#property indicator_style7  STYLE_DOT
#property indicator_style8  STYLE_DOT
#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

//
//
//
//
//

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
};
enum enMode
{
   mo_cls,  // Color change on slope
   mo_cl1,  // Color change on levels break into the zones
   mo_cl2,  // Color change on levels break - trend direction
   mo_cl3   // Color change on levels break - counter trend direction
};

extern int                rperiod                  = 25;             // Calculating period
extern enPrices           rprice                   = pr_close;       // Price
extern int                speriod                  = 14;             // Smoothing period
extern ENUM_MA_METHOD     smethod                  = MODE_SMA;       // Smoothing method
extern double             fastr                    =  8;             // Fast ratio
extern double             slowr                    = 22;             // Slow ratio
extern int                DzLookBackBars           = 35;             // dynamic zones lookback
extern double             DzStartBuyProbability    = 0.90;           // dynamic upper zone
extern double             DzStartSellProbability   = 0.90;           // dynamic lower zone
extern enMode             alertsLinesOnSlope       = mo_cls;         // Alerts and lines should be on?
extern bool               verticalLinesVisible     = false;          // Show vertical lines
extern string             verticalLinesID          = "RSID Lines1";  // Vertical lines unique ID
extern color              verticalLinesUpColor     = clrDeepSkyBlue; // Color for down cross
extern color              verticalLinesDownColor   = clrSandyBrown;  // Color for up cross
extern ENUM_LINE_STYLE    verticalLinesStyle       = STYLE_DOT;      // Lines style
extern int                verticalLinesWidth       = 0;              // Lines width
extern bool               alertsOn                 = false;          // Turn alerts on?
extern bool               alertsOnCurrent          = true;           // Alerts on current (still opened) bar
extern bool               alertsMessage            = true;           // Alerts should show pop-up message
extern bool               alertsSound              = false;          // Alerts should play alert sound
extern bool               alertsPushNotif          = false;          // Alerts should send push notification
extern bool               alertsEmail              = false;          // Alerts should send email
extern int                linesWidth               =  3;             // Lines width

double buffer[];
double bufferda[];
double bufferdb[];
double bufferua[];
double bufferub[];
double buffer1[];
double buffer2[];
double buffer3[];
double trend[];
double work[];

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(10);
   SetIndexBuffer(0,buffer,  INDICATOR_DATA); SetIndexStyle(0,EMPTY,EMPTY,linesWidth);
   SetIndexBuffer(1,bufferua,INDICATOR_DATA); SetIndexStyle(1,EMPTY,EMPTY,linesWidth);
   SetIndexBuffer(2,bufferub,INDICATOR_DATA); SetIndexStyle(2,EMPTY,EMPTY,linesWidth);
   SetIndexBuffer(3,bufferda,INDICATOR_DATA); SetIndexStyle(3,EMPTY,EMPTY,linesWidth);
   SetIndexBuffer(4,bufferdb,INDICATOR_DATA); SetIndexStyle(4,EMPTY,EMPTY,linesWidth);
   SetIndexBuffer(5,buffer1, INDICATOR_DATA);
   SetIndexBuffer(6,buffer2, INDICATOR_DATA);
   SetIndexBuffer(7,buffer3, INDICATOR_DATA);
   SetIndexBuffer(8,trend   ,INDICATOR_CALCULATIONS);
   SetIndexBuffer(9,work    ,INDICATOR_CALCULATIONS);
      
   IndicatorShortName("dz rsx digital Kahler ("+(string)rperiod+","+(string)speriod+")");
   return(0);
}
int deinit() 
{ 
   string lookFor       = verticalLinesID+":";
   int    lookForLength = StringLen(lookFor);
      for (int i=ObjectsTotal()-1; i>=0; i--)
      {
         string name = ObjectName(i);
         if (StringSubstr(name,0,lookForLength) == lookFor) ObjectDelete(name);
      }
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//


double wrkBuffer[][13];

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-1);

   //
   //
   //
   //
   //


   if (ArrayRange(wrkBuffer,0) != Bars) ArrayResize(wrkBuffer,Bars);
   if (trend[limit]==-1) CleanPoint(limit,bufferda,bufferdb);
   if (trend[limit]== 1) CleanPoint(limit,bufferua,bufferub);
   for(int i=limit, r = Bars-i-1; i>=0; i--,r++) 
   {
       if (i==(Bars-1)) { for (int c=0; c<12; c++) wrkBuffer[r][c] = 0; continue; }  
       wrkBuffer[r][12] = getPrice(rprice,Open,Close,High,Low,i);
            double noise = 0, vhf = 0;
            double max   = wrkBuffer[r][12];
            double min   = wrkBuffer[r][12];
            for (int k=0; k<rperiod && (r-k-1)>=0; k++)
            {
               noise += MathAbs(wrkBuffer[r-k][12]-wrkBuffer[r-k-1][12]);
               max    = MathMax(wrkBuffer[r-k][12],max);   
               min    = MathMin(wrkBuffer[r-k][12],min);   
            }      
            if (noise>0) vhf = (max-min)/noise;
            double period = MathMax(-MathLog(vhf)*rperiod,3); 
            double Kg     = (3.0)/(2.0+period); 
            double Hg     = 1.0-Kg;


      //
      //
      //
      //
      //
      
         double roc = wrkBuffer[r][12]-wrkBuffer[r-1][12];
         double roa = MathAbs(roc);
         for (int k=0; k<3; k++)
         {
            int kk = k*2;
               wrkBuffer[r][kk+0] = Kg*roc                + Hg*wrkBuffer[r-1][kk+0];
               wrkBuffer[r][kk+1] = Kg*wrkBuffer[r][kk+0] + Hg*wrkBuffer[r-1][kk+1]; roc = 1.5*wrkBuffer[r][kk+0] - 0.5 * wrkBuffer[r][kk+1];
               wrkBuffer[r][kk+6] = Kg*roa                + Hg*wrkBuffer[r-1][kk+6];
               wrkBuffer[r][kk+7] = Kg*wrkBuffer[r][kk+6] + Hg*wrkBuffer[r-1][kk+7]; roa = 1.5*wrkBuffer[r][kk+6] - 0.5 * wrkBuffer[r][kk+7];
         }
         if (roa != 0)
                work[i] = MathMax(MathMin((roc/roa+1.0)*50.0,100.00),0.00); 
         else   work[i] = 50.0;
         double fast_k  = work[i];
         double slow_k  = iMAOnArray(work,0,speriod,0,smethod,i);
         double temp    = 0;
         
         //
         //
         //
         //
         //
         
         if ((slowr*slow_k+fastr*fast_k)/(fastr+slowr)>50.0) temp= 1;
         if ((slowr*slow_k+fastr*fast_k)/(fastr+slowr)<50.0) temp=-1;
            buffer[i]   = iEma(temp,rperiod,i);
                
            if (DzStartBuyProbability >0) buffer1[i] = dzBuyP (buffer, DzStartBuyProbability,  DzLookBackBars, Bars, i, 0.0001);
            if (DzStartSellProbability>0) buffer2[i] = dzSellP(buffer, DzStartSellProbability, DzLookBackBars, Bars, i, 0.0001);
                                          buffer3[i] = dzSellP(buffer, 0.5                   , DzLookBackBars, Bars, i, 0.0001);
            bufferda[i] = EMPTY_VALUE;
            bufferdb[i] = EMPTY_VALUE;
            bufferua[i] = EMPTY_VALUE;
            bufferub[i] = EMPTY_VALUE;
            trend[i]    = 0;
      
         //
         //
         //
         //
         //

         if (i<Bars-1)
         {         
            switch (alertsLinesOnSlope)
            {
               case mo_cls: 
                  trend[i] = trend[i+1];
                     if (buffer[i]>buffer[i+1]) trend[i] =  1;
                     if (buffer[i]<buffer[i+1]) trend[i] = -1;
                     break;
               case mo_cl1: 
                     if (buffer[i]>buffer2[i]) trend[i] =  1; //levelup
                     if (buffer[i]<buffer1[i]) trend[i] = -1; //leveldown
                     break;
               case mo_cl2: 
                  trend[i] = trend[i+1];
                     if (buffer[i]>buffer2[i]) trend[i] =  1;
                     if (buffer[i]<buffer1[i]) trend[i] = -1;
                     break;
               case mo_cl3: 
                  trend[i] = trend[i+1];
                     if (buffer[i]<buffer2[i] && buffer[i+1]>buffer2[i]) trend[i] = -1;
                     if (buffer[i]>buffer1[i] && buffer[i+1]<buffer1[i]) trend[i] =  1;
               }                     
            if (trend[i] == -1) PlotPoint(i,bufferda,bufferdb,buffer);
            if (trend[i] ==  1) PlotPoint(i,bufferua,bufferub,buffer);
         }
         manageLines(i);
   }      
   manageAlerts();
   return(0);
}


//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] ==  1) doAlert(whichBar,"up");
         if (trend[whichBar] == -1) doAlert(whichBar,"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 =  Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" dz RSX digital Kahler trend changed to "+doWhat;
          if (alertsMessage)   Alert(message);
          if (alertsEmail)     SendMail(Symbol()+" dz RSX digital Kahler",message);
          if (alertsPushNotif) SendNotification(message);
          if (alertsSound)     PlaySound("alert2.wav");
   }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageLines(int i)
{
   if (verticalLinesVisible && (i+1)<Bars)
   {
         ObjectDelete(verticalLinesID+":"+(string)Time[i]);
         if (trend[i]!=trend[i+1])
         {
            if (trend[i] == 1) drawLine(i,verticalLinesUpColor);
            if (trend[i] ==-1) drawLine(i,verticalLinesDownColor);
         }
   }
}               

void drawLine(int i,color theColor)
{
   string name = verticalLinesID+":"+(string)Time[i];
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_VLINE,0,Time[i],0);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         ObjectSet(name,OBJPROP_STYLE,verticalLinesStyle);
         ObjectSet(name,OBJPROP_WIDTH,verticalLinesWidth);
         ObjectSet(name,OBJPROP_BACK,true);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workEma[][1];
double iEma(double tprice, double eperiod, int r, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= Bars) ArrayResize(workEma,Bars); r = Bars-r-1;

   //
   //
   //
   //
   //
      
   double alpha = 2.0 / (1.0+eperiod);
   if (r==0)
          workEma[r][instanceNo] = tprice;
   else   workEma[r][instanceNo] = workEma[r-1][instanceNo]+alpha*(tprice-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//
//

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-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; }
}