//+------------------------------------------------------------------+
//|                                             Steop stochastic.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 5
#property indicator_color1  Orange
#property indicator_color2  LimeGreen
#property indicator_color3  DarkGray
#property indicator_color4  DarkGray
#property indicator_color5  Orange
#property indicator_width4  2
#property indicator_width5  3
#property indicator_style1  STYLE_DOT
#property indicator_style2  STYLE_DOT
#property indicator_style3  STYLE_DOT
#property indicator_minimum -1
#property indicator_maximum 101

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuy(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i);
   double dzSell(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i);
#import

//
//
//
//
//

extern string TimeFrame              = "Current time frame";
extern int    UsePrice               = PRICE_CLOSE;
extern int    ATR_Length             = 10;
extern double K_Slow                 =  1;
extern double K_Fast                 =  1.5;
extern int    Window                 = 256;
extern bool   DzOnFastStoch          = true;
extern int    DzLookBackBars         = 70;
extern double DzStartBuyProbability  = 0.15;
extern double DzStartSellProbability = 0.15;
extern bool   alertsOn               = false;
extern bool   alertsOnCurrent        = false;
extern bool   alertsMessage          = true;
extern bool   alertsSound            = false;
extern bool   alertsEmail            = false;
extern bool   Interpolate            = true;

//
//
//
//
//

double stoch1[];
double stoch2[];
double atr[];
double trend[];
double sli[];
double bli[];
double zli[];

//
//
//
//
//

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

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

int init()
{
   IndicatorBuffers(7);
   SetIndexBuffer(0,bli);
   SetIndexBuffer(1,sli);
   SetIndexBuffer(2,zli);
   SetIndexBuffer(3,stoch2);
   SetIndexBuffer(4,stoch1);
   SetIndexBuffer(5,trend);
   SetIndexBuffer(6,atr);

      //
      //
      //
      //
      //
      
      indicatorFileName   = WindowExpertName();
      returnBars          = TimeFrame=="returnBars";          if (returnBars)          return(0);
      calculateValue      = TimeFrame=="calculateValue";      if (calculateValue)      return(0);
      timeFrame           = stringToTimeFrame(TimeFrame);
   
      IndicatorShortName(timeFrameToString(timeFrame)+" Step stochastic ("+ATR_Length+","+DoubleToStr(K_Slow,2)+","+DoubleToStr(K_Fast,2)+","+Window+")");
   return(0);
}
int deinit()
{
   return(0);
}

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

double work[][12];
#define k_SminMin   0
#define k_SmaxMin   1
#define k_SminMid   2
#define k_SmaxMid   3
#define k_SminMax   4
#define k_SmaxMax   5
#define k_TrendMin  6
#define k_TrendMid  7
#define k_TrendMax  8
#define k_linemin   9 
#define k_linemid  10
#define k_linemax  11
#define bigValue   99999999

//
//
//
//
//

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

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

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame==Period())
   {
      if (ArrayRange(work,0) != Bars) ArrayResize(work,Bars);
      for(i=limit, r=Bars-limit-1; i>=0; i--,r++)
      {
         double nPrice = iMA(NULL,0,1,0,MODE_SMA,UsePrice,i);  
                atr[i] = iATR(NULL,0,ATR_Length,i);
                if (r<=Window)
                {
                  work[r][k_TrendMin] = 0;
                  work[r][k_TrendMid] = 0;
                  work[r][k_TrendMax] = 0;
                  work[r][k_linemin]  = 0;
                  work[r][k_linemid]  = 0;
                  work[r][k_linemax]  = 0;
                  work[r][k_SminMin]  = bigValue;
                  work[r][k_SmaxMin]  = bigValue;
                  work[r][k_SminMax]  = 0;
                  work[r][k_SmaxMax]  = 0;
                  work[r][k_SminMid]  = 0;
                  work[r][k_SmaxMid]  = 0;
                  continue;
                }

         //
         //
         //
         //
         //
      
         double nATRmax     = atr[ArrayMaximum(atr,Window,i)];
         double nATRmin     = atr[ArrayMinimum(atr,Window,i)];
         double StepSizeMin = (K_Fast * nATRmin);
         double StepSizeMax = (K_Fast * nATRmax);
         double StepSizeMid = (K_Fast * 0.5 * K_Slow * (nATRmax + nATRmin));

            work[r][k_SmaxMin] = nPrice + 2.0 * StepSizeMin;
            work[r][k_SminMin] = nPrice - 2.0 * StepSizeMin;
            work[r][k_SmaxMax] = nPrice + 2.0 * StepSizeMax;
            work[r][k_SminMax] = nPrice - 2.0 * StepSizeMax;
            work[r][k_SmaxMid] = nPrice + 2.0 * StepSizeMid;
            work[r][k_SminMid] = nPrice - 2.0 * StepSizeMid;

            //
            //
            //
            //
            //
         
            double TrendMin = work[r-1][k_TrendMin];
            double TrendMid = work[r-1][k_TrendMid];
            double TrendMax = work[r-1][k_TrendMax];
            double linemin  = work[r-1][k_linemin];
            double linemid  = work[r-1][k_linemid];
            double linemax  = work[r-1][k_linemax];

            //
            //
            //
            //
            //
                        
            if (nPrice > work[r-1][k_SmaxMin]) TrendMin =  1;
            if (nPrice < work[r-1][k_SminMin]) TrendMin = -1;
            if (nPrice > work[r-1][k_SmaxMax]) TrendMax =  1;
            if (nPrice < work[r-1][k_SminMax]) TrendMax = -1;
            if (nPrice > work[r-1][k_SmaxMid]) TrendMid =  1;
            if (nPrice < work[r-1][k_SminMid]) TrendMid = -1;

            if (TrendMin > 0 && work[r][k_SminMin] < work[r-1][k_SminMin]) work[r][k_SminMin] = work[r-1][k_SminMin];
            if (TrendMin < 0 && work[r][k_SmaxMin] > work[r-1][k_SmaxMin]) work[r][k_SmaxMin] = work[r-1][k_SmaxMin];
            if (TrendMax > 0 && work[r][k_SminMax] < work[r-1][k_SminMax]) work[r][k_SminMax] = work[r-1][k_SminMax];
            if (TrendMax < 0 && work[r][k_SmaxMax] > work[r-1][k_SmaxMax]) work[r][k_SmaxMax] = work[r-1][k_SmaxMax];
            if (TrendMid > 0 && work[r][k_SminMid] < work[r-1][k_SminMid]) work[r][k_SminMid] = work[r-1][k_SminMid];
            if (TrendMid < 0 && work[r][k_SmaxMid] > work[r-1][k_SmaxMid]) work[r][k_SmaxMid] = work[r-1][k_SmaxMid];

            if (TrendMin > 0) linemin = work[r][k_SminMin] + StepSizeMin;
            if (TrendMin < 0) linemin = work[r][k_SmaxMin] - StepSizeMin;
            if (TrendMax > 0) linemax = work[r][k_SminMax] + StepSizeMax;
            if (TrendMax < 0) linemax = work[r][k_SmaxMax] - StepSizeMax;
            if (TrendMid > 0) linemid = work[r][k_SminMid] + StepSizeMid;
            if (TrendMid < 0) linemid = work[r][k_SmaxMid] - StepSizeMid;

         //
         //
         //
         //
         //
               
         work[r][k_TrendMin] = TrendMin;
         work[r][k_TrendMid] = TrendMid;
         work[r][k_TrendMax] = TrendMax;
         work[r][k_linemin]  = linemin;
         work[r][k_linemid]  = linemid;
         work[r][k_linemax]  = linemax;
            
         //
         //
         //
         //
         //
         
         double bsmin = linemax - StepSizeMax;
         double bsmax = linemax + StepSizeMax;
         if (bsmax!=bsmin)
         {
            stoch1[i] = ((linemin - bsmin) / (bsmax - bsmin)) * 100.0;
            stoch2[i] = ((linemid - bsmin) / (bsmax - bsmin)) * 100.0;
         }
         else               
         {
            stoch1[i] = 0;
            stoch2[i] = 0;
         }
         trend[i] = trend[i+1];
         if (stoch1[i]>stoch2[i]) trend[i] =  1;
         if (stoch1[i]<stoch2[i]) trend[i] = -1;
         
         //
         //
         //
         //
         //

         if (DzOnFastStoch)       
         {  
            bli[i] = dzBuy (stoch1, DzStartBuyProbability,  DzLookBackBars, Bars, i);
            sli[i] = dzSell(stoch1, DzStartSellProbability, DzLookBackBars, Bars, i);
            zli[i] = dzSell(stoch1, 0.5,                    DzLookBackBars, Bars, i);
         }
         else
         {
            bli[i] = dzBuy (stoch2, DzStartBuyProbability,  DzLookBackBars, Bars, i);
            sli[i] = dzSell(stoch2, DzStartSellProbability, DzLookBackBars, Bars, i);
            zli[i] = dzSell(stoch2, 0.5,                    DzLookBackBars, Bars, i);
         }            
         
      }
      manageAlerts();
      return(0);
   }
   
   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));

   if (ArraySize(trend)!=Bars) ArrayResize(trend,Bars);
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         bli[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",UsePrice,ATR_Length,K_Slow,K_Fast,Window,DzOnFastStoch,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,0,y);
         sli[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",UsePrice,ATR_Length,K_Slow,K_Fast,Window,DzOnFastStoch,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,1,y);
         zli[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",UsePrice,ATR_Length,K_Slow,K_Fast,Window,DzOnFastStoch,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,2,y);
         stoch2[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",UsePrice,ATR_Length,K_Slow,K_Fast,Window,DzOnFastStoch,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,3,y);
         stoch1[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",UsePrice,ATR_Length,K_Slow,K_Fast,Window,DzOnFastStoch,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,4,y);
         trend[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",UsePrice,ATR_Length,K_Slow,K_Fast,Window,DzOnFastStoch,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,5,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;	
            double factor = 1.0 / n;
            for(int k = 1; k < n; k++)
            {
               stoch1[i+k] = k*factor*stoch1[i+n] + (1.0-k*factor)*stoch1[i];
               stoch2[i+k] = k*factor*stoch2[i+n] + (1.0-k*factor)*stoch2[i];
               bli[i+k]     = k*factor*bli[i+n]     + (1.0-k*factor)*bli[i];
               sli[i+k]     = k*factor*sli[i+n]     + (1.0-k*factor)*sli[i];
               zli[i+k]     = k*factor*zli[i+n]     + (1.0-k*factor)*zli[i];
            }
   }
   manageAlerts();
   return(0);
}

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

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      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 =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," step stochastic - trend changed to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"step stochastic"),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

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

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