//+------------------------------------------------------------------+
//|                                         Ehlers non linear filter |
//|                                                                  |
//| original described in TASC 2001 volume 4                         |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1  LimeGreen
#property indicator_color2  Orange
#property indicator_color3  Orange
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2

//
//
//
//
//

extern int    Length   = 20;
extern int    Momentum =  5;
extern int    Price    = PRICE_CLOSE;
extern double SmoothPeriod = 5;
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 filter[];
double filterda[];
double filterdb[];
double cross[];

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init() 
{ 
   IndicatorBuffers(4);
   SetIndexBuffer(0,filter); 
   SetIndexBuffer(1,filterda); 
   SetIndexBuffer(2,filterdb); 
   SetIndexBuffer(3,cross); 
   
   return(0); 
}
int start()
{
   int counted_bars = IndicatorCounted();
   int i,limit;

      if(counted_bars < 0) return(-1);
      if(counted_bars > 0) counted_bars--;
           limit = MathMin(Bars-counted_bars,Bars-1);

   //
   //
   //
   //
   //
   
   if (cross[limit]==-1) CleanPoint(limit,filterda,filterdb);
   for(i=limit; i>=0; i--)
   {
      double price = iMA(NULL,0,1,0,MODE_SMA,Price,i);
      filter[i]   = iSsm(iEhlers(price,Length,Momentum,0,i),SmoothPeriod,i);
      filterda[i] = EMPTY_VALUE;
      filterdb[i] = EMPTY_VALUE;
      cross[i]    = cross[i+1];
         if (price>filter[i]) cross[i] =  1;
         if (price<filter[i]) cross[i] = -1;
         if (cross[i]==-1) PlotPoint(i,filterda,filterdb,filter);
   }         
   manageAlerts();
   return(0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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;
      }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double  enlf_work[][1];

//
//
//
//
//

double  iEhlers(double price,int length, int momentumLength, int s, int i)
{   
   if (ArrayRange(enlf_work,0)!=Bars) ArrayResize(enlf_work,Bars);
   
   int r = Bars-i-1;
   
   //
   //
   //
   //
   //
      
      enlf_work[r][s] = price;

      double sumCoef = 0;
      double num     = 0;
         for (int k=0; k<length; k++)
         {
            double coeff    = MathAbs(enlf_work[r-k][s]-enlf_work[r-k-momentumLength][s]);
                   sumCoef += coeff;
                   num     += coeff*enlf_work[r-k][s];
         } 
      if (sumCoef !=0)
            return(num/sumCoef);
      else  return(0);       
}

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

double workSsm[][2];
#define _price  0
#define _ssm    1

double workSsmCoeffs[][4];
#define _period 0
#define _c1     1
#define _c2     2
#define _c3     3
#define Pi 3.14159265358979323846264338327950288

//
//
//
//
//

double iSsm(double price, double period, int i, int instanceNo=0)
{
   if (ArrayRange(workSsm,0) !=Bars)                 ArrayResize(workSsm,Bars);
   if (ArrayRange(workSsmCoeffs,0) < (instanceNo+1)) ArrayResize(workSsmCoeffs,instanceNo+1);
   if (workSsmCoeffs[instanceNo][_period] != period)
   {
      workSsmCoeffs[instanceNo][_period] = period;
      double a1 = MathExp(-1.414*Pi/period);
      double b1 = 2.0*a1*MathCos(1.414*Pi/period);
         workSsmCoeffs[instanceNo][_c2] = b1;
         workSsmCoeffs[instanceNo][_c3] = -a1*a1;
         workSsmCoeffs[instanceNo][_c1] = 1.0 - workSsmCoeffs[instanceNo][_c2] - workSsmCoeffs[instanceNo][_c3];
   }

   //
   //
   //
   //
   //

   int s = instanceNo*2;   
      i = Bars-i-1;
      workSsm[i][s+_price] = price;
      if (i>3)
      {
          workSsm[i][s+_ssm]   = workSsmCoeffs[instanceNo][_c1]*(workSsm[i][s+_price]+workSsm[i-1][s+_price])/2.0 + 
                                 workSsmCoeffs[instanceNo][_c2]*workSsm[i-1][s+_ssm]                              + 
                                 workSsmCoeffs[instanceNo][_c3]*workSsm[i-2][s+_ssm];
      }
      else workSsm[i][s+_ssm] = price;
   return(workSsm[i][s+_ssm]);
}

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

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      
      //
      //
      //
      //
      //
      
      static string   alertType1 = "";
      static datetime alertTime1 = 0;
      if (cross[whichBar] != cross[whichBar+1])
      {
         if (cross[whichBar] ==  1) doAlert(alertType1,alertTime1,"Price crossed filter value up");
         if (cross[whichBar] == -1) doAlert(alertType1,alertTime1,"Price crossed filter value down");
      }
   }
}

//
//
//
//
//

void doAlert(string& previousAlert, datetime& previousTime, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[0]) {
       previousAlert  = doWhat;
       previousTime   = Time[0];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS),"  ",doWhat);
          if (alertsMessage)   Alert(message);
          if (alertsEmail)     SendMail(StringConcatenate(Symbol(),"Ehlers nonlinear filter"),message);
          if (alertsPushNotif) SendNotification(StringConcatenate(Symbol(),"Ehlers nonlinear filter "+message));
          if (alertsSound)     PlaySound("alert2.wav");
   }
}
