schaff_trend_cycle

Author: ht mladen
Miscellaneous
It issuies visual alerts to the screenIt sends emailsIt plays sound alerts
0 Views
0 Downloads
0 Favorites
schaff_trend_cycle
//------------------------------------------------------------------

   #property copyright "mladen"
   #property link      "www.forex-tsd.com"

//------------------------------------------------------------------

#property indicator_separate_window
#property indicator_buffers 5
#property indicator_plots   2

#property indicator_label1  "Schaff trend cycle"
#property indicator_type1   DRAW_FILLING
#property indicator_color1  C'216,237,243',MistyRose
#property indicator_label2  "Schaff trend cycle"
#property indicator_type2   DRAW_COLOR_LINE
#property indicator_color2  DeepSkyBlue,PaleVioletRed
#property indicator_style2  STYLE_SOLID
#property indicator_width2  2

//
//
//
//
//

input ENUM_TIMEFRAMES    TimeFrame     = PERIOD_CURRENT; // Time frame
input int                SchaffPeriod  = 10;             // Schaff cycle period
input int                FastEMAPeriod = 23;             // Fast EMA period
input int                SlowEMAPeriod = 50;             // Slow EMA period
input double             UpLevel       = 80;             // Upper level
input double             DownLevel     = 20;             // Lower level
input ENUM_APPLIED_PRICE Price         = PRICE_CLOSE;    // Price to use
input bool               Interpolate   = true;           // Interpolate mtf data
input bool               alertsOn         = false;       // Alert on trend change
input bool               alertsOnCurrent  = true;        // Alert on current bar
input bool               alertsMessage    = true;        // Display messageas on alerts
input bool               alertsSound      = false;       // Play sound on alerts
input bool               alertsEmail      = false;       // Send email on alerts

//
//
//
//
//

double sfu[];
double sfd[];
double st[];
double colorBuffer[];
double countBuffer[];
ENUM_TIMEFRAMES timeFrame;
int             mtfHandle;
int             atrHandle;
bool            calculating;

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

int OnInit()
{
   SetIndexBuffer(0,sfu,INDICATOR_DATA);
   SetIndexBuffer(1,sfd,INDICATOR_DATA);
   SetIndexBuffer(2,st,INDICATOR_DATA);
   SetIndexBuffer(3,colorBuffer,INDICATOR_COLOR_INDEX); 
   SetIndexBuffer(4,countBuffer,INDICATOR_CALCULATIONS); 

   //
   //
   //
   //
   //
         
      timeFrame   = MathMax(_Period,TimeFrame);
      calculating = (timeFrame==_Period);
      if (!calculating)
            mtfHandle = iCustom(NULL,timeFrame,getIndicatorName(),PERIOD_CURRENT,SchaffPeriod,FastEMAPeriod,SlowEMAPeriod,Price);

   IndicatorSetString(INDICATOR_SHORTNAME,getPeriodToString(timeFrame)+" Schaff trend cycle ("+string(SchaffPeriod)+")");
   return(0);
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

double work[][6];
#define _fastEma 0
#define _slowEma 1
#define _macd    2
#define _fastK   3
#define _fastKK  4
#define _fastD   5

//
//
//
//
//

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[])
{

   //
   //
   //
   //
   //
   
   if (calculating)
   {
      if (ArrayRange(work,0)!=rates_total) ArrayResize(work,rates_total);

         double fastAlpha = 2.0/(1.0+FastEMAPeriod);
         double slowAlpha = 2.0/(1.0+SlowEMAPeriod);
      
         //
         //
         //
         //
         //
         
         for (int i=(int)MathMax(prev_calculated-1,0); i<rates_total; i++)
         {
            double price = getPrice(Price,open,close,high,low,i);
            if (i==0)
            {
               work[i][_fastEma] = 0;
               work[i][_slowEma] = 0;
               work[i][_macd]    = 0;
               work[i][_fastK]   = 0;
               work[i][_fastKK]  = 0;
               work[i][_fastD]   = 0;
               st[i]             = 0;
               continue;
            }
            work[i][_fastEma] = work[i-1][_fastEma]+fastAlpha*(price-work[i-1][_fastEma]);
            work[i][_slowEma] = work[i-1][_slowEma]+slowAlpha*(price-work[i-1][_slowEma]);
            work[i][_macd]    = work[i][_fastEma]-work[i][_slowEma];

            //
            //
            //
            //
            //
      
               double lowMacd  = minValue(work,_macd,SchaffPeriod,i);
               double highMacd = maxValue(work,_macd,SchaffPeriod,i)-lowMacd;
                  if (highMacd > 0)
                        work[i][_fastK] = 100*((work[i][_macd]-lowMacd)/highMacd);
                  else  work[i][_fastK] = work[i-1][_fastK];
                        work[i][_fastD] = work[i-1][_fastD]+0.5*(work[i][_fastK]-work[i-1][_fastD]);

               double lowStoch  = minValue(work,_fastD,SchaffPeriod,i);
               double highStoch = maxValue(work,_fastD,SchaffPeriod,i)-lowStoch;
                  if (highStoch > 0)
                        work[i][_fastKK] = 100*((work[i][_fastD]-lowStoch)/highStoch);
                  else  work[i][_fastKK] = work[i-1][_fastKK];
      
            //
            //
            //
            //
            //
            
            st[i]  = st[i-1]+0.5*(work[i][_fastKK]-st[i-1]);
            sfu[i] = st[i];
            sfd[i] = MathMin(MathMax(DownLevel,st[i]),UpLevel);
               colorBuffer[i]=colorBuffer[i-1];
                  if (st[i]>st[i-1]) colorBuffer[i]=0;
                  if (st[i]<st[i-1]) colorBuffer[i]=1;
         }      
     
         countBuffer[rates_total-1] = MathMax(rates_total-prev_calculated+1,1);
         manageAlerts(time[rates_total-1],time[rates_total-2],colorBuffer,rates_total);
      return(rates_total);
   }
   
   //
   //
   //
   //
   //
   
      datetime times[]; 
      datetime startTime = time[0]-PeriodSeconds(timeFrame);
      datetime endTime   = time[rates_total-1];
         int bars = CopyTime(NULL,timeFrame,startTime,endTime,times);
        
         if (times[0]>time[0] || bars<1) return(rates_total);
               double tst[];   CopyBuffer(mtfHandle,2,0,bars,tst);
               double tcolo[]; CopyBuffer(mtfHandle,3,0,bars,tcolo);
               double count[]; CopyBuffer(mtfHandle,4,0,bars,count);
         int maxb = (int)MathMax(MathMin(count[bars-1]*PeriodSeconds(timeFrame)/PeriodSeconds(_Period),rates_total-1),1);

         //
         //
         //
         //
         //
         
         for(int i=(int)MathMax(prev_calculated-maxb,0); i<rates_total; i++)
         {
            int d = dateArrayBsearch(times,time[i],bars);
            if (d > -1 && d < bars)
            {
               st[i]          = tst[d];
               colorBuffer[i] = tcolo[d];
               sfu[i]         = st[i];
               sfd[i]         = MathMin(MathMax(DownLevel,st[i]),UpLevel);
            }
            if (!Interpolate) continue;
        
            //
            //
            //
            //
            //
         
            int j=MathMin(i+1,rates_total-1);

            if (d!=dateArrayBsearch(times,time[j],bars) || i==j)
            {
               int n,k;
                  for(n = 1; (i-n)> 0 && time[i-n] >= times[d]; n++) continue;	
                  for(k = 1; (i-k)>=0 && k<n; k++)
                  {
                     st[i-k]  = st[i] + (st[i-n] - st[i]  )*k/n;
                     sfu[i-k] = st[i-k];
                     sfd[i-k] = MathMin(MathMax(DownLevel,st[i-k]),UpLevel);
                  }                  
            }
            
         }

   //
   //
   //
   //
   //
   
   manageAlerts(times[bars-1],times[bars-2],tcolo,bars);
   return(rates_total);
}



//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double minValue(double& array[][6],int useValue, int period, int shift)
{
   double minValue = array[shift][useValue];
            for (int i=1; i<period && (shift-i)>=0; i++) minValue = MathMin(minValue,array[shift-i][useValue]);
   return(minValue);
}
double maxValue(double& array[][6],int useValue, int period, int shift)
{
   double maxValue = array[shift][useValue];
            for (int i=1; i<period && (shift-i)>=0; i++) maxValue = MathMax(maxValue,array[shift-i][useValue]);
   return(maxValue);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void manageAlerts(datetime currTime, datetime prevTime, double& trend[], int bars)
{
   if (alertsOn)
   {
      datetime time     = currTime;
      int      whichBar = bars-1; if (!alertsOnCurrent) { whichBar = bars-2; time = prevTime; }
         
      //
      //
      //
      //
      //
         
      if (trend[whichBar] != trend[whichBar-1])
      {
         if (trend[whichBar] == 0) doAlert(time,"up");
         if (trend[whichBar] == 1) doAlert(time,"down");
      }         
   }
}   

//
//
//
//
//

void doAlert(datetime forTime, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != forTime) 
   {
      previousAlert  = doWhat;
      previousTime   = forTime;

      //
      //
      //
      //
      //

      message = TimeToString(TimeLocal(),TIME_SECONDS)+" "+_Symbol+" "+getPeriodToString(timeFrame)+" Schaff trend changed to "+doWhat;
         if (alertsMessage) Alert(message);
         if (alertsEmail)   SendMail(_Symbol+" Schaff trend cycle",message);
         if (alertsSound)   PlaySound("alert2.wav");
   }
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

double getPrice(ENUM_APPLIED_PRICE price,const double& open[], const double& close[], const double& high[], const double& low[], int i)
{
   switch (price)
   {
      case PRICE_CLOSE:     return(close[i]);
      case PRICE_OPEN:      return(open[i]);
      case PRICE_HIGH:      return(high[i]);
      case PRICE_LOW:       return(low[i]);
      case PRICE_MEDIAN:    return((high[i]+low[i])/2.0);
      case PRICE_TYPICAL:   return((high[i]+low[i]+close[i])/3.0);
      case PRICE_WEIGHTED:  return((high[i]+low[i]+close[i]+close[i])/4.0);
   }
   return(0);
}
  
//
//
//
//
//

string getIndicatorName()
{
   string progPath    = MQL5InfoString(MQL5_PROGRAM_PATH);
   string toFind      = "MQL5\\Indicators\\";
   int    startLength = StringFind(progPath,toFind)+StringLen(toFind);
         
         string indicatorName = StringSubstr(progPath,startLength);
                indicatorName = StringSubstr(indicatorName,0,StringLen(indicatorName)-4);
   return(indicatorName);
}

//
//
//
//
//
 
string getPeriodToString(int period)
{
   int i;
   static int    _per[]={1,2,3,4,5,6,10,12,15,20,30,0x4001,0x4002,0x4003,0x4004,0x4006,0x4008,0x400c,0x4018,0x8001,0xc001};
   static string _tfs[]={"1 minute","2 minutes","3 minutes","4 minutes","5 minutes","6 minutes","10 minutes","12 minutes",
                         "15 minutes","20 minutes","30 minutes","1 hour","2 hours","3 hours","4 hours","6 hours","8 hours",
                         "12 hours","daily","weekly","monthly"};
   
   if (period==PERIOD_CURRENT) 
       period = Period();   
            for(i=0;i<20;i++) if(period==_per[i]) break;
   return(_tfs[i]);   
}


//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

int dateArrayBsearch(datetime& times[], datetime toFind, int total)
{
   int mid   = 0;
   int first = 0;
   int last  = total-1;
   
   while (last >= first)
   {
      mid = (first + last) >> 1;
      if (toFind == times[mid] || (mid < (total-1) && (toFind > times[mid]) && (toFind < times[mid+1]))) break;
      if (toFind <  times[mid])
            last  = mid - 1;
      else  first = mid + 1;
   }
   return (mid);
}

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---