//+------------------------------------------------------------------+
//|                                           Schaff Trend Cycle.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1  PaleVioletRed
#property indicator_minimum -1.1
#property indicator_maximum +1.1
#property indicator_width1  2

//
//
//
//
//

extern string TimeFrame       = "current time frame";
extern int    STCPeriod       = 10;
extern int    FastMAPeriod    = 23;
extern int    SlowMAPeriod    = 50;

extern string note            = "turn on Alert = true";
extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = true;
extern bool   alertsEmail     = false;
extern string soundfile       = "alert2.wav";

double stcSlope[];
double stcBuffer[];
double macdBuffer[];
double fastKBuffer[];
double fastDBuffer[];
double fastKKBuffer[];
string indicatorFileName;
bool   calculateValue;
bool   returnBars;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(6);
   SetIndexBuffer(0,stcSlope);
   SetIndexBuffer(1,stcBuffer);
   SetIndexBuffer(2,macdBuffer);
   SetIndexBuffer(3,fastKBuffer);
   SetIndexBuffer(4,fastDBuffer);
   SetIndexBuffer(5,fastKKBuffer);
   
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
         returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
   
      IndicatorShortName(timeFrameToString(timeFrame)+" Schaff Trend Cycle binary ("+STCPeriod+","+FastMAPeriod+","+SlowMAPeriod+")");
   return(0);
}
int deinit() { 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) { stcSlope[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame==Period())
   {
      for(int i = limit; i >= 0; i--)
      {
         macdBuffer[i] = iMA(NULL,0,FastMAPeriod,0,MODE_EMA,PRICE_CLOSE,i)-iMA(NULL,0,SlowMAPeriod,0,MODE_EMA,PRICE_CLOSE,i);

            double lowMacd  = minValue(macdBuffer,i);
            double highMacd = maxValue(macdBuffer,i)-lowMacd;
               if (highMacd > 0)
                     fastKBuffer[i] = 100*((macdBuffer[i]-lowMacd)/highMacd);
               else  fastKBuffer[i] = fastKBuffer[i+1];
                     fastDBuffer[i] = fastDBuffer[i+1]+0.5*(fastKBuffer[i]-fastDBuffer[i+1]);
               
            double lowStoch  = minValue(fastDBuffer,i);
            double highStoch = maxValue(fastDBuffer,i)-lowStoch;
               if (highStoch > 0)
                     fastKKBuffer[i] = 100*((fastDBuffer[i]-lowStoch)/highStoch);
               else  fastKKBuffer[i] = fastKKBuffer[i+1];
                     stcBuffer[i]    = stcBuffer[i+1]+0.5*(fastKKBuffer[i]-stcBuffer[i+1]);
                  
         //
         //
         //
         //
         //
         
         stcSlope[i] = stcSlope[i+1];
            if (stcBuffer[i]>stcBuffer[i+1]) stcSlope[i] =  1;
            if (stcBuffer[i]<stcBuffer[i+1]) stcSlope[i] = -1;
      }
      
      if (alertsOn)
      {
         if (alertsOnCurrent)
              int whichBar = 0;
         else     whichBar = 1;

         //
         //
         //
         //
         //
         
         if (stcSlope[whichBar] != stcSlope[whichBar+1])
         if (stcSlope[whichBar] == 1)
               doAlert("uptrend");
         else  doAlert("downtrend");       
      }
      return(0);
   }
   
   //
   //
   //
   //
   //

   
   limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for (i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         stcSlope[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",STCPeriod,FastMAPeriod,SlowMAPeriod,"",alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,soundfile,0,y);
   }
   return(0);
         
}
//+------------------------------------------------------------------+


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(timeFrameToString(Period())+" "+Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," STC binary ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"   STC binary "),message);
             if (alertsSound)   PlaySound(soundfile);
      }
} 
   
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double minValue(double& array[],int shift)
{
   double minValue = array[shift];
            for (int i=1; i<STCPeriod; i++) minValue = MathMin(minValue,array[shift+i]);
   return(minValue);
}
double maxValue(double& array[],int shift)
{
   double maxValue = array[shift];
            for (int i=1; i<STCPeriod; i++) maxValue = MathMax(maxValue,array[shift+i]);
   return(maxValue);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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);
}