//+------------------------------------------------------------------+
//|                                              Stochastic tape.mq4 |
//|                                                           mladen |
//|                                           4 colors by chrisstoff |
//+------------------------------------------------------------------+
#property copyright "mladen & chrisstoff"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers   2
#property indicator_color1    DimGray
#property indicator_color2    Lime
#property indicator_minimum   0
#property indicator_maximum 100
#property indicator_level1   80
#property indicator_level2   20
#property indicator_levelcolor DimGray

//
//
//
//
//

extern string TimeFrame       = "Current time frame";
extern int    KPeriod         = 34;
extern int    Slowing         = 10;
extern int    DPeriod         =  5;
extern int    MAMethod        =  2;
extern int    PriceField      =  0;
extern int    BarsToCount     = 500;
extern bool   ShowTape        = true;
extern color  TapeColorUp     = LimeGreen;
extern color  TapeColorUp2    = Green;
extern color  TapeColorDown   = OrangeRed;
extern color  TapeColorDown2  = Crimson;
extern int    TapeBarsWidth   = 3;
extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = true;
extern bool   alertsMessage   = true;
extern bool   alertsPushNotif = false;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;
extern string UniqueID        = "StochasticTape";

//
//
//
//
//

double StocBuffer[];
double SignBuffer[];
double EmaBuffer1[];
double EmaBuffer2[];
double EmaBuffer3[];
double DiffBuffer[];
double rising[];
double trend[];
string shortName;
int    Window;
int    timeFrame;
string indicatorFileName;
bool   returnBars;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,SignBuffer);
   SetIndexBuffer(1,StocBuffer);
   SetIndexBuffer(2,EmaBuffer1);
   SetIndexBuffer(3,EmaBuffer2);
   SetIndexBuffer(4,EmaBuffer3);
   SetIndexBuffer(5,DiffBuffer);
   SetIndexBuffer(6,rising);
   SetIndexBuffer(7,trend);
   
   //
   //
   //
   //
   //

   indicatorFileName = WindowExpertName();
   returnBars        = TimeFrame=="returnBars";  if (returnBars) { return(0); }
   timeFrame         = stringToTimeFrame(TimeFrame);
   BarsToCount       = MathMax(BarsToCount,300);
   shortName         = timeFrameToString(timeFrame)+" "+UniqueID+" ("+KPeriod+","+DPeriod+","+Slowing+")";
   
   //
   //
   //
   //
   //
   
   IndicatorShortName(shortName);
   return(0);
}

int deinit()
{
   DeleteTape();
   return(0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int start()
{
   int counted_bars=IndicatorCounted();
     if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit=MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { SignBuffer[0] = MathMin(limit+1,Bars-1); return(0); }
         if (timeFrame != Period()) limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
         CheckWindow();

   //
   //
   //
   //
   //

   for (int i=limit;i>=0;i--)
      {
         int y = iBarShift(NULL,timeFrame,Time[i]);
          StocBuffer[i] = iStochastic(NULL,timeFrame,KPeriod,DPeriod,Slowing,MAMethod,PriceField,MODE_MAIN,y);
          SignBuffer[i] = iStochastic(NULL,timeFrame,KPeriod,DPeriod,Slowing,MAMethod,PriceField,MODE_SIGNAL,y);
          DiffBuffer[i] = MathAbs(SignBuffer[i] - StocBuffer[i]);    
              rising[i] = rising[i+1];
              if (DiffBuffer[i]>DiffBuffer[i+1]) rising[i] =  1;
              if (DiffBuffer[i]<DiffBuffer[i+1]) rising[i] = -1;
              trend[i] = trend[i+1];
                  if (StocBuffer[i]>SignBuffer[i]) trend[i] =  1;
                  if (StocBuffer[i]<SignBuffer[i]) trend[i] = -1;
      }   
      DeleteTape(); if (ShowTape) for (i=0; i<BarsToCount ;i++) DrawTape(StocBuffer[i],SignBuffer[i],rising[i],i);
      manageAlerts();

   //
   //
   //
   //
   //
         
   for (i=0;i<indicator_buffers;i++) SetIndexDrawBegin(i,Bars-BarsToCount);
   return(0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

#define SignalName "StocTape"
    int maxLines = 0;

//
//
//
//
//

void DrawTape(double __1, double __2, double trising, int shift)
{
   if (__1==__2) return;
   
   //
   //
   //
   //
   //
   
   maxLines++;
      datetime time = Time[shift];
      string   name = StringConcatenate(UniqueID,SignalName,"-",maxLines);
 
      ObjectCreate(name,OBJ_TREND,Window,time,__1,time,__2);
         if (__1>__2)
         {  
           if (trising==1)
           {  
               ObjectSet(name,OBJPROP_COLOR ,TapeColorUp);
           } else {
               ObjectSet(name,OBJPROP_COLOR ,TapeColorUp2); 
           }
         }         
         else {
           if (trising==1) 
           {
               ObjectSet(name,OBJPROP_COLOR ,TapeColorDown);
           } else {
               ObjectSet(name,OBJPROP_COLOR ,TapeColorDown2);
           }  
         }    
         ObjectSet(name,OBJPROP_RAY   ,false);
         ObjectSet(name,OBJPROP_BACK  ,true);
         ObjectSet(name,OBJPROP_WIDTH ,TapeBarsWidth);
}
void DeleteTape()
{
   string name = StringConcatenate(UniqueID,SignalName);
      while(maxLines>0) { ObjectDelete(StringConcatenate(name,"-",maxLines)); maxLines--; }
                          ObjectDelete(name);
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

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("up");
         if (trend[whichBar] == -1) doAlert("down");
      }
   }
}

//
//
//
//
//

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 = timeFrameToString(Period())+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" stochastic trend changed to "+doWhat;
          if (alertsMessage)   Alert(message);
          if (alertsEmail)     SendMail(StringConcatenate(Symbol()," stochastic tape "),message);
          if (alertsPushNotif) SendNotification(message);
          if (alertsSound)     PlaySound("alert2.wav");
   }
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void CheckWindow()
{
   Window = WindowFind(shortName);
}


//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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);
}