//+------------------------------------------------------------------+
//|                                                stoch crosses.mq4 |
//+------------------------------------------------------------------+

#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1  clrDarkGreen
#property indicator_color2  clrCrimson
#property strict

enum enArrowsOn
{
   arr_onKD_cross,        // Show arrows on stoch/signal cross
   arr_onK_OBOScross,     // Show arrows on stoch leaving OB/OS
   arr_onD_OBOScross      // Show arrows on stoch signal leaving OB/OS
};

input int            KPeriod         = 5;               // Stochastic K period
input int            DPeriod         = 3;               // Stochastic D period
input int            Slowing         = 3;               // Stochastic slowing
input ENUM_MA_METHOD MA_Method       = MODE_SMA;        // Stochastic ma type
input ENUM_STO_PRICE PriceField      = 0;               // Stochastic price
input enArrowsOn     arrowsOn        = arr_onKD_cross;  
input double         OverBoughtLevel = 80;              // Overbought level
input double         OverSoldLevel   = 20;              // Oversold level
input bool           alertsOn        = false;           // Alerts on true/false?
input bool           alertsOnCurrent = false;           // Alerts current bar true/false?
input bool           alertsMessage   = false;           // Alerts message true/false?
input bool           alertsSound     = false;           // Alerts sound true/false?
input bool           alertsEmail     = false;           // Alerts email true/false?
input bool           alertsNotify    = false;           // Alerts notification true/false?
input string         soundFile       = "alert2.wav";    // Alerts Sound file
input int            ArrowCodeUp     = 251;             // Arrow code up
input int            ArrowCodeDn     = 242;             // Arrow code down
input double         ArrowGapUp      = 0.5;             // Gap for arrow up        
input double         ArrowGapDn      = 0.5;             // Gap for arrow down
input int            ArrowSizeUp     = 2;               // Arrow up size
input int            ArrowSizeDn     = 2;               // Arrow down size
//button template start1; copy and paste
extern string             button_note1          = "------------------------------";
extern int                btn_Subwindow         = 0;
extern string             UniqueButtonID        = "StochShortArrows";
extern ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER; 
extern string             btn_text              = "SHORT";
extern string             btn_Font              = "Arial";
extern int                btn_FontSize          = 10;                        
extern color              btn_text_ON_color     = clrWhite;
extern color              btn_text_OFF_color    = clrRed;
extern color              btn_background_color  = clrDimGray;
extern color              btn_border_color      = clrBlack;
extern int                button_x              = 80;                                   
extern int                button_y              = 33;                                   
extern int                btn_Width             = 60;                                
extern int                btn_Height            = 20;                               
extern string             button_note2          = "------------------------------";

bool show_data = true, recalc    = true;
string indicatorFileName, IndicatorName, IndicatorObjPrefix,buttonId;
//button template end1; copy and paste

double CrossUp[],CrossDn[],trend[];
//+------------------------------------------------------------------------------------------------------------------+
//button template start2; copy and paste
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;

   indicatorFileName = WindowExpertName();
   
   ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, 1);
   buttonId = IndicatorObjPrefix + UniqueButtonID + 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);
   
   init2();
   
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------------------------------------------------------+
void OnDeinit(const int reason) { 
     ObjectsDeleteAll(ChartID(), IndicatorObjPrefix);
}
//+------------------------------------------------------------------+
void createButton(string buttonID,string buttonText,int width2,int height,string font,int fontSize,color bgColor,color borderColor,color txtColor)
{
      ObjectDelete    (0,buttonID);
      ObjectCreate    (0,buttonID,OBJ_BUTTON,btn_Subwindow,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,width2);
      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;
   }
}
//+------------------------------------------------------------------------------------------------------------------+
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_ARROW);
     
   if (show_data)
      {
       ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_ON_color); 
      }
      else
      {
        ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_OFF_color);
        for (int banzai2=0; banzai2<indicator_buffers; banzai2++)
            SetIndexStyle(banzai2,DRAW_NONE);
      }
}
//button template end2; copy and paste
//+------------------------------------------------------------------------------------------------------------------+

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

int init2()
{
   IndicatorBuffers(3);   
   SetIndexBuffer(0, CrossUp,INDICATOR_DATA);  SetIndexStyle(0,DRAW_ARROW,0,ArrowSizeUp); SetIndexArrow(0,ArrowCodeUp);
   SetIndexBuffer(1, CrossDn,INDICATOR_DATA);  SetIndexStyle(1,DRAW_ARROW,0,ArrowSizeDn); SetIndexArrow(1,ArrowCodeDn);
   SetIndexBuffer(2, trend);     
return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//

int  OnCalculate(const int rates_total,const int prev_calculated,const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   int i=rates_total-prev_calculated+1; if (i>=rates_total) i=rates_total-1; 
   
   //
   //
   //
         
   for (; i>=0 && !_StopFlag; i--)
   {
       double stoNow = iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MA_Method,PriceField,MODE_MAIN,i);
       double stoPre = iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MA_Method,PriceField,MODE_MAIN,i+1);
       double sigNow = iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MA_Method,PriceField,MODE_SIGNAL,i);
       double sigPre = iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MA_Method,PriceField,MODE_SIGNAL,i+1);
       switch(arrowsOn)
       {
          case arr_onK_OBOScross:          trend[i] = (stoNow>OverSoldLevel   && stoPre<OverSoldLevel)   ?  1 : 
                                                      (stoNow<OverBoughtLevel && stoPre>OverBoughtLevel) ? -1 : 0; break;
          case arr_onD_OBOScross:          trend[i] = (sigNow>OverSoldLevel   && sigPre<OverSoldLevel)   ?  1 : 
                                                      (sigNow<OverBoughtLevel && sigPre>OverBoughtLevel) ? -1 : 0; break;
          default :  if (i<rates_total-1)  trend[i] = (stoNow>sigNow && stoPre<sigPre) ?  1 : 
                                                      (stoNow<sigNow && stoPre>sigPre) ? -1 : trend[i+1];
       }              
       if (i<rates_total-1 && trend[i]!=trend[i+1])
       {
           if (trend[i] ==  1) CrossUp[i] =  low[i] - iATR(NULL,0,15,i)*ArrowGapUp;
           if (trend[i] == -1) CrossDn[i] = high[i] + iATR(NULL,0,15,i)*ArrowGapDn;
       }
    }
    
    //
    //
    //
    //
    //
    
    if (alertsOn)
    {
      int whichBar = (alertsOnCurrent) ? 0 : 1;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] == 1) doAlert(whichBar,"buy");
         if (trend[whichBar] ==-1) doAlert(whichBar,"sell");
      }         
   }
return(rates_total);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

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 = timeFrameToString(_Period)+" "+_Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" Stochastic crossing "+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(_Symbol+" Stochastic crossing ",message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}