//+------------------------------------------------------------------+
//|                                    kase permision stochastic.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 8
#property indicator_color1  DeepSkyBlue
#property indicator_color2  PaleVioletRed
#property indicator_color3  LimeGreen
#property indicator_color4  LimeGreen
#property indicator_color5  Red
#property indicator_color6  Red
#property indicator_color7  DimGray
#property indicator_color8  DimGray
#property indicator_style2  STYLE_DASH
#property indicator_style4  STYLE_DOT
#property indicator_style6  STYLE_DOT
#property indicator_style7  STYLE_DOT
#property indicator_style8  STYLE_DASHDOT
#property indicator_width1  2

//
//
//
//
//

#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    pstLength                     = 9;
extern int    pstX                          = 5;
extern int    pstSmooth                     = 3;
extern double smoothPeriod                  = 10;
extern double smoothPhase                   = 0;
extern bool   smoothdouble                  = true;
extern int    ZigZagHighLowPeriod           = 30;
extern bool   ZigZagVisible                 = true;
extern int    DzLookBackBars                = 70;
extern double DzStartBuyProbability1        = 0.10;
extern double DzStartBuyProbability2        = 0.25;
extern double DzStartSellProbability1       = 0.10;
extern double DzStartSellProbability2       = 0.25;
extern bool   divergenceVisible             = true;
extern bool   divergenceOnValuesVisible     = true;
extern bool   divergenceOnChartVisible      = true;
extern color  divergenceBullishColor        = LimeGreen;
extern color  divergenceBearishColor        = OrangeRed;
extern string divergenceUniqueID            = "Kase Stoch diverge1";
extern bool   Interpolate                   = true;
extern bool   ShowSignal                    = false;

extern bool   alertsOn                      = true;
extern bool   alertsOnKaseSignalCross       = false;
extern bool   alertsOnUpLevel1Cross         = false;
extern bool   alertsOnUpLevel2Cross         = false;
extern bool   alertsOnZeroLineCross         = false;
extern bool   alertsOnDnLevel2Cross         = false;
extern bool   alertsOnDnLevel1Cross         = false;
extern bool   alertsOnOsObCross             = true;
extern bool   alertsOnCurrent               = false;
extern bool   alertsMessage                 = true;
extern bool   alertsSound                   = false;
extern bool   alertsEmail                   = false;
extern bool   alertsNotification            = false;

extern bool   arrowsVisible                 = true;
extern string arrowsIdentifier              = "Dz KPSS Arrows";
extern double arrowsDisplacement            = 1.0;

extern bool   arrowsOnKaseSignalCross       = false;
extern color  arrowsUp_KaseSignalCrossColor = DeepSkyBlue;
extern int    arrowsUp_KaseSignalCrossCode  = 233;
extern int    arrowsUp_KaseSignalCrossSize  = 1;
extern color  arrowsDn_KaseSignalCrossColor = Red;
extern int    arrowsDn_KaseSignalCrossCode  = 234;
extern int    arrowsDn_KaseSignalCrossSize  = 1;

extern bool   arrowsOnUpLevel1Cross         = false;
extern color  arrowsUp_UpLevel1CrossColor   = DeepSkyBlue;
extern int    arrowsUp_UpLevel1CrossCode    = 217;
extern int    arrowsUp_UpLevel1CrossSize    = 1;
extern color  arrowsDn_UpLevel1CrossColor   = Red;
extern int    arrowsDn_UpLevel1CrossCode    = 218;
extern int    arrowsDn_UpLevel1CrossSize    = 1;

extern bool   arrowsOnUpLevel2Cross         = false;
extern color  arrowsUp_UpLevel2CrossColor   = DeepSkyBlue;
extern int    arrowsUp_UpLevel2CrossCode    = 228;
extern int    arrowsUp_UpLevel2CrossSize    = 1;
extern color  arrowsDn_UpLevel2CrossColor   = Red;
extern int    arrowsDn_UpLevel2CrossCode    = 230;
extern int    arrowsDn_UpLevel2CrossSize    = 1;

extern bool   arrowsOnZeroLineCross         = false;
extern color  arrowsUp_ZeroCrossColor       = DeepSkyBlue;
extern int    arrowsUp_ZeroCrossCode        = 241;
extern int    arrowsUp_ZeroCrossSize        = 1;
extern color  arrowsDn_ZeroCrossColor       = Red;
extern int    arrowsDn_ZeroCrossCode        = 242;
extern int    arrowsDn_ZeroCrossSize        = 1;

extern bool   arrowsOnDnLevel2Cross         = false;
extern color  arrowsUp_DnLevel2CrossColor   = DeepSkyBlue;
extern int    arrowsUp_DnLevel2CrossCode    = 225;
extern int    arrowsUp_DnLevel2CrossSize    = 1;
extern color  arrowsDn_DnLevel2CrossColor   = Red;
extern int    arrowsDn_DnLevel2CrossCode    = 226;
extern int    arrowsDn_DnLevel2CrossSize    = 1;

extern bool   arrowsOnDnLevel1Cross         = false;
extern color  arrowsUp_DnLevel1CrossColor   = DeepSkyBlue;
extern int    arrowsUp_DnLevel1CrossCode    = 71;
extern int    arrowsUp_DnLevel1CrossSize    = 1;
extern color  arrowsDn_DnLevel1CrossColor   = Red;
extern int    arrowsDn_DnLevel1CrossCode    = 72;
extern int    arrowsDn_DnLevel1CrossSize    = 1;

extern bool   arrowsOnOsObCross             = true;
extern color  arrowsUp_OsObCrossColor       = DeepSkyBlue;
extern int    arrowsUp_OsObCrossCode        = 119;
extern int    arrowsUp_OsObCrossSize        = 1;
extern color  arrowsDn_OsObCrossColor       = Red;
extern int    arrowsDn_OsObCrossCode        = 119;
extern int    arrowsDn_OsObCrossSize        = 1;

extern bool   LinesVisible                  = true;
extern string verticalLinesID               = "Dz KPSS lines1";
extern color  verticalLinesUpColor          = DeepSkyBlue;
extern color  verticalLinesDnColor          = PaleVioletRed;
extern int    verticalLinesStyle            = STYLE_DOT;
extern int    verticalLinesWidth            = 0;
extern bool   linesOnKaseSignalCross        = false;
extern bool   linesOnUpLevel1Cross          = false;
extern bool   linesOnUpLevel2Cross          = false;
extern bool   linesOnZeroLineCross          = false;
extern bool   linesOnDnLevel2Cross          = false;
extern bool   linesOnDnLevel1Cross          = false;
extern bool   linesOnOsObCross              = true;

//
//
//
//
//

double pst[];
double pss[];
double bl1[];
double bl2[];
double sl1[];
double sl2[];
double zl1[];
double zigZag[];

//
//
//
//
//

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;
string shortName;

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

int init()
{
   SetIndexBuffer(0,pst);
   SetIndexBuffer(1,pss);
   SetIndexBuffer(2,bl1);
   SetIndexBuffer(3,bl2);
   SetIndexBuffer(4,sl1);
   SetIndexBuffer(5,sl2);
   SetIndexBuffer(6,zl1);
   SetIndexBuffer(7,zigZag); SetIndexStyle(7,DRAW_SECTION); SetIndexEmptyValue(7,0);
   
   if (ShowSignal)
   {
   SetIndexStyle(1,DRAW_LINE);     
   }
   
   else
   {
   SetIndexStyle(1,DRAW_NONE);
   }
      
      //
      //
      //
      //
      //
      
      pstSmooth         = MathMax(pstSmooth,1);
      smoothPeriod      = MathMax(smoothPeriod,1);
      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)+"  DZ KPSS ("+pstLength+","+pstX+")";
   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 && LinesVisible)  deleteLines();
   if (!calculateValue && arrowsVisible) deleteArrows();
   

return(0);
}

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

double work[][4];
#define _zzLow  0
#define _zzHigh 1
#define _chLow  2
#define _chHigh 3

double trends[][7];
#define _tks1 0
#define _tup1 1
#define _tup2 2
#define _tmi1 3
#define _tdn2 4
#define _tdn1 5
#define _tos1 6

double wrkBuffer[][5];
#define TripleK   0
#define TripleDF  1
#define TripleDFs 2
#define TripleDS  3
#define TripleDSs 4

//
//
//
//
//

int start()
{
   double alpha       = 2.0/(1.0+pstSmooth);
   int lookBackPeriod = pstLength*pstX;
   int counted_bars   = IndicatorCounted();
   int i,r,k,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { pst[0] = MathMin(limit+1,Bars-1); return(0); }
         
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame==Period())
   {
     if (ArrayRange(work,0)!=Bars) { ArrayResize(work,Bars); ArrayResize(trends,Bars); }
     if (ArrayRange(wrkBuffer,0) != Bars) ArrayResize(wrkBuffer,Bars);

      //
      //
      //
      //
      //
      
      if (ZigZagVisible)
         for (int lastZag=limit+1; lastZag<Bars-1; lastZag++) if (work[Bars-lastZag-1][_zzLow] != 0 || work[Bars-lastZag-1][_zzHigh] != 0) break;

      for(i=limit,r=Bars-i-1; i>=0; i--,r++)
      {
      double min = Low [iLowest (NULL,0,MODE_LOW ,lookBackPeriod,i)];
      double max = High[iHighest(NULL,0,MODE_HIGH,lookBackPeriod,i)]-min;
      if (max>0)
            wrkBuffer[r][TripleK] = 100.0*(Close[i]-min)/max;
      else  wrkBuffer[r][TripleK] =   0.0;
      if (i==(Bars-1))
      {
            wrkBuffer[r][TripleDF] = wrkBuffer[r][TripleK];
            wrkBuffer[r][TripleDS] = wrkBuffer[r][TripleK];
            continue;
      }
      wrkBuffer[r][TripleDF] =  wrkBuffer[r-pstX][TripleDF]+alpha*(wrkBuffer[r][TripleK]-wrkBuffer[r-pstX][TripleDF]);
      wrkBuffer[r][TripleDS] = (wrkBuffer[r-pstX][TripleDS]*2.0+wrkBuffer[r][TripleDF])/3.0;
      
      //
      //
      //
      //
      //
      
      wrkBuffer[r][TripleDSs] = iSma(TripleDS ,3,r);
      pss[i]                  = iDSmooth(wrkBuffer[r][TripleDSs],smoothPeriod,smoothPhase,smoothdouble,i, 0);
      wrkBuffer[r][TripleDFs] = iSma(TripleDF ,3,r);
      pst[i]                  = iDSmooth(wrkBuffer[r][TripleDFs],smoothPeriod,smoothPhase,smoothdouble,i,20);
      
      //
      //
      //
      //
      //
      
      if (DzStartBuyProbability1  > 0) bl1[i] = dzBuyP (pst, DzStartBuyProbability1,  DzLookBackBars, Bars, i, 0.0001);
      if (DzStartBuyProbability2  > 0) bl2[i] = dzBuyP (pst, DzStartBuyProbability2,  DzLookBackBars, Bars, i, 0.0001);
      if (DzStartSellProbability1 > 0) sl1[i] = dzSellP(pst, DzStartSellProbability1, DzLookBackBars, Bars, i, 0.0001);
      if (DzStartSellProbability2 > 0) sl2[i] = dzSellP(pst, DzStartSellProbability2, DzLookBackBars, Bars, i, 0.0001);
                                       zl1[i] = dzSellP(pst, 0.5                    , DzLookBackBars, Bars, i, 0.0001);
      
         setTrends(i,r);
         manageArrow(i,r);
         manageLine(i,r);
         
         //
         //
         //
         //
         //
         
         if (divergenceVisible)
          {
             CatchBullishDivergence(pst,i);
             CatchBearishDivergence(pst,i);
          }
   
         //
         //
         //
         //
         //

         if (!ZigZagVisible) continue;
   
            //
            //
            //
            //
            //
            
            work[r][_zzLow]  = 0;
            work[r][_zzHigh] = 0;
            work[r][_chLow]  = pst[i];
            work[r][_chHigh] = pst[i];
               for (k=1; k<ZigZagHighLowPeriod && (i+k)<Bars; k++)
               {
                  work[r][_chLow]  = MathMin(work[r][_chLow] ,pst[i+k]);
                  work[r][_chHigh] = MathMax(work[r][_chHigh],pst[i+k]);
               }
         
               //
               //
               //
               //
               //
               
               if (work[r][_chLow] < work[r-1][_chLow])
               {
                  if (zigZag[lastZag] == work[Bars-lastZag-1][_chLow])
                      zigZag[lastZag] = 0;
                      zigZag[i]       =  work[r][_chLow];
                      work[r][_zzLow] =  work[r][_chLow];
                              lastZag = i;
                              continue;
               }
               if (work[r][_chHigh] > work[r-1][_chHigh])
               {
                  if (zigZag[lastZag] == work[Bars-lastZag-1][_chHigh])
                      zigZag[lastZag]  = 0;
                      zigZag[i]        = work[r][_chHigh];
                      work[r][_zzHigh] = work[r][_chHigh];
                               lastZag = i;
                               continue;
               }
               if (zigZag[i] != 0)
               {
                  zigZag[i] = 0;
                  for (lastZag=i+1; lastZag<Bars; lastZag++)
                  {
                     if (work[Bars-lastZag-1][_zzLow]  != 0) { zigZag[lastZag] = work[Bars-lastZag-1][_zzLow];  break; }
                     if (work[Bars-lastZag-1][_zzHigh] != 0) { zigZag[lastZag] = work[Bars-lastZag-1][_zzHigh]; break; }
                  }
              }
   }
   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);
   if (ZigZagVisible)
      while (limit<Bars-1) { if (zigZag[limit]!= 0) break; limit++; }
      
   //
   //
   //
   //
         
   for (i=limit, r=Bars-i-1;i>=0; i--,r++)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         pst[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",pstLength,pstX,pstSmooth,smoothPeriod,smoothPhase,smoothdouble,ZigZagHighLowPeriod,ZigZagVisible,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,0,y);
         pss[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",pstLength,pstX,pstSmooth,smoothPeriod,smoothPhase,smoothdouble,ZigZagHighLowPeriod,ZigZagVisible,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,1,y);
         bl1[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",pstLength,pstX,pstSmooth,smoothPeriod,smoothPhase,smoothdouble,ZigZagHighLowPeriod,ZigZagVisible,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,2,y);
         bl2[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",pstLength,pstX,pstSmooth,smoothPeriod,smoothPhase,smoothdouble,ZigZagHighLowPeriod,ZigZagVisible,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,3,y);
         sl1[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",pstLength,pstX,pstSmooth,smoothPeriod,smoothPhase,smoothdouble,ZigZagHighLowPeriod,ZigZagVisible,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,4,y);
         sl2[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",pstLength,pstX,pstSmooth,smoothPeriod,smoothPhase,smoothdouble,ZigZagHighLowPeriod,ZigZagVisible,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,5,y);
         zl1[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",pstLength,pstX,pstSmooth,smoothPeriod,smoothPhase,smoothdouble,ZigZagHighLowPeriod,ZigZagVisible,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,6,y);
         zigZag[i] = 0;
         
         setTrends(i,r);
         manageArrow(i,r);
         manageLine(i,r);
        
         if (ZigZagVisible)
         if (y!=iBarShift(NULL,timeFrame,Time[i-1]))
         zigZag[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",pstLength,pstX,pstSmooth,smoothPeriod,smoothPhase,smoothdouble,ZigZagHighLowPeriod,ZigZagVisible,DzLookBackBars,DzStartBuyProbability1,DzStartBuyProbability2,DzStartSellProbability1,DzStartSellProbability2,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,Interpolate,7,y);

         //
         //
         //
         //
         //
                  
         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 x = 1; x < n; x++)
            {
               pst[i+x] = pst[i] + (pst[i+n] - pst[i]) * x/n;
               pss[i+x] = pss[i] + (pss[i+n] - pss[i]) * x/n;
               bl1[i+x] = bl1[i] + (bl1[i+n] - bl1[i]) * x/n;
               bl2[i+x] = bl2[i] + (bl2[i+n] - bl2[i]) * x/n;
               sl1[i+x] = sl1[i] + (sl1[i+n] - sl1[i]) * x/n;
               sl2[i+x] = sl2[i] + (sl2[i+n] - sl2[i]) * x/n;
               zl1[i+x] = zl1[i] + (zl1[i+n] - zl1[i]) * x/n;
            }
   }
   
   manageAlerts();
   return(0);
}

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

double iSma(int forDim, int period, int pos)
{
   double sum = wrkBuffer[pos][forDim];
      for(int i=1; i<period; i++) sum += wrkBuffer[pos-i][forDim];
   return(sum/period);
}

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

double wrk[][40];

#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 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);
}

//
//
//
//
//

void setTrends(int i, int r)
{
   trends[r][_tks1] = trends[r-1][_tks1];
   trends[r][_tup1] = trends[r-1][_tup1];
   trends[r][_tup2] = trends[r-1][_tup2];
   trends[r][_tmi1] = trends[r-1][_tmi1];
   trends[r][_tdn1] = trends[r-1][_tdn1];
   trends[r][_tdn2] = trends[r-1][_tdn2];
   trends[r][_tos1] = trends[r-1][_tos1];
  
   
      if (pst[i] > pss[i])                         trends[r][_tks1] =  1;
      if (pst[i] < pss[i])                         trends[r][_tks1] = -1;
      if (pst[i] > bl1[i])                         trends[r][_tup1] =  1;
      if (pst[i] < bl1[i])                         trends[r][_tup1] = -1;
      if (pst[i] > bl2[i])                         trends[r][_tup2] =  1;
      if (pst[i] < bl2[i])                         trends[r][_tup2] = -1;
      if (pst[i] > zl1[i])                         trends[r][_tmi1] =  1;                            
      if (pst[i] < zl1[i])                         trends[r][_tmi1] = -1;                              
      if (pst[i] > sl2[i])                         trends[r][_tdn2] =  1;                            
      if (pst[i] < sl2[i])                         trends[r][_tdn2] = -1;
      if (pst[i] > sl1[i])                         trends[r][_tdn1] =  1;                            
      if (pst[i] < sl1[i])                         trends[r][_tdn1] = -1; 
      if (pst[i] > bl1[i] && pst[i+1] <= bl1[i+1]) trends[r][_tos1] =  1;
      if (pst[i] < sl1[i] && pst[i+1] >= sl1[i+1]) trends[r][_tos1] = -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 (alertsOnKaseSignalCross && trends[whichBar][_tks1] != trends[whichBar-1][_tks1])
      {
         if (trends[whichBar][_tks1] ==  1) doAlert(time1,mess1,whichBar,"kase crossing signal up");
         if (trends[whichBar][_tks1] == -1) doAlert(time1,mess1,whichBar,"kase crossing signal down");
      }
      
            
      static datetime time2 = 0;
      static string   mess2 = "";
      if (alertsOnUpLevel1Cross && trends[whichBar][_tup1] != trends[whichBar-1][_tup1])
      {
         if (trends[whichBar][_tup1] ==  1) doAlert(time2,mess2,whichBar,"crossing upper level one line up");
         if (trends[whichBar][_tup1] == -1) doAlert(time2,mess2,whichBar,"crossing upper level two line down");
      }
      
      static datetime time3 = 0;
      static string   mess3 = "";
      if (alertsOnUpLevel2Cross && trends[whichBar][_tup2] != trends[whichBar-1][_tup2])
      {
         if (trends[whichBar][_tup2] ==  1) doAlert(time3,mess3,whichBar,"crossing upper level two line up");
         if (trends[whichBar][_tup2] == -1) doAlert(time3,mess3,whichBar,"crossing upper level two line down");
      }
      
      static datetime time4 = 0;
      static string   mess4 = "";
      if (alertsOnZeroLineCross && trends[whichBar][_tmi1] != trends[whichBar-1][_tmi1])
      {
         if (trends[whichBar][_tmi1] ==  1) doAlert(time4,mess4,whichBar,"crossed zero line up");
         if (trends[whichBar][_tmi1] == -1) doAlert(time4,mess4,whichBar,"crossed zero line down");
      }
      
      static datetime time5 = 0;
      static string   mess5 = "";
      if (alertsOnDnLevel2Cross && trends[whichBar][_tdn2] != trends[whichBar-1][_tdn2])
      {
         if (trends[whichBar][_tdn2] ==  1) doAlert(time5,mess5,whichBar,"crossing lower level two line up");
         if (trends[whichBar][_tdn2] == -1) doAlert(time5,mess5,whichBar,"crossing lower level two line down");
      }
      
      
      static datetime time6 = 0;
      static string   mess6 = "";
      if (alertsOnDnLevel1Cross && trends[whichBar][_tdn1] != trends[whichBar-1][_tdn1])
      {
         if (trends[whichBar][_tdn1] ==  1) doAlert(time6,mess6,whichBar,"crossing lower level one line up");
         if (trends[whichBar][_tdn1] == -1) doAlert(time6,mess6,whichBar,"crossing lower level one line down");
      }
     
      
      static datetime time7 = 0;
      static string   mess7 = "";
      if (alertsOnOsObCross && trends[whichBar][_tos1] != trends[whichBar-1][_tos1])
      {
         if (trends[whichBar][_tos1] ==  1) doAlert(time7,mess7,whichBar,"leaving oversold up");
         if (trends[whichBar][_tos1] == -1) doAlert(time7,mess7,whichBar,"leaving overbought 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)," Kase Stochastic ",doWhat);
          if (alertsMessage)      Alert(message);
          if (alertsEmail)        SendMail(StringConcatenate(Symbol()," Kase Stochastic "),message);
          if (alertsNotification) SendNotification(message);
          if (alertsSound)        PlaySound("alert2.wav");
   }
}

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

void manageArrow(int i, int r)
{
   if (!calculateValue && arrowsVisible)
   {
      deleteArrow(Time[i]);
      
      if (arrowsOnKaseSignalCross && trends[r][_tks1]!=trends[r-1][_tks1])
      {
         if (trends[r][_tks1] == 1) drawArrow(i,arrowsUp_KaseSignalCrossColor,arrowsUp_KaseSignalCrossCode,arrowsUp_KaseSignalCrossSize,false);
         if (trends[r][_tks1] ==-1) drawArrow(i,arrowsDn_KaseSignalCrossColor,arrowsDn_KaseSignalCrossCode,arrowsDn_KaseSignalCrossSize,false);
      }
      
      if (arrowsOnUpLevel1Cross && trends[r][_tup1]!=trends[r-1][_tup1])
      {
         if (trends[r][_tup1] == 1) drawArrow(i,arrowsUp_UpLevel1CrossColor,arrowsUp_UpLevel1CrossCode,arrowsUp_UpLevel1CrossSize,false);
         if (trends[r][_tup1] ==-1) drawArrow(i,arrowsDn_UpLevel1CrossColor,arrowsDn_UpLevel1CrossCode,arrowsDn_UpLevel1CrossSize,true);
      }
      
      if (arrowsOnUpLevel2Cross && trends[r][_tup2]!=trends[r-1][_tup2])
      {
         if (trends[r][_tup2] == 1) drawArrow(i,arrowsUp_UpLevel2CrossColor,arrowsUp_UpLevel2CrossCode,arrowsUp_UpLevel2CrossSize,false);
         if (trends[r][_tup2] ==-1) drawArrow(i,arrowsDn_UpLevel2CrossColor,arrowsDn_UpLevel2CrossCode,arrowsDn_UpLevel2CrossSize,true);
      }
      
      if (arrowsOnZeroLineCross && trends[r][_tmi1]!=trends[r-1][_tmi1])
      {
         if (trends[r][_tmi1] == 1) drawArrow(i,arrowsUp_ZeroCrossColor,arrowsUp_ZeroCrossCode,arrowsUp_ZeroCrossSize,false);
         if (trends[r][_tmi1] ==-1) drawArrow(i,arrowsDn_ZeroCrossColor,arrowsDn_ZeroCrossCode,arrowsDn_ZeroCrossSize,true);
      }
      
      if (arrowsOnDnLevel2Cross && trends[r][_tdn1]!=trends[r-1][_tdn1])
      {
         if (trends[r][_tdn1] == 1) drawArrow(i,arrowsUp_DnLevel2CrossColor,arrowsUp_DnLevel2CrossCode,arrowsUp_DnLevel2CrossSize,false);
         if (trends[r][_tdn1] ==-1) drawArrow(i,arrowsDn_DnLevel2CrossColor,arrowsDn_DnLevel2CrossCode,arrowsDn_DnLevel2CrossSize,true);
      }
      
      if (arrowsOnDnLevel1Cross && trends[r][_tdn2]!=trends[r-1][_tdn2])
      {
         if (trends[r][_tdn2] == 1) drawArrow(i,arrowsUp_DnLevel1CrossColor,arrowsUp_DnLevel1CrossCode,arrowsUp_DnLevel1CrossSize,false);
         if (trends[r][_tdn2] ==-1) drawArrow(i,arrowsDn_DnLevel1CrossColor,arrowsDn_DnLevel1CrossCode,arrowsDn_DnLevel1CrossSize,true);
      }
      
      if (arrowsOnOsObCross && trends[r][_tos1]!=trends[r-1][_tos1])
      {
         if (trends[r][_tos1] == 1) drawArrow(i,arrowsUp_OsObCrossColor,arrowsUp_OsObCrossCode,arrowsUp_OsObCrossSize,false);
         if (trends[r][_tos1] ==-1) drawArrow(i,arrowsDn_OsObCrossColor,arrowsDn_OsObCrossCode,arrowsDn_OsObCrossSize,true);
      }
      
   }
}               

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,int theSize, 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);
         ObjectSet(name,OBJPROP_WIDTH,    theSize);      
         
         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 manageLine(int i, int r)
{
   if (!calculateValue && LinesVisible)
   {
      deleteLine(Time[i]);
      
      if (linesOnKaseSignalCross && trends[r][_tks1]!=trends[r-1][_tks1])
      {
         if (trends[r][_tks1] == 1) drawLine(i,verticalLinesUpColor);
         if (trends[r][_tks1] ==-1) drawLine(i,verticalLinesDnColor);
      }
      
      if (linesOnUpLevel1Cross && trends[r][_tup1]!=trends[r-1][_tup1])
      {
         if (trends[r][_tup1] == 1) drawLine(i,verticalLinesUpColor);
         if (trends[r][_tup1] ==-1) drawLine(i,verticalLinesDnColor);
      }
      
      if (linesOnUpLevel2Cross && trends[r][_tup2]!=trends[r-1][_tup2])
      {
         if (trends[r][_tup2] == 1) drawLine(i,verticalLinesUpColor);
         if (trends[r][_tup2] ==-1) drawLine(i,verticalLinesDnColor);
      }
      
      if (linesOnZeroLineCross && trends[r][_tmi1]!=trends[r-1][_tmi1])
      {
         if (trends[r][_tmi1] == 1) drawLine(i,verticalLinesUpColor);
         if (trends[r][_tmi1] ==-1) drawLine(i,verticalLinesDnColor);
      }
      
      if (linesOnDnLevel2Cross && trends[r][_tdn2]!=trends[r-1][_tdn2])
      {
         if (trends[r][_tdn2] == 1) drawLine(i,verticalLinesUpColor);
         if (trends[r][_tdn2] ==-1) drawLine(i,verticalLinesDnColor);
      }
      
      if (linesOnDnLevel1Cross && trends[r][_tdn1]!=trends[r-1][_tdn1])
      {
         if (trends[r][_tdn1] == 1) drawLine(i,verticalLinesUpColor);
         if (trends[r][_tdn1] ==-1) drawLine(i,verticalLinesDnColor); 
      }
      
      if (linesOnOsObCross && trends[r][_tos1]!=trends[r-1][_tos1])
      {
         if (trends[r][_tos1] == 1) drawLine(i,verticalLinesUpColor);
         if (trends[r][_tos1] ==-1) drawLine(i,verticalLinesDnColor);
      }   
   }
}               

//
//
//
//
//

void drawLine(int i,color theColor)
{
   string name = verticalLinesID+":"+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);
}

//
//
//
//
//

void deleteLines()
{
   string lookFor       = verticalLinesID+":";
   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 deleteLine(datetime time)
{
   string lookFor = verticalLinesID+":"+time; ObjectDelete(lookFor);
}

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


      


