//https://www.mql5.com/en/forum/173478/page18
//+------------------------------------------------------------------+
//|                                           Schaff Trend Cycle.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1  Orange
#property indicator_color2  LimeGreen
#property indicator_color3  LimeGreen
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2

//
//
//
//
//

extern ENUM_TIMEFRAMES    TimeFrame       = PERIOD_CURRENT;
extern int                STCPeriod       = 10;
extern ENUM_APPLIED_PRICE STCPrice        = PRICE_CLOSE;
extern int                FastMAPeriod    = 23;
extern int                SlowMAPeriod    = 50;
extern int                CDPeriod        = 25;
extern double             sm              = 2;
extern int                LevelForUp      = 90;
extern int                LevelForDown    = 10;
extern bool               alertsOn        = false;
extern bool               alertsOnCurrent = true;
extern bool               alertsMessage   = true;
extern bool               alertsPushNotif = false;
extern bool               alertsSound     = false;
extern bool               alertsEmail     = false;

double stcBuffer[];
double stcBufferUA[];
double stcBufferUB[];
double macdBuffer[];
double cdBuffer[];
double fastKBuffer[];
double fastDBuffer[];
double fastKKBuffer[];
double trend[];
double cross[];

string indicatorFileName;
bool   returnBars;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
      SetIndexBuffer(0,stcBuffer);
      SetIndexBuffer(1,stcBufferUA);
      SetIndexBuffer(2,stcBufferUB);
      SetIndexBuffer(3,macdBuffer);
      SetIndexBuffer(4,fastKBuffer);
      SetIndexBuffer(5,fastDBuffer);
      SetIndexBuffer(6,fastKKBuffer);
      SetIndexBuffer(7,cdBuffer);
      
         indicatorFileName = WindowExpertName();
         returnBars        = TimeFrame == -99;
         TimeFrame         = MathMax(TimeFrame,_Period);
         
   IndicatorShortName(timeFrameToString(TimeFrame)+" Schaff Trend Cycle 1 ("+STCPeriod+","+FastMAPeriod+","+SlowMAPeriod+")");
   return(0);
}

int deinit()
{
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
{
   int i,r,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) { stcBuffer[0] = limit+1; return(0); }
         if (ArraySize(trend)!=Bars) ArrayResize(trend,Bars);
         if (ArraySize(cross)!=Bars) ArrayResize(cross,Bars);
         if (TimeFrame!=Period())
         {
            limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
            if (trend[Bars-limit-1]==-1) CleanPoint(limit,stcBufferUA,stcBufferUB);
            for(i = limit,r=Bars-i-1; i >= 0; i--,r++)
            {
               int y = iBarShift(NULL,TimeFrame,Time[i]);               
                  stcBuffer[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,STCPeriod,STCPrice,FastMAPeriod,SlowMAPeriod,CDPeriod,sm,LevelForUp,LevelForDown,alertsOn,alertsOnCurrent,alertsMessage,alertsPushNotif,alertsSound,alertsEmail,0,y);
                  stcBufferUA[i] = EMPTY_VALUE;
                  stcBufferUB[i] = EMPTY_VALUE;
                  trend[r]       = trend[r-1];      
                     if (stcBuffer[i] > stcBuffer[i+1]) trend[r] = 1;
                     if (stcBuffer[i] < stcBuffer[i+1]) trend[r] =-1;
                     if (trend[r] == 1) PlotPoint(i,stcBufferUA,stcBufferUB,stcBuffer);
            }
            return(0);                  
         }
         

   //
   //
   //
   //
   //
      
   double alphaCD = sm / (1.0 + CDPeriod);
   if (trend[Bars-limit-1]==1) CleanPoint(limit,stcBufferUA,stcBufferUB);
   for(i = limit,r=Bars-i-1; i >= 0; i--,r++)
   {
      macdBuffer[i] = iMA(NULL,0,FastMAPeriod,0,MODE_EMA,STCPrice,i)-
                      iMA(NULL,0,SlowMAPeriod,0,MODE_EMA,STCPrice,i);  
      cdBuffer[i]   = cdBuffer[i+1]+alphaCD*(macdBuffer[i]-cdBuffer[i+1]);
   
      //
      //
      //
      //
      //
      
         double lowCd  = minValue(cdBuffer,i);
         double highCd = maxValue(cdBuffer,i)-lowCd;
            if (highCd > 0)
                  fastKBuffer[i] = 100*((cdBuffer[i]-lowCd)/highCd);
            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]);
         
         //
         //
         //
         //
         //

         trend[r]=trend[r-1];      
         cross[r]=cross[r-1];      
               if (stcBuffer[i] >= LevelForUp)   cross[r] =  1;
               if (stcBuffer[i] <= LevelForDown) cross[r] = -1;
         stcBufferUA[i] = EMPTY_VALUE;
         stcBufferUB[i] = EMPTY_VALUE;
            if (stcBuffer[i] > stcBuffer[i+1]) trend[r] = 1;
            if (stcBuffer[i] < stcBuffer[i+1]) trend[r] =-1;
            if (trend[r] == 1) PlotPoint(i,stcBufferUA,stcBufferUB,stcBuffer);
   }   
   manageAlerts();
   return(0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   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 (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 manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0; whichBar = Bars-whichBar-1;
      if (cross[whichBar] != cross[whichBar-1])
      {
         if (cross[whichBar] ==  1) doAlert(0,"up");
         if (cross[whichBar] == -1) doAlert(0,"down");
      }         
   }
}

//
//
//
//
//

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(Symbol(),timeFrameToString(_Period)+" at ",TimeToStr(TimeLocal(),TIME_SECONDS)," Schaff trend cycle signal ",doWhat);
          if (alertsMessage)   Alert(message);
          if (alertsEmail)     SendMail(StringConcatenate(Symbol()," Schaff trend cycle"),message);
          if (alertsPushNotif) SendNotification(StringConcatenate(Symbol()," Schaff trend cycle "+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};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}