//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "www,forex-tsd.com"
#property link      "www,forex-tsd.com"

#property indicator_chart_window
#property indicator_buffers 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    KSTType                = 1;
extern ENUM_MA_METHOD KSTMaType      = MODE_EMA;
extern int    KSTSignalMaPeriod      = 9;
extern double SmoothPhase            = 0;
extern int    DzLookBackBars         = 35;
extern double DzStartBuyProbability  = 0.05;
extern double DzStartSellProbability = 0.05;
extern color  ColorUp                = clrLimeGreen;
extern color  ColorDown              = clrOrangeRed;
extern string ColorUniqueID          = "DZkst color bars";
extern int    ColorWidth             = 2;
extern int    ColorBars              = 500;
extern int    widthWick              = 0;
extern int    widthBody              = 2;
extern bool   drawInBackgound        = false;
extern bool   alertsOn               = true;
extern bool   alertsOnSignalCross    = true;
extern bool   alertsOnZeroCross      = true;
extern bool   alertsOnSlope          = true;
extern bool   alertsOnCurrent        = false;
extern bool   alertsMessage          = true;
extern bool   alertsSound            = true;
extern bool   alertsNotify           = false;
extern bool   alertsEmail            = false;
extern string soundFile              = "alert2.wav";
//
//
//
//
//

double obLine[],osLine[],zeroLine[],ratios[],kst[],kstSignal[],trend[],slope[],value[],paramr[4],paramm[4],koef = 1;
string shortName = "",indicatorFileName;
bool   returnBars,calculateValue;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int window;
int init()
{
   KSTType   = MathMax(MathMin(KSTType  ,2),0);   
   KSTMaType = MathMax(MathMin(KSTMaType,1),0);   
   
   //
   //
   //
   //
   //
   
     switch (KSTMaType)
     {
         case 0 :
            switch (KSTType)
            {
               case 0 :
                     paramr[0] = 10; paramr[1] = 15; paramr[2] = 20; paramr[3] = 30; 
                     paramm[0] = 10; paramm[1] = 10; paramm[2] = 10; paramm[3] = 15;
                     shortName = ColorUniqueID+": ""Short term SMA";
                     break;
               case 1 :                     
                     paramr[0] = 10; paramr[1] = 13; paramr[2] = 15; paramr[3] = 20;
                     paramm[0] = 10; paramm[1] = 13; paramm[2] = 15; paramm[3] = 20;
                     shortName = ColorUniqueID+": ""Intermediate term SMA";
                     break;
               case 2:                     
                     paramr[0] =  9; paramr[1] = 12; paramr[2] = 18; paramr[3] = 24;
                     paramm[0] =  6; paramm[1] =  6; paramm[2] =  6; paramm[3] =  9; koef = 4;
                     shortName = ColorUniqueID+": ""Long term SMA";
                     break;
            }
            break;

         //
         //
         //
         //
         //
                     
         case 1 :            
            switch (KSTType)
            {
               case 0 :
                     paramr[0] = 3; paramr[1] = 4; paramr[2] = 6; paramr[3] = 10; 
                     paramm[0] = 3; paramm[1] = 4; paramm[2] = 6; paramm[3] =  8;
                     shortName = ColorUniqueID+": ""Short term EMA";
                     break;
               case 1 :                     
                     paramr[0] = 10; paramr[1] = 13; paramr[2] = 15; paramr[3] = 20;
                     paramm[0] = 10; paramm[1] = 13; paramm[2] = 15; paramm[3] = 20;
                     shortName = ColorUniqueID+": ""Intermediate term EMA";
                     break;
               case 2:                     
                     paramr[0] = 39; paramr[1] = 52; paramr[2] = 78; paramr[3] = 109;
                     paramm[0] = 26; paramm[1] = 26; paramm[2] = 26; paramm[3] =  39;
                     shortName = ColorUniqueID+": ""Long term EMA";
                     break;
            }
      }
      
      //
      //
      //
      //
      //
      
      IndicatorBuffers(9);
      SetIndexBuffer(0,obLine);   SetIndexStyle(0,DRAW_NONE);
      SetIndexBuffer(1,osLine);   SetIndexStyle(1,DRAW_NONE);
      SetIndexBuffer(2,kst);
      SetIndexBuffer(3,kstSignal);
      SetIndexBuffer(4,ratios); 
      SetIndexBuffer(5,zeroLine);
      SetIndexBuffer(6,slope);
      SetIndexBuffer(7,trend);
      SetIndexBuffer(8,value);
      
         //
         //
         //
         //
         //
      
            indicatorFileName = WindowExpertName();
            returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
            calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
            timeFrame         = stringToTimeFrame(TimeFrame);
      
         //
         //
         //
         //
         //
         
      IndicatorShortName(shortName);
return(0);
}
int deinit()
{
      int lookForLength = StringLen(ColorUniqueID);
      for (int i=ObjectsTotal()-1; i>=0; i--) 
      {
         string name = ObjectName(i);  if (StringSubstr(name,0,lookForLength) == ColorUniqueID) ObjectDelete(name);
      }
   return(0); 
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double work[][4];
int start()
{
   int i,r,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(work,0)!=Bars) ArrayResize(work,Bars);
           if (returnBars) { obLine[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
      int cb = ColorBars; if (ColorBars==0) cb = Bars-1; cb = MathMin(Bars-1,cb);
      for (i=limit, r=Bars-i-1; i>=0; i--,r++)
      {
         for (int k=0; k<4; k++) work[r][k] = iROC(paramr[k],i);
         if (KSTMaType==0)
               kst[i] = (iSMA(0,r)+iSMA(1,r)*2.0+iSMA(2,r)*3.0+iSMA(3,r)*4.0)/koef;
         else  kst[i] = (iEMA(0,r)+iEMA(1,r)*2.0+iEMA(2,r)*3.0+iEMA(3,r)*4.0)/koef;
      
         double sum = 0; for (k=0; k<KSTSignalMaPeriod; k++) sum += kst[i+k];
               kstSignal[i] = sum/KSTSignalMaPeriod; 
               obLine[i]    = dzBuyP (kst, DzStartBuyProbability,  DzLookBackBars, Bars, i, 0.00001);
               osLine[i]    = dzSellP(kst, DzStartSellProbability, DzLookBackBars, Bars, i, 0.00001);
               zeroLine[i]  = dzSellP(kst, 0.5,                    DzLookBackBars, Bars, i, 0.00001);
               ratios[i]    = -1;
               
               //
               //
               //
               //
               //
               
               trend[i] = trend[i+1];
               slope[i] = slope[i+1];
               value[i] = value[i+1];
                  
               if (kst[i]>kstSignal[i]) value[i] = 1;
               if (kst[i]<kstSignal[i]) value[i] =-1;
               if (kst[i]>zeroLine[i])  trend[i] = 1;
               if (kst[i]<zeroLine[i])  trend[i] =-1;
               if (kst[i]>kst[i+1])     slope[i] = 1;
               if (kst[i]<kst[i+1])     slope[i] =-1;
               
               //
               //
               //
               
               if (cb>=i)
               {
                  double ratio = MathMin(kst[i],osLine[i]);
                         ratio = MathMax(ratio     ,obLine[i]);
                         if ((osLine[i]-obLine[i]) != 0)
                              ratio = (ratio-obLine[i])/(osLine[i]-obLine[i]);
                        else  ratio = 0; 
                        ratios[i] = ratio;
                        if (!calculateValue)
                        {
                           color barColor = gradientColor(100.0*ratios[i],101,ColorDown,ColorUp);
                           drawBar(Time[i],High[i],Low[i],Open[i],Close[i],barColor,barColor);
                        }
            }                     
         
      }
      
     //
     //
     //
            
     if (alertsOn)
      {
        int whichBar = 1; if (alertsOnCurrent) whichBar = 0; 
        static datetime time1 = 0;
        static string   mess1 = "";
           if (alertsOnSignalCross && value[whichBar] != value[whichBar+1])
           {
              if (value[whichBar] == 1) doAlert(time1,mess1,whichBar," crossing signal up ");
              if (value[whichBar] ==-1) doAlert(time1,mess1,whichBar," crossing signal down ");
           }            
        static datetime time2 = 0;
        static string   mess2 = "";
           if (alertsOnZeroCross && trend[whichBar] != trend[whichBar+1])
           {
              if (trend[whichBar] == 1) doAlert(time2,mess2,whichBar," crossing zeroline up ");
              if (trend[whichBar] ==-1) doAlert(time2,mess2,whichBar," crossing zeroline down ");
           }
           
        static datetime time3 = 0;
        static string   mess3 = "";
           if (alertsOnSlope && slope[whichBar] != slope[whichBar+1])
           {
              if (slope[whichBar] == 1) doAlert(time3,mess3,whichBar," sloping up ");
              if (slope[whichBar] ==-1) doAlert(time3,mess3,whichBar," sloping down ");
           }                                                
   } 
   return(0);
   }  
   
   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for(i=limit, r=Bars-i-1; i>=0; i--,r++)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         ratios[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",KSTType,KSTMaType,KSTSignalMaPeriod,SmoothPhase,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,ColorUp,ColorDown,ColorUniqueID,ColorWidth,ColorBars,widthWick,widthBody,drawInBackgound,alertsOn,alertsOnSignalCross,alertsOnZeroCross,alertsOnSlope,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotify,soundFile,4,y);
         barColor  = gradientColor(100.0*ratios[i],101,ColorDown,ColorUp);
            if (ratios[i] != -1) drawBar(Time[i],High[i],Low[i],Open[i],Close[i],barColor,barColor);
   }
   return(0);
}


//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+

double iROC(int period, int shift)
{
   double ROC;

   if (Close[shift + period] != 0)
          ROC = (Close[shift]-Close[shift + period]) / Close[shift + period];
   else   ROC = 0.00;
   return(ROC);
}

//
//
//
//
//

double iSMA(int forBuffer, int r)
{
   double sum=0;
   for (int k=0; k<paramm[forBuffer] && (r-k)>=0; k++) sum += work[r-k][forBuffer];
        return(sum/paramm[forBuffer]);
}

//
//
//
//
//

double workEma[][4];
double iEMA(int forBuffer, int r)
{
   if (ArrayRange(workEma,0)!=Bars) ArrayResize(workEma,Bars);
   if (r==0) 
      workEma[r][forBuffer] = work[r][forBuffer];
   else
   {
      double alpha = 2.0/(1.0+paramm[forBuffer]);
         workEma[r][forBuffer] = workEma[r-1][forBuffer]+alpha*(work[r][forBuffer]-workEma[r-1][forBuffer]);
   }      
   return(workEma[r][forBuffer]);
}

//
//
//
//
//

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()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," KST ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," KST "),message);
             if (alertsNotify)  SendNotification(message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------

color gradientColor(int step, int totalSteps, color from, color to)
{
   step = MathMax(MathMin(step,totalSteps-1),0);
      color newBlue  = getColor(step,totalSteps,(from & 0XFF0000)>>16,(to & 0XFF0000)>>16)<<16;
      color newGreen = getColor(step,totalSteps,(from & 0X00FF00)>> 8,(to & 0X00FF00)>> 8) <<8;
      color newRed   = getColor(step,totalSteps,(from & 0X0000FF)    ,(to & 0X0000FF)    )    ;
      return(newBlue+newGreen+newRed);
}
color getColor(int stepNo, int totalSteps, color from, color to)
{
   double step = (from-to)/(totalSteps-1.0);
   return(MathRound(from-step*stepNo));
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------

void drawBar(int bTime, double prHigh, double prLow, double prOpen, double prClose, color barColor, color wickColor)
{
   string oName;
          oName = ColorUniqueID+TimeToStr(bTime)+"w";
            if (ObjectFind(oName) < 0) ObjectCreate(oName,OBJ_TREND,window,bTime,0,bTime,0);
                 ObjectSet(oName, OBJPROP_PRICE1, prHigh);
                 ObjectSet(oName, OBJPROP_PRICE2, prLow);
                 ObjectSet(oName, OBJPROP_COLOR, wickColor);
                 ObjectSet(oName, OBJPROP_WIDTH, widthWick);
                 ObjectSet(oName, OBJPROP_RAY, false);
                 ObjectSet(oName, OBJPROP_BACK, drawInBackgound);
           
         oName = ColorUniqueID+TimeToStr(bTime)+"b";
            if (ObjectFind(oName) < 0)ObjectCreate(oName,OBJ_TREND,window,bTime,0,bTime,0);
                 ObjectSet(oName, OBJPROP_PRICE1, prOpen);
                 ObjectSet(oName, OBJPROP_PRICE2, prClose);
                 ObjectSet(oName, OBJPROP_COLOR, barColor);
                 ObjectSet(oName, OBJPROP_WIDTH, widthBody);
                 ObjectSet(oName, OBJPROP_RAY, false);
                 ObjectSet(oName, OBJPROP_BACK, drawInBackgound);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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);
}


