//+------------------------------------------------------------------+
//|                                           NonLinearKalman_v1.mq4 |
//|                           Copyright © 2007, TrendLaboratory Ltd. |
//|            http://finance.groups.yahoo.com/group/TrendLaboratory |
//|                                   E-mail: igorad2003@yahoo.co.uk |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007, TrendLaboratory Ltd."
#property link      "http://finance.groups.yahoo.com/group/TrendLaboratory"
//---- indicator settings
#property indicator_chart_window 
#property indicator_buffers 3
#property indicator_color1 LightBlue 
#property indicator_color2 Salmon
#property indicator_color3 Salmon
#property indicator_width1 2
#property indicator_width2 2
#property indicator_width3 2

//---- indicator parameters
extern int    Price             =  0;  //Price mode : 0-Close,1-Open,2-High,3-Low,4-Median,5-Typical,6-Weighted
extern int    Order             =  3;  //Filter Order: 1-EMA,2-2nd Order,3-3rd Order
extern int    Length            = 14;  //Fast Filter Period 
extern int    PreSmooth         =  3;  //Pre-smoothing period
extern int    PreSmoothMode     =  3;  //Pre-smoothing MA Mode: 0-SMA,1-EMA,2-SMMA,3-LWMA
extern bool   ShowLines         = false;
extern string LinesIdentifier   = "NonLinearKalmanLines1";
extern color  LinesColorForUp   = Green;
extern color  LinesColorForDown = Red;
extern int    LinesStyle        = STYLE_DOT;
extern bool   alertsOn          = true;
extern bool   alertsOnCurrent   = true;
extern bool   alertsMessage     = true;
extern bool   alertsSound       = false;
extern bool   alertsNotify      = true;
extern bool   alertsEmail       = true;
extern string soundFile         = "alert2.wav"; 
//---- indicator buffers
double     Kalman[];
double     Kalmanda[];
double     Kalmandb[];
double     LowPass[];
double     Delta[];
double     slope[];

int        draw_begin;
double     a, b, c, pi = 3.1415926535;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{
//---- indicator buffers mapping
   IndicatorBuffers(6);
   SetIndexBuffer(0,Kalman);
   SetIndexBuffer(1,Kalmanda);
   SetIndexBuffer(2,Kalmandb);
   SetIndexBuffer(3,LowPass);
   SetIndexBuffer(4,Delta);
   SetIndexBuffer(5,slope);
//---- drawing settings
   draw_begin = 2*(Length+3) + PreSmooth;
   SetIndexDrawBegin(0,draw_begin);
//---- name for DataWindow and indicator subwindow label
   IndicatorShortName("NonLinearKalman("+Order+","+Length+","+PreSmooth+")");
   SetIndexLabel(0,"NinLinearKalman");
//----
   if(Order == 1)
   a = 2.0/(1+Length);
   else
   if(Order == 2)
   {
   a = MathExp(-MathSqrt(2)*pi/Length);
	b = 2*a*MathCos(MathSqrt(2)*pi/Length);
   }
   else
   if(Order == 3)
   {
   a = MathExp(-pi/Length);
	b = 2*a*MathCos(MathSqrt(3)*pi/Length);
   c = MathExp(-2*pi/Length);
   } 
//---- initialization done
   return(0);
}

//
//
//
//
//

int deinit()
{
   int lookForLength = StringLen(LinesIdentifier);
   for (int i=ObjectsTotal(); i>=0; i--)
      {
         string name = ObjectName(i);
         if (StringSubstr(name,0,lookForLength)==LinesIdentifier) ObjectDelete(name);
      }
   return(0);
}

//+------------------------------------------------------------------+
//| NonLinearKalman_v1                                               |
//+------------------------------------------------------------------+
//
//

int start()
{
   int limit, i, shift;
   int counted_bars=IndicatorCounted();
   double Smoother, Detrend;
   
   if(counted_bars<1)
   for(i=1;i<=draw_begin;i++) 
   {
   Kalman[Bars-i]=iMA(NULL,0,1,0,0,Price,Bars-i); 
   Kalmanda[i] = EMPTY_VALUE;
   Kalmandb[i] = EMPTY_VALUE;
   LowPass[Bars-i]=iMA(NULL,0,1,0,0,Price,Bars-i); 
   Delta[Bars-i]=0; 
   }
//---- last counted bar will be recounted
   if(counted_bars>0) counted_bars--;
   limit=Bars-counted_bars;

   if (slope[limit]==-1) CleanPoint(limit,Kalmanda,Kalmandb);
   for(shift=limit; shift>=0; shift--)
   {
      Kalmanda[shift] = EMPTY_VALUE;
      Kalmandb[shift] = EMPTY_VALUE;
      Smoother = iMA(NULL,0,PreSmooth,0,PreSmoothMode,Price,shift);
      
      if(Order == 1) 
      {
      LowPass[shift] = (1-a)*LowPass[shift+1] + a*Smoother;
      Detrend = Smoother - LowPass[shift]; 
      Delta[shift] =  (1-a)*Delta[shift+1] + a*Detrend;
      }
      else
		if(Order == 2) 
		{
		LowPass[shift] = b*LowPass[shift+1] - a*a*LowPass[shift+2] + (1 - b + a*a)*Smoother;
		Detrend = Smoother - LowPass[shift]; 
		Delta[shift] = b*Delta[shift+1] - a*a*Delta[shift+2] + (1 - b + a*a)*Detrend;
		}
		else
		if(Order == 3) 
		{
		LowPass[shift] = (b+c)*LowPass[shift+1] - (c+b*c)*LowPass[shift+2] + c*c*LowPass[shift+3] + (1-b+c)*(1-c)*Smoother;
		Detrend = Smoother - LowPass[shift];
		Delta[shift] = (b+c)*Delta[shift+1] - (c+b*c)*Delta[shift+2] + c*c*Delta[shift+3] + (1-b+c)*(1-c)*Detrend;
		}
	   Kalman[shift] = LowPass[shift] + Delta[shift]; 	
	   slope[shift] = slope[shift+1];
	   if (Kalman[shift]>Kalman[shift+1]) slope[shift] = 1;
	   if (Kalman[shift]<Kalman[shift+1]) slope[shift] =-1;
            if (slope[shift]==-1) PlotPoint(shift,Kalmanda,Kalmandb,Kalman);
            
            //
            //
            //
            //
            //
            
            if (ShowLines)
            {
               deleteLine(shift);
               if (slope[shift]!= slope[shift+1])
               if (slope[shift]==1)
                     drawLine(shift,LinesColorForUp);
               else  drawLine(shift,LinesColorForDown);
            } 
   }
   
   //
   //
   //
   //
   //
      
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      if (slope[whichBar] != slope[whichBar+1])
      if (slope[whichBar] == 1)
                doAlert("Buy");
          else  doAlert("Sell");       
   }

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(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," NonLinearKalman ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(StringConcatenate(Symbol(), Period() ," NonLinearKalman " +" "+message));
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," NonLinearKalman "),message);
             if (alertsSound)   PlaySound(soundFile);
      }
}
      

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void deleteLine(int i)
{
   ObjectDelete(LinesIdentifier+":"+Time[i]);
}

//
//
//
//
//

void drawLine(int i, color theColor)
{
   string name = LinesIdentifier+":"+Time[i];
   if (ObjectFind(name)<0)
       ObjectCreate(name,OBJ_VLINE,0,Time[i],0);
       ObjectSet(name,OBJPROP_COLOR,theColor);
       ObjectSet(name,OBJPROP_BACK,true);
       ObjectSet(name,OBJPROP_STYLE,LinesStyle);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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;
      }
}
