//+------------------------------------------------------------------+
//|                                               Schaff TCD RSX.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"


#property indicator_separate_window
#property indicator_buffers    3
#property indicator_color1     DeepSkyBlue
#property indicator_color2     PaleVioletRed
#property indicator_color3     PaleVioletRed
#property indicator_minimum    -10
#property indicator_maximum    110
#property indicator_level1     85
#property indicator_level2     15
#property indicator_levelcolor MediumOrchid

//
//
//
//
//

extern string TimeFrame       = "current time frame";
extern int    FastLength      = 23;
extern int    SlowLength      = 50;
extern int    PeriodLength    = 25;
extern int    MacdPrice       = PRICE_CLOSE;
extern int    RsxLength       = 9;
extern bool   Interpolate     = true;
extern bool   MultiColor      = true;

extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = false;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;

//
//
//
//
//

double strBuffer[];
double strUa[];
double strUb[];
double macdBuffer[];
double signBuffer[];
double trend[];
double alphas[];
double wrkBuffer[][12];

//
//
//
//
//

string indicatorFileName;
bool   calculateSchaff;
bool   returnBars;
int    timeFrame;


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(6);
   SetIndexBuffer(0,strBuffer);
   SetIndexBuffer(1,strUa);
   SetIndexBuffer(2,strUb);
   SetIndexBuffer(3,macdBuffer);
   SetIndexBuffer(4,signBuffer);
   SetIndexBuffer(5,trend);
   
   //
   //
   //
   //
   //
   
   indicatorFileName = WindowExpertName();
   calculateSchaff   = (TimeFrame=="calculateSchaff"); if (calculateSchaff) return(0);
   returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
   timeFrame         = stringToTimeFrame(TimeFrame);
    
   //
   //
   //
   //
   //
    
   IndicatorShortName(timeFrameToString(timeFrame)+" Nonlag Schaff Tcd Rsx  ("+FastLength+","+PeriodLength+","+SlowLength+","+RsxLength+")");
  
   return (0);
}

//
//
//
//
//

int deinit(){ return(0);}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   
   int counted_bars=IndicatorCounted();
   int limit,i,r,n;

   if(counted_bars < 0) return(-1);
   if(counted_bars > 0) counted_bars--;
           limit = MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { strBuffer[0] = MathMin(limit+1,Bars-1); return(0); }
           
           


   //
   //
   //
   //
   //
   
   if (calculateSchaff || timeFrame == Period())
   {
   
   if (MultiColor && trend[limit]==-1) CleanPoint(limit,strUa,strUb);

   //
   //
   //
   //
   //

   
   if (ArrayRange(wrkBuffer,0) != Bars) ArrayResize(wrkBuffer,Bars);
      
      double alpha = 2.0 / (1.0 + PeriodLength);
      double Kg    = (3.0)/(2.0 + RsxLength); 
      double Hg    = 1.0-Kg;

      //
      //
      //
      //
      //
      
      for(i=limit, r=Bars-i-1; i>=0; i--, r++)
      {
         macdBuffer[i] = iNoLagMa(iMA(NULL,0,1,0,MODE_SMA,MacdPrice,i),FastLength,alphas,0,i)-
                         iNoLagMa(iMA(NULL,0,1,0,MODE_SMA,MacdPrice,i),SlowLength,alphas,1,i);
         signBuffer[i] = signBuffer[i+1]+alpha*(macdBuffer[i]-signBuffer[i+1]);
                         
        if (i==(Bars-1)) { for (int c=0; c<12; c++) wrkBuffer[r][c] = 0; continue; }  

        //
        //
        //
        //
        //
      
        double roc = signBuffer[i]-signBuffer[i+1];
        double roa = MathAbs(roc);
        for (int k=0; k<3; k++)
        {
            int kk = k*2;
               wrkBuffer[r][kk+0] = Kg*roc                + Hg*wrkBuffer[r-1][kk+0];
               wrkBuffer[r][kk+1] = Kg*wrkBuffer[r][kk+0] + Hg*wrkBuffer[r-1][kk+1]; roc = 1.5*wrkBuffer[r][kk+0] - 0.5 * wrkBuffer[r][kk+1];
               wrkBuffer[r][kk+6] = Kg*roa                + Hg*wrkBuffer[r-1][kk+6];
               wrkBuffer[r][kk+7] = Kg*wrkBuffer[r][kk+6] + Hg*wrkBuffer[r-1][kk+7]; roa = 1.5*wrkBuffer[r][kk+6] - 0.5 * wrkBuffer[r][kk+7];
        }
        if (roa != 0)
             strBuffer[i] = MathMax(MathMin((roc/roa+1.0)*50.0,100.00),0.00); 
        else strBuffer[i] = 50.0; 
                trend[i]  = trend[i+1];
                
               if (strBuffer[i] > strBuffer[i+1]) trend[i]= 1;
               if (strBuffer[i] < strBuffer[i+1]) trend[i]=-1;
               if (MultiColor && !calculateSchaff && trend[i]==-1) PlotPoint(i,strUa,strUb,strBuffer);
        
        //
        //
        //
        //
        //
        
                                
       }         
      manageAlerts();  
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (MultiColor && trend[limit]==-1) CleanPoint(limit,strUa,strUb);      
   for (i=limit;i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);

         strBuffer[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateSchaff",FastLength,SlowLength,PeriodLength,MacdPrice,RsxLength,0,y);
         strUa[i]     = EMPTY_VALUE;
         strUb[i]     = EMPTY_VALUE;
         trend[i]     = iCustom(NULL,timeFrame,indicatorFileName,"calculateSchaff",FastLength,SlowLength,PeriodLength,MacdPrice,RsxLength,5,y);
         
         //
         //
         //
         //
         //
         
         if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(k = 1; k < n; k++)
            {
              strBuffer[i+k] = strBuffer[i] + (strBuffer[i+n] - strBuffer[i]) * k/n;
               
            }
            }
            if (MultiColor) for (i=limit;i>=0;i--) if (trend[i]==-1) PlotPoint(i,strUa,strUb,strBuffer);

   //
   //
   //
   //
   //
   manageAlerts(); 
   return(0);
}

//
//
//
//
//

double values[][3];
double prices[][1];

#define Pi       3.14159265358979323846264338327950288
#define _length  0
#define _len     1
#define _weight  2

//
//
//
//
//

double iNoLagMa(double price, int length, double &alphasArray[], int forValue, int i)
{
   if (ArrayRange(prices,0) != Bars) ArrayResize(prices,Bars);
            int r = Bars-i-1;  prices[r][forValue]=price;
   if (length<3 || r<3) return(prices[r][forValue]);
   
   //
   //
   //
   //
   //
   
   if (ArrayRange(values,0)<(forValue+1) || values[forValue][_length] != length)
   {
      double Cycle = 4.0;
      double Coeff = 3.0*Pi;
      int    Phase = length-1;
      
      if (ArrayRange(values,0)<forValue+1) ArrayResize(values,forValue+1);

         values[forValue][_length] = length;
         values[forValue][_len]    = length*4 + Phase;  
         values[forValue][_weight] = 0;  
         ArrayResize(alphasArray,values[forValue][_len]);

         for (int k=0; k<values[forValue][_len]-1; k++)
         {
            if (k<=Phase-1) 
                 double t = 1.0 * k/(Phase-1);
            else        t = 1.0 + (k-Phase+1)*(2.0*Cycle-1.0)/(Cycle*length-1.0); 
            double beta = MathCos(Pi*t);
            double g = 1.0/(Coeff*t+1); if (t <= 0.5 ) g = 1;
      
            alphasArray[k]             = g * beta;
            values[forValue][_weight] += alphasArray[k];
         }
   }
   
   //
   //
   //
   //
   //
   
   if (values[forValue][_weight]>0)
   {
      int    len = values[forValue][_len];
      double sum = 0;
           for (k=0; k < len-1; k++) sum += alphasArray[k]*prices[r-k][forValue];      
           return( sum / values[forValue][_weight]);
   }
   else return(0);           
}


void manageAlerts()
{
   if (!calculateSchaff && 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(whichBar,"up");
         if (trend[whichBar] == -1) doAlert(whichBar,"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(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," Non Lag Schaff Tcd changed direction to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Non Lag Schaff Tcd "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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;
      }
}
  

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 char = StringGetChar(s, length);
         if((char > 96 && char < 123) || (char > 223 && char < 256))
                     s = StringSetChar(s, length, char - 32);
         else if(char > -33 && char < 0)
                     s = StringSetChar(s, length, char + 224);
   }
   return(s);
}