//+------------------------------------------------------------------+
//|                                                    iStochTxt.mq4 |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright ""
#property link      ""

#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 Blue
#property indicator_color2 Red
#property indicator_width1 1
#property indicator_width2 1
//----
extern string TimeFrame        = "Current time frame";
extern int   k = 5, s = 3, l = 20;
extern color txtColor         = Brown;
extern bool  alertsOn         = false;
extern bool  alertsMessage    = true;
extern bool  alertsSound      = false;
extern bool  alertsEmail      = false;
//----
int d=3;
//---- buffers
double ExtMapBuffer1[];
double ExtMapBuffer2[];
int    timeFrame;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   SetIndexStyle(0, DRAW_ARROW, STYLE_SOLID, 1);
   SetIndexArrow(0, 241);
   SetIndexBuffer(0, ExtMapBuffer1);
   SetIndexStyle(1, DRAW_ARROW, STYLE_SOLID, 1);
   SetIndexArrow(1, 242);
   SetIndexBuffer(1, ExtMapBuffer2);
   timeFrame = stringToTimeFrame(TimeFrame);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   for(int i = 0; i < ObjectsTotal(); i++)
     {
       if(StringFind(ObjectName(i), "txt_", 0) == 0)
         {
           ObjectDelete(ObjectName(i));
           i--;
         }
     }
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   string on;
   int limit;
	  int counted_bars = IndicatorCounted(); // определим количество просчитаных баров у индикатора
	  if(counted_bars > 0)
	    {
	      counted_bars--;
	    }	
	  limit = MathMin(MathMax(Bars-counted_bars,timeFrame/Period()),Bars-1); // определяем границу до которой рассчитываем значения индикатора
//----
	  for(int i = 0; i < limit; i++)
	    {
	        int y = iBarShift(NULL,timeFrame,Time[i]);
	        int x = iBarShift(NULL,timeFrame,Time[i+1]);
	        if (x==y) continue;
               double mc = iStochastic(NULL, timeFrame, k, d, s, 0, 0, MODE_MAIN, y);
               double mp = iStochastic(NULL, timeFrame, k, d, s, 0, 0, MODE_MAIN, x);
               //----
               ExtMapBuffer1[i] = EMPTY_VALUE;
               ExtMapBuffer2[i] = EMPTY_VALUE;      
               on = "txt_" + Time[i]; ObjectDelete(on);
               //----
               if(mc > l && mp <= l)
               {
                  ExtMapBuffer1[i] = Low[i] - iATR(NULL, 0, 14, i);
                 ObjectCreate(on, OBJ_TEXT, 0, Time[i], Low[i] - 1.5*iATR(NULL, 0, 14, i));
                 ObjectSetText(on, DoubleToStr(Close[i], Digits) + " " + TimeToStr(Time[i], 
                               TIME_MINUTES), 8, "Arial", txtColor);
                               if (y==0) doAlert(i,"up");
               }
               if(mc < 100 - l && mp >= 100 - l)
               {
                 ExtMapBuffer2[i] = High[i] + iATR(NULL, 0, 14, i);         
                 ObjectCreate(on, OBJ_TEXT, 0, Time[i], High[i] + 2*iATR(NULL, 0, 14, i));
                 ObjectSetText(on, DoubleToStr(Close[i], Digits) + " " + TimeToStr(Time[i], 
                               TIME_MINUTES), 8, "Arial", txtColor);
                               if (y==0) doAlert(i,"down");
               }
     }
//----

   return(0);
  }

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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(timeFrameToString(timeFrame)," ",Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," iStoch txt signal ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"iStoch txt "),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   ts = str;

   for (int length=StringLen(str)-1; length>=0; length--)
   {
      int tchar = StringGetChar(ts, length);
         if((tchar > 96 && tchar < 123) || (tchar > 223 && tchar < 256))
                     ts = StringSetChar(ts, length, tchar - 32);
         else if(tchar > -33 && tchar < 0)
                     ts = StringSetChar(ts, length, tchar + 224);
   }
   return(ts);
}