//+------------------------------------------------------------------+
//|                                         Adaptive Laguerre Filter |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1  DeepSkyBlue
#property indicator_color2  DeepSkyBlue
#property indicator_color3  Red
#property indicator_color4  Red
#property indicator_width1  2
#property indicator_width2  1
#property indicator_width3  1

//
//
//
//
//

extern string TimeFrame   = "current time frame";
extern int    LookBack    = 20;
extern int    Median      = 5;
extern int    PriceType   = PRICE_MEDIAN;
extern int    MAPeriod    = 14;
extern int    MAMethod    = MODE_EMA;
extern int    MAPrice     = PRICE_CLOSE;
extern bool   Interpolate = true;
extern bool   ShowMA      = true;

extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = false;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;


//
//
//
//
//

double Filter[];
double ArrowUp[];
double ArrowDn[];
double Diff[];
double sortDiff[];
double state[];
double ma[];

//
//
//
//
//

int    timeFrame;
string IndicatorFileName;
bool   ReturningBars;
bool   CalculatingAlf;

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
//
//
//
//

int init() 
{

   IndicatorBuffers(6);
   SetIndexBuffer(0,Filter);  SetIndexLabel(0,"ALF");
   SetIndexBuffer(1,ArrowUp); SetIndexStyle(1,DRAW_ARROW); SetIndexArrow(1,159);
   SetIndexBuffer(2,ArrowDn); SetIndexStyle(2,DRAW_ARROW); SetIndexArrow(2,159);
   SetIndexBuffer(3,ma);
   SetIndexBuffer(4,Diff);
   SetIndexBuffer(5,state);
      if (ShowMA)
            SetIndexStyle(3,DRAW_LINE);
      else  SetIndexStyle(3,DRAW_NONE);
      Median = MathMin(Median,LookBack); ArrayResize(sortDiff,Median);

   //
   //
   //
   //
   //
         
      IndicatorFileName   = WindowExpertName();
      CalculatingAlf = (TimeFrame=="CalculateAlf"); if (CalculatingAlf) return(0);
      ReturningBars  = (TimeFrame=="returnBars");   if (ReturningBars)  return(0);
      timeFrame      = stringToTimeFrame(TimeFrame);
   
   //
   //
   //
   //
   //
   
   IndicatorShortName("Adaptive Laguerre filter "+timeFrameToString(timeFrame)+" ("+LookBack+","+Median+","+PriceType+")");
   return (0);
}
  
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
//
//
//
//
//
//

double work[][4];
#define L0 0
#define L1 1
#define L2 2
#define L3 3

//
//
//
//
//

int start()
{
   int counted_bars = IndicatorCounted();
   int i,r,limit;
    
   if (counted_bars<0) return(-1);
   if (counted_bars>0) counted_bars--;
      limit = MathMin(Bars-counted_bars,Bars-1);
           if (ReturningBars)  { Filter[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (CalculatingAlf || timeFrame==Period())
   {
      if (ArrayRange(work,0) != Bars) ArrayResize(work,Bars);
      
      //
      //
      //
      //
      //
      
      for (i=limit, r=Bars-i-1; i>=0; i--,r++)
      {
         double price = iMA(NULL,0,1,0,MODE_SMA,PriceType,i); Diff[i] = MathAbs(price - Filter[i+1]);
         double high  = Diff[ArrayMaximum(Diff,LookBack,i)];
         double low   = Diff[ArrayMinimum(Diff,LookBack,i)];
         double alpha = 0.5;

            if (high!=low)
            {
               for (int j=0; j<Median; j++) sortDiff[j] = (Diff[i+j]-low)/(high-low);
               ArraySort(sortDiff,WHOLE_ARRAY,0,MODE_ASCEND);
         
               if (MathMod(Median,2.0) != 0)
                     alpha =  sortDiff[Median/2];         
               else  alpha = (sortDiff[Median/2]+sortDiff[(Median/2)-1])/2.0;
            }
      
         //
         //
         //
         //
         //

         work[r][L0] = (1-alpha)* work[r-1][L0]+alpha*price;
         work[r][L1] = (1-alpha)*(work[r-1][L1]-work[r][L0]) + work[r-1][L0];
         work[r][L2] = (1-alpha)*(work[r-1][L2]-work[r][L1]) + work[r-1][L1];
         work[r][L3] = (1-alpha)*(work[r-1][L3]-work[r][L2]) + work[r-1][L2];
         Filter[i] = (work[r][L0] + 2.0*work[r][L1] + 2.0*work[r][L2] + work[r][L3]) / 6.0;
         ma[i]     = iMA(NULL,0,MAPeriod,0,MAMethod,MAPrice,i);
         
         //
         //
         //
         //
         //

         ArrowUp[i] = EMPTY_VALUE;
         ArrowDn[i] = EMPTY_VALUE;
         state[i]   = state[i+1];
         double atr = iATR(NULL,0,20,i)/2.0;
            if (ma[i]<Filter[i]) state[i] =  1;
            if (ma[i]>Filter[i]) state[i] = -1;
            if (state[i]!= state[i+1])
               if   (state[i] == 1)
                     ArrowDn[i] = High[i]+atr;
               else  ArrowUp[i] = Low[i]+atr;
      }
      
      //
      //
      //
      //
      //
      
      if (!CalculatingAlf) manageAlerts();
      return(0);
   }  
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,IndicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for (i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         Filter[i]  = iCustom(NULL,timeFrame,IndicatorFileName,"CalculateAlfr",LookBack,Median,PriceType,MAPeriod,MAMethod,MAPrice,0,y);
         ma[i]      = iCustom(NULL,timeFrame,IndicatorFileName,"CalculateAlfr",LookBack,Median,PriceType,MAPeriod,MAMethod,MAPrice,3,y);
         ArrowUp[i] = EMPTY_VALUE;
         ArrowDn[i] = EMPTY_VALUE;
            if (iBarShift(NULL,0,iTime(NULL,timeFrame,y)) == i)
            {
               ArrowUp[i] = iCustom(NULL,timeFrame,IndicatorFileName,"CalculateAlfr",LookBack,Median,PriceType,MAPeriod,MAMethod,MAPrice,1,y);
               ArrowDn[i] = iCustom(NULL,timeFrame,IndicatorFileName,"CalculateAlfr",LookBack,Median,PriceType,MAPeriod,MAMethod,MAPrice,2,y);
            }         

         //
         //
         //
         //
         //
      
         if (timeFrame <= Period() || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
         if (!Interpolate) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(int k = 1; k < n; k++)
            {
                Filter[i+k] = Filter[i]+(Filter[i+n]-Filter[i])*k/n;
                ma[i+k]     = ma[i]    +(ma[i+n]    -ma[i]    )*k/n;
            }
   }
   manageAlerts();
   
   //
   //
   //
   //
   //
   
   return (0);   
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      if (ArrowUp[whichBar] != EMPTY_VALUE) doAlert(whichBar,"up");
      if (ArrowDn[whichBar] != EMPTY_VALUE) 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()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," "+timeFrameToString(timeFrame)+" alf close crossed ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"Alf mtf "),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};

//
//
//
//
//

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);
}