//+------------------------------------------------------------------+
//|                                    kase permision stochastic.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "www,forex-station.com"

#property indicator_separate_window
#property indicator_buffers    6
#property indicator_color1     clrMediumSeaGreen
#property indicator_color2     clrRed
#property indicator_color3     clrCrimson
#property indicator_color4     clrCrimson
#property indicator_color5     clrDimGray
#property indicator_color6     clrDimGray

#property indicator_width1     2
#property indicator_width3     2
#property indicator_width4     2
#property indicator_style2     STYLE_DOT
#property indicator_style5     STYLE_DOT
#property indicator_style6     STYLE_DOT
#property indicator_minimum    0
#property indicator_maximum    100
//#property indicator_level1     25
//#property indicator_level2     75
//#property indicator_levelcolor clrDimGray 
#property strict

//
//
//
//
//

enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_tbiased2,   // Trend biased (extreme) price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased,  // Heiken ashi trend biased price
   pr_hatbiased2, // Heiken ashi trend biased (extreme) price
   pr_habclose,   // Heiken ashi (better formula) close
   pr_habopen ,   // Heiken ashi (better formula) open
   pr_habhigh,    // Heiken ashi (better formula) high
   pr_hablow,     // Heiken ashi (better formula) low
   pr_habmedian,  // Heiken ashi (better formula) median
   pr_habtypical, // Heiken ashi (better formula) typical
   pr_habweighted,// Heiken ashi (better formula) weighted
   pr_habaverage, // Heiken ashi (better formula) average
   pr_habmedianb, // Heiken ashi (better formula) median body
   pr_habtbiased, // Heiken ashi (better formula) trend biased price
   pr_habtbiased2 // Heiken ashi (better formula) trend biased (extreme) price
};

input  int            pstLength        = 9;                 // Length
input  int            pstX             = 3;                 // Bars to calculate stoch
extern int            pstSmooth        = 3;                 // Smoothing length
input enPrices        Price            = pr_close;          // Price to use
extern int            smoothPeriod     = 10;                // Jurik smooth length
input  double         smoothPhase      = 0;                 // Jurik smooth phase 
extern int                sellevel            = 25;
extern int                buylevel            = 75;
input  bool           alertsOn         = true;              // Turn alerts on/off?
input  bool           alertsOnCurrent  = false;             // Alerts on still opened bar on/off?
input  bool           alertsMessage    = true;              // Alerts popup message on/off?
input  bool           alertsSound      = false;             // Alerts sound on/off?
input  bool           alertsNotify     = false;             // Alerts notification on/off?
input  bool           alertsEmail      = false;             // Alerts email on/off?
input  string         soundFile        = "alert2.wav";      // Alerts sound file

extern string             button_note1          = "------------------------------";
extern int                btn_Subwindow = 0;
extern ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER; 
extern string             btn_text              = "kase";
extern string             btn_Font              = "Arial";
extern int                btn_FontSize          = 10;                        
extern color              btn_text_ON_color     = clrLime;
extern color              btn_text_OFF_color    = clrRed;
extern color              btn_background_color  = clrDimGray;
extern color              btn_border_color      = clrBlack;
extern int                button_x              = 900;                                   
extern int                button_y              = 0;                                   
extern int                btn_Width             = 70;                                
extern int                btn_Height            = 20;                               
extern string             button_note2          = "------------------------------";

bool show_data = true;
bool recalc    = true;

string IndicatorName, IndicatorObjPrefix,buttonId;

double mada[],madb[],slope[];
double pstBuffer[],pssBuffer[],wrkBuffer[][5],trend[],priceHi[],priceLo[];
// template obos 2
double upVal[],dnVal[];
// template obos 2
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
string GenerateIndicatorName(const string target) 
{
   string name = target;
   int try = 2;
   while (WindowFind(name) != -1)
   {
      name = target + " #" + IntegerToString(try++);
   }
   return name;
}
//
//
//

int OnInit()
{
   IndicatorName = GenerateIndicatorName(btn_text);
   IndicatorObjPrefix = "__" + IndicatorName + "__";
   IndicatorShortName(IndicatorName);
   IndicatorDigits(Digits);
   
   double val;
   if (GlobalVariableGet(IndicatorName + "_visibility", val))
      show_data = val != 0;
   IndicatorBuffers(7);
   SetIndexBuffer(0,pstBuffer); SetIndexStyle(0,DRAW_LINE); SetIndexLabel(0,"Kase Stochastic");
   SetIndexBuffer(1,pssBuffer); SetIndexStyle(1,DRAW_LINE); SetIndexLabel(1,"Kase Signal");
   SetIndexBuffer(2,mada,INDICATOR_DATA); SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(3,madb,INDICATOR_DATA); SetIndexStyle(3,DRAW_LINE);
   SetIndexBuffer(4, upVal);       SetIndexStyle(4 ,DRAW_LINE);
   SetIndexBuffer(5, dnVal);       SetIndexStyle(5 ,DRAW_LINE);
   
   SetIndexBuffer(6,trend);
   
   pstSmooth    = fmax(pstSmooth,1);
   smoothPeriod = fmax(smoothPeriod,1);

   IndicatorShortName("Kase permission stochastic smoothed ("+(string)pstLength+","+(string)pstX+")");  
   
    ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, 1);
   buttonId = IndicatorObjPrefix + (btn_text);
   createButton(buttonId, btn_text, btn_Width, btn_Height, btn_Font, btn_FontSize, btn_background_color, btn_border_color, btn_text_ON_color);
   ObjectSetInteger(0, buttonId, OBJPROP_YDISTANCE, button_y);
   ObjectSetInteger(0, buttonId, OBJPROP_XDISTANCE, button_x);
   
    
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)

 {
 
ObjectsDeleteAll(ChartID(), IndicatorObjPrefix); 
 
 
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
void createButton(string buttonID,string buttonText,int width,int height,string font,int fontSize,color bgColor,color borderColor,color txtColor)
{
   //   ObjectDelete    (0,buttonID);
      ObjectCreate    (0,buttonID,OBJ_BUTTON,WindowOnDropped(),0,0);
      ObjectSetInteger(0,buttonID,OBJPROP_COLOR,txtColor);
      ObjectSetInteger(0,buttonID,OBJPROP_BGCOLOR,bgColor);
      ObjectSetInteger(0,buttonID,OBJPROP_BORDER_COLOR,borderColor);
      ObjectSetInteger(0,buttonID,OBJPROP_BORDER_TYPE,BORDER_RAISED);
      ObjectSetInteger(0,buttonID,OBJPROP_XSIZE,width);
      ObjectSetInteger(0,buttonID,OBJPROP_YSIZE,height);
      ObjectSetString (0,buttonID,OBJPROP_FONT,font);
      ObjectSetString (0,buttonID,OBJPROP_TEXT,buttonText);
      ObjectSetInteger(0,buttonID,OBJPROP_FONTSIZE,fontSize);
      ObjectSetInteger(0,buttonID,OBJPROP_SELECTABLE,0);
      ObjectSetInteger(0,buttonID,OBJPROP_CORNER,btn_corner);
      ObjectSetInteger(0,buttonID,OBJPROP_HIDDEN,1);
      ObjectSetInteger(0,buttonID,OBJPROP_XDISTANCE,9999);
      ObjectSetInteger(0,buttonID,OBJPROP_YDISTANCE,9999);
}

void handleButtonClicks()
{
   if (ObjectGetInteger(0, buttonId, OBJPROP_STATE))
   {
      ObjectSetInteger(0, buttonId, OBJPROP_STATE, false);
      show_data = !show_data;
      GlobalVariableSet(IndicatorName + "_visibility", show_data ? 1.0 : 0.0);
      recalc = true;
     // start();
   }
}
void OnChartEvent(const int id, 
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
   handleButtonClicks();
   if (id==CHARTEVENT_OBJECT_CLICK && ObjectGet(sparam,OBJPROP_TYPE)==OBJ_BUTTON)
   
   for (int banzai=0; banzai<indicator_buffers; banzai++)
     SetIndexStyle(banzai,DRAW_LINE);
     
   if (show_data)
   {
   ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_ON_color);
     
      }
      else
      {
        ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_OFF_color);
        for (int banzai=0; banzai<indicator_buffers; banzai++)
            SetIndexStyle(banzai,DRAW_NONE);
      }     
   
}

//
//

#define TripleK   0
#define TripleDF  1
#define TripleDFs 2
#define TripleDS  3
#define TripleDSs 4

int start()
{
   int i,r,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = fmin(Bars-counted_bars,Bars-1); 
         
   //
   //
   //
   //
   //
   if (trend[i]==-1) CleanPoint(i,mada,madb);
   double alpha = 2.0/(1.0+pstSmooth);
   int lookBackPeriod = pstLength*pstX;
   if (ArrayRange(wrkBuffer,0) != Bars) ArrayResize(wrkBuffer,Bars);
   
   
   
   for(i=limit,r=Bars-i-1; i>=0; i--,r++)
   {
      if(i>=Bars-pstLength) continue;
      double min = Low [iLowest (NULL,0,MODE_LOW ,lookBackPeriod,i)];
      double max = High[iHighest(NULL,0,MODE_HIGH,lookBackPeriod,i)]-min;
      wrkBuffer[r][TripleK] = (max>0) ? 100.0*(getPrice(Price,Open,Close,High,Low,i,Bars)-min)/max : 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);
      pssBuffer[i]            = iSmooth(wrkBuffer[r][TripleDSs],smoothPeriod,smoothPhase,i,Bars,0);
      wrkBuffer[r][TripleDFs] = iSma(TripleDF,3,r);
      pstBuffer[i]            = iSmooth(wrkBuffer[r][TripleDFs],smoothPeriod,smoothPhase,i,Bars,1);
      
      upVal[i] = buylevel;
      
       dnVal[i] = sellevel; 
      trend[i] = (i<Bars-1) ? (pstBuffer[i]>pssBuffer[i]) ? 1 : (pstBuffer[i]<pssBuffer[i]) ? -1 : trend[i+1] : 0;
      
         mada[i] = EMPTY_VALUE;
         madb[i] = EMPTY_VALUE;
        
      if (trend[i]==-1) PlotPoint(i,mada,madb,pstBuffer);
   }
   
   //
   //
   //
   //
   //
   
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (trend[whichBar] != trend[whichBar+1])
         if (trend[whichBar] == 1)
               doAlert("up");
         else  doAlert("down");
   }
return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     1
#define _priceInstancesSize 4
double  _priceWorkHa[][_priceInstances*_priceInstancesSize];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars, int instanceNo=0)
{
  if (tprice>=pr_haclose)
   {
      if (ArrayRange(_priceWorkHa,0)!= bars) ArrayResize(_priceWorkHa,bars); instanceNo*=_priceInstancesSize; int r = #ifdef __MQL4__ bars-i-1 #else i #endif;
         
         //
         //
         //
         //
         //
         
         double haOpen  = (r>0) ? (_priceWorkHa[r-1][instanceNo+2] + _priceWorkHa[r-1][instanceNo+3])/2.0 : (open[i]+close[i])/2;;
         double haClose = (open[i]+high[i]+low[i]+close[i]) / 4.0;
         if (_prHABF(tprice))
               if (high[i]!=low[i])
                     haClose = (open[i]+close[i])/2.0+(((close[i]-open[i])/(high[i]-low[i]))*MathAbs((close[i]-open[i])/2.0));
               else  haClose = (open[i]+close[i])/2.0; 
         double haHigh  = fmax(high[i], fmax(haOpen,haClose));
         double haLow   = fmin(low[i] , fmin(haOpen,haClose));

         //
         //
         //
         //
         //
         
         if(haOpen<haClose) { _priceWorkHa[r][instanceNo+0] = haLow;  _priceWorkHa[r][instanceNo+1] = haHigh; } 
         else               { _priceWorkHa[r][instanceNo+0] = haHigh; _priceWorkHa[r][instanceNo+1] = haLow;  } 
                              _priceWorkHa[r][instanceNo+2] = haOpen;
                              _priceWorkHa[r][instanceNo+3] = haClose;
         //
         //
         //
         //
         //
         
         switch (tprice)
         {
            case pr_haclose:
            case pr_habclose:    return(haClose);
            case pr_haopen:   
            case pr_habopen:     return(haOpen);
            case pr_hahigh: 
            case pr_habhigh:     return(haHigh);
            case pr_halow:    
            case pr_hablow:      return(haLow);
            case pr_hamedian:
            case pr_habmedian:   return((haHigh+haLow)/2.0);
            case pr_hamedianb:
            case pr_habmedianb:  return((haOpen+haClose)/2.0);
            case pr_hatypical:
            case pr_habtypical:  return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:
            case pr_habweighted: return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:  
            case pr_habaverage:  return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
            case pr_habtbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
            case pr_hatbiased2:
            case pr_habtbiased2:
               if (haClose>haOpen)  return(haHigh);
               if (haClose<haOpen)  return(haLow);
                                    return(haClose);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (tprice)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
      case pr_tbiased2:   
               if (close[i]>open[i]) return(high[i]);
               if (close[i]<open[i]) return(low[i]);
                                     return(close[i]);        
   }
   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);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#define _smoothInstances     2
#define _smoothInstancesSize 10
double  _smthWork[][_smoothInstances*_smoothInstancesSize];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iSmooth(double price, double length, double phase, int r, int bars, int instanceNo=0)
{
   if (ArrayRange(_smthWork,0)!=bars) ArrayResize(_smthWork,bars); instanceNo*=_smoothInstancesSize; r = bars-r-1;
   if (price==EMPTY_VALUE) price=0;

   int k = 0; if (r==0) { for(; k<7; k++) _smthWork[0][instanceNo+k]=price; for(; k<10; k++) _smthWork[0][instanceNo+k]=0; return(price); }

      //
      //
      //
      //
      //
  
      double len1   = fmax(log(sqrt(0.5*(length-1)))/log(2.0)+2.0,0);
      double pow1   = fmax(len1-2.0,0.5);
      double del1   = price - _smthWork[r-1][instanceNo+bsmax];
      double del2   = price - _smthWork[r-1][instanceNo+bsmin];
      double div    = 1.0/(10.0+10.0*(fmin(fmax(length-10,0),100))/100);
      int    forBar = (int)fmin(r,10);

         _smthWork[r][instanceNo+volty] = (fabs(del1) > fabs(del2)) ? fabs(del1): (fabs(del1) < fabs(del2)) ? fabs(del2) : 0;
         _smthWork[r][instanceNo+vsum]  = _smthWork[r-1][instanceNo+vsum] + (_smthWork[r][instanceNo+volty]-_smthWork[r-forBar][instanceNo+volty])*div;
        
         //
         //
         //
         //
         //
              
         _smthWork[r][instanceNo+avolty] = _smthWork[r-1][instanceNo+avolty]+(2.0/(fmax(4.0*length,30)+1.0))*(_smthWork[r][instanceNo+vsum]-_smthWork[r-1][instanceNo+avolty]);
         double dVolty = (_smthWork[r][instanceNo+avolty] > 0) ? _smthWork[r][instanceNo+volty]/_smthWork[r][instanceNo+avolty] : 0;  
            if (dVolty > pow(len1,1.0/pow1)) dVolty = pow(len1,1.0/pow1);
            if (dVolty < 1)                  dVolty = 1.0;

         //
         //
         //
         //
         //
        
         double pow2 = pow(dVolty, pow1);
         double len2 = sqrt(0.5*(length-1))*len1;
         double Kv   = pow(len2/(len2+1), sqrt(pow2));

            if (del1 > 0) _smthWork[r][instanceNo+bsmax] = price; else _smthWork[r][instanceNo+bsmax] = price - Kv*del1;
            if (del2 < 0) _smthWork[r][instanceNo+bsmin] = price; else _smthWork[r][instanceNo+bsmin] = price - Kv*del2;

      //
      //
      //
      //
      //
      
      double R     = fmax(fmin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = pow(beta,pow2);

         _smthWork[r][instanceNo+0] = price + alpha*(_smthWork[r-1][instanceNo+0]-price);
         _smthWork[r][instanceNo+1] = (price - _smthWork[r][instanceNo+0])*(1-beta) + beta*_smthWork[r-1][instanceNo+1];
         _smthWork[r][instanceNo+2] = (_smthWork[r][instanceNo+0] + R*_smthWork[r][instanceNo+1]);
         _smthWork[r][instanceNo+3] = (_smthWork[r][instanceNo+2] - _smthWork[r-1][instanceNo+4])*pow((1-alpha),2) + pow(alpha,2)*_smthWork[r-1][instanceNo+3];
         _smthWork[r][instanceNo+4] = (_smthWork[r-1][instanceNo+4] + _smthWork[r][instanceNo+3]);

   //
   //
   //
   //
   //

   return(_smthWork[r][instanceNo+4]);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
void CleanPoint(int i,double& first[],double& second[])
{
   if (i>=Bars-3) return;
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (i>=Bars-2) return;
   if (first[i+1] == EMPTY_VALUE)
      if (first[i+2] == EMPTY_VALUE) 
            { first[i]  = from[i]; first[i+1]  = from[i+1]; second[i] = EMPTY_VALUE; }
      else  { second[i] = from[i]; second[i+1] = from[i+1]; first[i]  = EMPTY_VALUE; }
   else     { first[i]  = from[i];                          second[i] = EMPTY_VALUE; }
}
//
//
//

void doAlert(string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
      if (previousAlert != doWhat || previousTime != Time[0]) {
          previousAlert  = doWhat;
          previousTime   = Time[0];

          //
          //
          //
          //
          //
          
          message =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," kase permission stochastic ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," kase permission stochastic "),message);
             if (alertsSound)   PlaySound(soundFile);
      }
}



