#property copyright "www,forex-station.com"
#property link      "www,forex-station.com"

#property indicator_separate_window
#property indicator_buffers 6
#property indicator_color1  Gold
#property indicator_color2  DeepSkyBlue
#property indicator_color3  DeepSkyBlue
#property indicator_color4  PaleVioletRed
#property indicator_color5  PaleVioletRed
#property indicator_color6  DarkSlateGray
#property indicator_style3  STYLE_DOT
#property indicator_style4  STYLE_DOT
#property indicator_style6  STYLE_DASH
#property indicator_width1  2
#property indicator_width2  0
#property indicator_width5  0

//
//
//
//
//

#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

//
//
//
//
//

extern string TimeFrame                 = "Current time frame";
extern int    PcciSmoothLength          = 10;
extern double PcciSmoothPhase           = 0;
extern bool   PcciSmoothDouble          = true;
extern int    PcciPrice                 = PRICE_CLOSE;
extern int    DzLookBackBars            = 70;
extern double DzStartBuyProbability1    = 0.025;
extern double DzStartBuyProbability2    = 0.10;
extern double DzStartSellProbability1   = 0.025;
extern double DzStartSellProbability2   = 0.10;
extern bool   divergenceVisible         = true;
extern bool   divergenceOnValuesVisible = true;
extern bool   divergenceOnChartVisible  = false;
extern color  divergenceBullishColor    = Chartreuse;
extern color  divergenceBearishColor    = DarkOrange;
extern string divergenceUniqueID        = "Jurik pcci diverge1";
extern bool   Interpolate               = true;

extern bool   alertsOn                  = false;
extern bool   alertsOnZLCross           = true;
extern bool   alertsOnUpLevel1Cross     = true;
extern bool   alertsOnUpLevel2Cross     = true;
extern bool   alertsOnDnLevel1Cross     = true;
extern bool   alertsOnDnLevel2Cross     = true;
extern bool   alertsOnCurrent           = false;
extern bool   alertsMessage             = true;
extern bool   alertsSound               = false;
extern bool   alertsEmail               = false;

extern bool   arrowsVisible             = false;
extern string arrowsIdentifier          = "Dz Pcci Arrows1";
extern double arrowsDisplacement        = 1.0;
extern color  arrowsUpColor             = DeepSkyBlue;
extern color  arrowsDnColor             = PaleVioletRed;
extern bool   arrowsOnZLCross           = true;
extern bool   arrowsOnUpLevel1Cross     = true;
extern bool   arrowsOnUpLevel2Cross     = true;
extern bool   arrowsOnDnLevel1Cross     = true;
extern bool   arrowsOnDnLevel2Cross     = true;

//
//
//
//
//

double pcci[];
double bl1[];
double bl2[];
double sl2[];
double sl1[];
double zli[];
double price[];

double trends[][5];
#define _tmi  0
#define _tup1 1
#define _tup2 2
#define _tdn1 3
#define _tdn2 4

//
//
//
//
//

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;
string shortName;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

int init()
  {
  IndicatorBuffers(7);
    SetIndexBuffer(0,pcci);
    SetIndexBuffer(1,bl1);
    SetIndexBuffer(2,bl2);
    SetIndexBuffer(3,sl2);
    SetIndexBuffer(4,sl1);
    SetIndexBuffer(5,zli);
    SetIndexBuffer(6,price);
  
    //
    //
    //
    //
    //
   
      indicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      calculateValue    = (TimeFrame=="calculateValue");
      if (calculateValue)
      {
         int s = StringFind(divergenceUniqueID,":",0);
               shortName = divergenceUniqueID;
               divergenceUniqueID = StringSubstr(divergenceUniqueID,0,s);
               return(0);
      }            
      timeFrame = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //
      
      shortName = divergenceUniqueID+": "+timeFrameToString(timeFrame)+ "  Dynamic zone jurik pcci";
   IndicatorShortName(shortName);
return(0);
}

//
//
//
//
//
   
int deinit()
{
   
   int lookForLength = StringLen(divergenceUniqueID);
   
   for (int i=ObjectsTotal()-1; i>=0; i--) {
   
   string objectName = ObjectName(i);
   if (StringSubstr(objectName,0,lookForLength) == divergenceUniqueID) ObjectDelete(objectName);
   
   }
   
   if (!calculateValue && arrowsVisible) deleteArrows();
   
return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,n,k,r,limit;
   
   if(counted_bars < 0) return(-1);
   if(counted_bars > 0) counted_bars--;
           limit = MathMin(Bars-counted_bars,Bars-1); 
           if (returnBars)  { pcci[0] = limit+1; return(0); }
   
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {     
      
      for(i=limit, r=Bars-i-1; i>=0; i--, r++)
      { 
          if (ArrayRange(trends,0)!=Bars) ArrayResize(trends,Bars);  
           
          price[i] = iMA(NULL,0,1,0,MODE_SMA,PcciPrice,i);
            
          double response =
           
          0.1177628838235*price[i]
         +0.1170077388431*price[i+1]
         +0.1147601209029*price[i+2]
         +0.1110729054065*price[i+3]
         +0.1060324421434*price[i+4]
         +0.0997560988008*price[i+5]
         +0.0923890376402*price[i+6]
         +0.0841000389219*price[i+7]
         +0.0750766919597*price[i+8]
         +0.0655202662708*price[i+9]
         +0.0556401583046*price[i+10]
         +0.0456482572592*price[i+11]
         +0.0357530528012*price[i+12]
         +0.02615415804227*price[i+13]
         +0.01703731282680*price[i+14]
         +0.00856960311288*price[i+15]
         +0.000895555708556*price[i+16]
         -0.00586627422066*price[i+17]
         -0.01162552971203*price[i+18]
         -0.01632152444323*price[i+19]
         -0.01992414580732*price[i+20]
         -0.02243335117589*price[i+21]
         -0.02387813894599*price[i+22]
         -0.02431430200598*price[i+23]
         -0.02382176331725*price[i+24]
         -0.02250140527159*price[i+25]
         -0.02047075493180*price[i+26]
         -0.01786000052706*price[i+27]
         -0.01480733499641*price[i+28]
         -0.01145463232852*price[i+29]
         -0.00794304696010*price[i+30]
         -0.00440829083275*price[i+31]
         -0.000977238472653*price[i+32]
         +0.002235823933755*price[i+33]
         +0.00513191787383*price[i+34]
         +0.00762972457736*price[i+35]
         +0.00966747623918*price[i+36]
         +0.01120310303187*price[i+37]
         +0.01221499285956*price[i+38]
         +0.01270127547603*price[i+39]
         +0.01267881242200*price[i+40]
         +0.01218165493397*price[i+41]
         +0.01125820035359*price[i+42]
         +0.00996954486984*price[i+43]
         +0.00838605323109*price[i+44]
         +0.00658436935337*price[i+45]
         +0.00464439195323*price[i+46]
         +0.002645759417416*price[i+47]
         +0.000666068159555*price[i+48]
         -0.001222776729259*price[i+49]
         -0.002956488520058*price[i+50]
         -0.00448011021214*price[i+51]
         -0.00574988855361*price[i+52]
         -0.00673332989225*price[i+53]
         -0.00741117882839*price[i+54]
         -0.00777644547070*price[i+55]
         -0.00783388153265*price[i+56]
         -0.00759966748743*price[i+57]
         -0.00709931269272*price[i+58]
         -0.00636769053766*price[i+59]
         -0.00544559940274*price[i+60]
         -0.00437852874428*price[i+61]
         -0.00321542503890*price[i+62]
         -0.002005580069262*price[i+63]
         -0.000798178859997*price[i+64]
         +0.000361723322003*price[i+65]
         +0.001433101593600*price[i+66]
         +0.002380073229874*price[i+67]
         +0.00317453700490*price[i+68]
         +0.00379492177651*price[i+69]
         +0.00422884523807*price[i+70]
         +0.00447038314289*price[i+71]
         +0.00452100306476*price[i+72]
         +0.00439082398691*price[i+73]
         +0.00409492037175*price[i+74]
         +0.00365528338580*price[i+75]
         +0.003096238149856*price[i+76]
         +0.002446112685573*price[i+77]
         +0.001736376831290*price[i+78]
         +0.000996103380422*price[i+79]
         +0.0002557237615143*price[i+80]
         -0.000458282529397*price[i+81]
         -0.001119581482823*price[i+82]
         -0.001704893115208*price[i+83]
         -0.002199032152313*price[i+84]
         -0.002586916898054*price[i+85]
         -0.002861741841535*price[i+86]
         -0.003018651749353*price[i+87]
         -0.003060101508137*price[i+88]
         -0.002997112675297*price[i+89]
         -0.002834938217095*price[i+90]
         -0.002589089321820*price[i+91]
         -0.002272072078644*price[i+92]
         -0.001902835889698*price[i+93]
         -0.001502872027811*price[i+94]
         -0.001077466851623*price[i+95]
         -0.000655481642188*price[i+96]
         -0.0002511660753314*price[i+97]
         +0.0001137882502083*price[i+98]
         +0.000426098842482*price[i+99]
         +0.000714775119642*price[i+100]
         +0.000916639580735*price[i+101]
         +0.001063116482197*price[i+102]
         +0.001143113996535*price[i+103]
         +0.001159315803654*price[i+104]
         +0.00922554212244*price[i+105]; 
         
         //
         //
         //
         //
         //
         
         pcci[i] = iDSmooth(price[i]-response,PcciSmoothLength,PcciSmoothPhase,PcciSmoothDouble,i); 
         
         if (DzStartBuyProbability1  > 0) bl1[i] = dzBuyP (pcci, DzStartBuyProbability1,  DzLookBackBars, Bars, i, 0.0001);
         if (DzStartBuyProbability2  > 0) bl2[i] = dzBuyP (pcci, DzStartBuyProbability2,  DzLookBackBars, Bars, i, 0.0001);
         if (DzStartSellProbability1 > 0) sl1[i] = dzSellP(pcci, DzStartSellProbability1, DzLookBackBars, Bars, i, 0.0001);
         if (DzStartSellProbability2 > 0) sl2[i] = dzSellP(pcci, DzStartSellProbability2, DzLookBackBars, Bars, i, 0.0001);
                                          zli[i] = dzSellP(pcci, 0.5                    , DzLookBackBars, Bars, i, 0.0001);
                                          
         setTrends(i,r);
         manageArrow(i,r);
                                          
         if (divergenceVisible)
         {
            CatchBullishDivergence(pcci,i);
            CatchBearishDivergence(pcci,i);
         }         
                                          
         
         
         }
         
         manageAlerts();
         return(0);
         }       
             
         //
         //
         //
         //
         //
             
         limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
         
         if (ArrayRange(trends,0)!=Bars) ArrayResize(trends,Bars);
             
         for(i=limit, r=Bars-i-1; i>=0; i--, r++)
         {
         
            int y = iBarShift(NULL,timeFrame,Time[i]);
                pcci[i]= iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PcciSmoothLength,PcciSmoothPhase,PcciSmoothDouble,PcciPrice,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,0,y);
                bl1[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PcciSmoothLength,PcciSmoothPhase,PcciSmoothDouble,PcciPrice,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,1,y);
                bl2[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PcciSmoothLength,PcciSmoothPhase,PcciSmoothDouble,PcciPrice,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,2,y);
                sl2[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PcciSmoothLength,PcciSmoothPhase,PcciSmoothDouble,PcciPrice,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,3,y);
                sl1[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PcciSmoothLength,PcciSmoothPhase,PcciSmoothDouble,PcciPrice,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,4,y);
                zli[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PcciSmoothLength,PcciSmoothPhase,PcciSmoothDouble,PcciPrice,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,5,y);
                
                setTrends(i,r);
                manageArrow(i,r);
                
                //
                //
                //
                //
                //
        
                if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
      
                //
                //
                //
                //
                //

                datetime time = iTime(NULL,timeFrame,y);
                   for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
                   for(k = 1; k < n; k++)
                   {
                       pcci[i+k]= pcci[i]+ (pcci[i+n]- pcci[i]) * k/n;
                       bl1[i+k] = bl1[i] + (bl1[i+n] - bl1[i])  * k/n;
                       bl2[i+k] = bl2[i] + (bl2[i+n] - bl2[i])  * k/n;
                       sl2[i+k] = sl2[i] + (sl2[i+n] - sl2[i])  * k/n;
                       sl1[i+k] = sl1[i] + (sl1[i+n] - sl1[i])  * k/n;
                       zli[i+k] = zli[i] + (zli[i+n] - zli[i])  * k/n;
                   }
        }
        
manageAlerts();
              
return(0);
}

//+------------------------------------------------------------------+
//
//
//
//

double wrk[][20];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iDSmooth(double tprice, double length, double phase, bool isDouble, int i, int s=0)
{
   if (isDouble)
         return (iSmooth(iSmooth(tprice,MathSqrt(length),phase,i,s),MathSqrt(length),phase,i,s+10));
   else  return (iSmooth(tprice,length,phase,i,s));
}

//
//
//
//
//

double iSmooth(double tprice, double length, double phase, int i, int s=0)
{
   if (length <=1) return(tprice);
   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]=tprice; for(; k<10; k++) wrk[r][k+s]=0; return(tprice); }

   //
   //
   //
   //
   //
   
      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   = tprice - wrk[r-1][bsmax+s];
      double del2   = tprice - 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] = tprice; else wrk[r][bsmax+s] = tprice - Kv*del1;
         if (del2 < 0) wrk[r][bsmin+s] = tprice; else wrk[r][bsmin+s] = tprice - 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] = tprice + alpha*(wrk[r-1][0+s]-tprice);
         wrk[r][1+s] = (tprice - 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 setTrends(int i, int r)
{
   trends[r][_tmi]  = trends[r-1][_tmi];
   trends[r][_tup1] = trends[r-1][_tup1];
   trends[r][_tup2] = trends[r-1][_tup2];
   trends[r][_tdn1] = trends[r-1][_tdn1];
   trends[r][_tdn2] = trends[r-1][_tdn2];
   
      if (pcci[i] > zli[i]) trends[r][_tmi]  =  1;
      if (pcci[i] < zli[i]) trends[r][_tmi]  = -1;
      if (pcci[i] > bl1[i]) trends[r][_tdn2] =  1;
      if (pcci[i] < bl1[i]) trends[r][_tdn2] = -1;
      if (pcci[i] > bl2[i]) trends[r][_tdn1] =  1;
      if (pcci[i] < bl2[i]) trends[r][_tdn1] = -1;
      if (pcci[i] > sl1[i]) trends[r][_tup2] =  1;
      if (pcci[i] < sl1[i]) trends[r][_tup2] = -1;
      if (pcci[i] > sl2[i]) trends[r][_tup1] =  1;
      if (pcci[i] < sl2[i]) trends[r][_tup1] = -1;
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar)); 
                             whichBar = Bars-whichBar-1;

      //
      //
      //
      //
      //
            
      static datetime time1 = 0;
      static string   mess1 = "";
      if (alertsOnUpLevel1Cross && trends[whichBar][_tup1] != trends[whichBar-1][_tup1])
      {
         if (trends[whichBar][_tup1] ==  1) doAlert(time1,mess1,whichBar,"crossed upper line 1 up");
         if (trends[whichBar][_tup1] == -1) doAlert(time1,mess1,whichBar,"crossed upper line 1 down");
      }
      static datetime time2 = 0;
      static string   mess2 = "";
      if (alertsOnUpLevel2Cross && trends[whichBar][_tup2] != trends[whichBar-1][_tup2])
      {
         if (trends[whichBar][_tup2] ==  1) doAlert(time2,mess2,whichBar,"crossed upper line 2 up");
         if (trends[whichBar][_tup2] == -1) doAlert(time2,mess2,whichBar,"crossed upper line 2 down");
      }
      static datetime time3 = 0;
      static string   mess3 = "";
      if (alertsOnDnLevel1Cross && trends[whichBar][_tdn1] != trends[whichBar-1][_tdn1])
      {
         if (trends[whichBar][_tdn1] ==  1) doAlert(time3,mess3,whichBar,"crossed lower line 1 up");
         if (trends[whichBar][_tdn1] == -1) doAlert(time3,mess3,whichBar,"crossed lower line 1 down");
      }
      static datetime time4 = 0;
      static string   mess4 = "";
      if (alertsOnDnLevel2Cross && trends[whichBar][_tdn2] != trends[whichBar-1][_tdn2])
      {
         if (trends[whichBar][_tdn2] ==  1) doAlert(time4,mess4,whichBar,"crossed lower line 2 up");
         if (trends[whichBar][_tdn2] == -1) doAlert(time4,mess4,whichBar,"crossed lower line 2 down");
      }
      static datetime time5 = 0;
      static string   mess5 = "";
      if (alertsOnZLCross && trends[whichBar][_tmi] != trends[whichBar-1][_tmi])
      {
         if (trends[whichBar][_tmi] ==  1) doAlert(time5,mess5,whichBar,"crossed zero line up");
         if (trends[whichBar][_tmi] == -1) doAlert(time5,mess5,whichBar,"crossed zero line down");
      }
   }
}

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, int forBar, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," DZ pcci ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," DZ pcci "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void manageArrow(int i, int r)
{
   if (!calculateValue && arrowsVisible)
   {
      deleteArrow(Time[i]);
      if (arrowsOnUpLevel1Cross && trends[r][_tup1]!=trends[r-1][_tup1])
      {
         if (trends[r][_tup1] == 1) drawArrow(i,arrowsUpColor,241,false);
         if (trends[r][_tup1] ==-1) drawArrow(i,arrowsDnColor,242,true);
      }
      if (arrowsOnUpLevel2Cross && trends[r][_tup2]!=trends[r-1][_tup2])
      {
         if (trends[r][_tup2] == 1) drawArrow(i,arrowsUpColor,241,false);
         if (trends[r][_tup2] ==-1) drawArrow(i,arrowsDnColor,242,true);
      }
      if (arrowsOnDnLevel1Cross && trends[r][_tdn1]!=trends[r-1][_tdn1])
      {
         if (trends[r][_tdn1] == 1) drawArrow(i,arrowsUpColor,241,false);
         if (trends[r][_tdn1] ==-1) drawArrow(i,arrowsDnColor,242,true);
      }
      if (arrowsOnDnLevel2Cross && trends[r][_tdn2]!=trends[r-1][_tdn2])
      {
         if (trends[r][_tdn2] == 1) drawArrow(i,arrowsUpColor,241,false);
         if (trends[r][_tdn2] ==-1) drawArrow(i,arrowsDnColor,242,true);
      }
      if (arrowsOnZLCross && trends[r][_tmi]!=trends[r-1][_tmi])
      {
         if (trends[r][_tmi] == 1) drawArrow(i,arrowsUpColor,241,false);
         if (trends[r][_tmi] ==-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] + arrowsDisplacement * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i]  - arrowsDisplacement * gap);
}

//
//
//
//
//

void deleteArrows()
{
   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);
   }
}

//
//
//
//
//

void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

void CatchBullishDivergence(double& values[], int i)
{
   i++;
            ObjectDelete(divergenceUniqueID+"l"+DoubleToStr(Time[i],0));
            ObjectDelete(divergenceUniqueID+"l"+"os" + DoubleToStr(Time[i],0));            
   if (!IsIndicatorLow(values,i)) return;  

   //
   //
   //
   //
   //

   int currentLow = i;
   int lastLow    = GetIndicatorLastLow(values,i+1);
      if (values[currentLow] > values[lastLow] && Low[currentLow] < Low[lastLow])
      {
         if(divergenceOnChartVisible)  DrawPriceTrendLine("l",Time[currentLow],Time[lastLow],Low[currentLow],Low[lastLow],divergenceBullishColor,STYLE_SOLID);
         if(divergenceOnValuesVisible) DrawIndicatorTrendLine("l",Time[currentLow],Time[lastLow],values[currentLow],values[lastLow],divergenceBullishColor,STYLE_SOLID);
      }
      if (values[currentLow] < values[lastLow] && Low[currentLow] > Low[lastLow])
      {
         if(divergenceOnChartVisible)  DrawPriceTrendLine("l",Time[currentLow],Time[lastLow],Low[currentLow],Low[lastLow], divergenceBullishColor, STYLE_DOT);
         if(divergenceOnValuesVisible) DrawIndicatorTrendLine("l",Time[currentLow],Time[lastLow],values[currentLow],values[lastLow], divergenceBullishColor, STYLE_DOT);
      }
}

//
//
//
//
//

void CatchBearishDivergence(double& values[], int i)
{
   i++; 
            ObjectDelete(divergenceUniqueID+"h"+DoubleToStr(Time[i],0));
            ObjectDelete(divergenceUniqueID+"h"+"os" + DoubleToStr(Time[i],0));            
   if (IsIndicatorPeak(values,i) == false) return;

   //
   //
   //
   //
   //
      
   int currentPeak = i;
   int lastPeak = GetIndicatorLastPeak(values,i+1);
      if (values[currentPeak] < values[lastPeak] && High[currentPeak]>High[lastPeak])
      {
         if (divergenceOnChartVisible)  DrawPriceTrendLine("h",Time[currentPeak],Time[lastPeak],High[currentPeak],High[lastPeak],divergenceBearishColor,STYLE_SOLID);
         if (divergenceOnValuesVisible) DrawIndicatorTrendLine("h",Time[currentPeak],Time[lastPeak],values[currentPeak],values[lastPeak],divergenceBearishColor,STYLE_SOLID);
      }
      if(values[currentPeak] > values[lastPeak] && High[currentPeak] < High[lastPeak])
      {
         if (divergenceOnChartVisible)  DrawPriceTrendLine("h",Time[currentPeak],Time[lastPeak],High[currentPeak],High[lastPeak], divergenceBearishColor, STYLE_DOT);
         if (divergenceOnValuesVisible) DrawIndicatorTrendLine("h",Time[currentPeak],Time[lastPeak],values[currentPeak],values[lastPeak], divergenceBearishColor, STYLE_DOT);
      }
}

//
//
//
//
//

bool IsIndicatorPeak(double& values[], int i) { return(values[i] >= values[i+1] && values[i] > values[i+2] && values[i] > values[i-1]); }
bool IsIndicatorLow( double& values[], int i) { return(values[i] <= values[i+1] && values[i] < values[i+2] && values[i] < values[i-1]); }

int GetIndicatorLastPeak(double& values[], int shift)
{
   for(int i = shift+5; i<Bars; i++)
         if (values[i] >= values[i+1] && values[i] > values[i+2] && values[i] >= values[i-1] && values[i] > values[i-2]) return(i);
   return(-1);
}
int GetIndicatorLastLow(double& values[], int shift)
{
   for(int i = shift+5; i<Bars; i++)
         if (values[i] <= values[i+1] && values[i] < values[i+2] && values[i] <= values[i-1] && values[i] < values[i-2]) return(i);
   return(-1);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

void DrawPriceTrendLine(string first,datetime t1, datetime t2, double p1, double p2, color lineColor, double style)
{
   string   label = divergenceUniqueID+first+"os"+DoubleToStr(t1,0);
   if (Interpolate) t2 += Period()*60-1;
    
   ObjectDelete(label);
      ObjectCreate(label, OBJ_TREND, 0, t1+Period()*60-1, p1, t2, p2, 0, 0);
         ObjectSet(label, OBJPROP_RAY, false);
         ObjectSet(label, OBJPROP_COLOR, lineColor);
         ObjectSet(label, OBJPROP_STYLE, style);
}
void DrawIndicatorTrendLine(string first,datetime t1, datetime t2, double p1, double p2, color lineColor, double style)
{
   int indicatorWindow = WindowFind(shortName);
   if (indicatorWindow < 0) return;
   if (Interpolate) t2 += Period()*60-1;
   
   string label = divergenceUniqueID+first+DoubleToStr(t1,0);
   ObjectDelete(label);
      ObjectCreate(label, OBJ_TREND, indicatorWindow, t1+Period()*60-1, p1, t2, p2, 0, 0);
         ObjectSet(label, OBJPROP_RAY, false);
         ObjectSet(label, OBJPROP_COLOR, lineColor);
         ObjectSet(label, OBJPROP_STYLE, style);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

//
//
//
//
//

int stringToTimeFrame(string tfs) {
   tfs = stringUpperCase(tfs);
   for (int i=ArraySize(iTfTable)-1; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[i],Period()));
                                                      return(Period());
}

//
//
//
//
//

string timeFrameToString(int tf) {
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//
//
//
//
//

string stringUpperCase(string str) {
   string   s = str;

   for (int length=StringLen(str)-1; length>=0; length--) {
      int tchar = StringGetChar(s, length);
         if((tchar > 96 && tchar < 123) || (tchar > 223 && tchar < 256))
                     s = StringSetChar(s, length, tchar - 32);
         else if(tchar > -33 && tchar < 0)
                     s = StringSetChar(s, length, tchar + 224);
   }
   return(s);
}


