//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1  RoyalBlue
#property indicator_color2  Red
#property indicator_width1  1
#property indicator_width2  1

//
//
//
//
//

extern ENUM_TIMEFRAMES    TimeFrame       = PERIOD_CURRENT;
extern int                NlmPeriod       = 20;
extern ENUM_APPLIED_PRICE NlmPrice        = PRICE_CLOSE;
extern double             PctFilter       = 0;
extern int                Shift           = 0;
extern bool               alertsOn        = true;
extern bool               alertsOnCurrent = false;
extern bool               alertsMessage   = true;
extern bool               alertsSound     = false;
extern bool               alertsNotify    = true;
extern bool               alertsEmail     = false;
extern bool               DotsOnFirst     = false;

//
//
//
//
//

double nlmDa[];
double nlmDb[];
double trend[];
double nlm[];
double work[][2];
#define _change 0
#define _achang 1

string indicatorFileName;
bool   returnBars;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(4);
   SetIndexBuffer(0,nlmDa); SetIndexStyle(0,DRAW_ARROW); SetIndexArrow(0,159);
   SetIndexBuffer(1,nlmDb); SetIndexStyle(1,DRAW_ARROW); SetIndexArrow(1,159);
   SetIndexBuffer(2,nlm);
   SetIndexBuffer(3,trend);

      //
      //
      //
      //
      //
         
          indicatorFileName = WindowExpertName();
          returnBars        = (TimeFrame==-99);
          TimeFrame         = MathMax(TimeFrame,_Period);
          for (int i=0; i<3; i++) SetIndexShift(i,Shift*TimeFrame/Period());
   
      //
      //
      //
      //
      //
      
return(0);
}
int deinit() {  return(0); }

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int i,r,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
           int limit=MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { nlmDa[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //

   if (TimeFrame == Period())
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      for(i=limit, r=Bars-i-1; i>=0; i--,r++)
      {
         nlm[i]   = iNonLagMa(iMA(NULL,0,1,0,MODE_SMA,NlmPrice,i),NlmPeriod,i,0);
         nlmDa[i] = EMPTY_VALUE;
         nlmDb[i] = EMPTY_VALUE;
         trend[i] = trend[i+1];

         //
         //
         //
         //
         //
               
         if (PctFilter>0)
         {
            work[r][_change] = MathAbs(nlm[i]-nlm[i+1]);
            work[r][_achang] = work[r][_change];
            for (int k=1; k<NlmPeriod; k++) work[r][_achang] += work[r-k][_change];
                                            work[r][_achang] /= 1.0*NlmPeriod;
    
            double stddev = 0; for (k=0; k<NlmPeriod; k++) stddev += MathPow(work[r-k][_change]-work[r-k][_achang],2);
                   stddev = MathSqrt(stddev/NlmPeriod); 
            double filter = PctFilter * stddev;
            if( MathAbs(nlm[i]-nlm[i+1]) < filter ) nlm[i]=nlm[i+1];
         }

         //
         //
         //
         //
         //
               
         if (nlm[i]>nlm[i+1]) trend[i] =  1;
         if (nlm[i]<nlm[i+1]) trend[i] = -1;
         if (trend[i] == 1)   nlmDa[i] = nlm[i];
         if (trend[i] ==-1)   nlmDb[i] = nlm[i]; 
      }
   manageAlerts();
   return(0);
   }
   
   //
   //
   //
   //
   //
   
   int displace = -1; if (DotsOnFirst) displace = 1;
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   for (i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,TimeFrame,Time[i]);
      int x = iBarShift(NULL,TimeFrame,Time[i+displace]);
      if (x!=y)
      { 
         nlmDa[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,NlmPeriod,NlmPrice,PctFilter,0,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,0,y);
         nlmDb[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,NlmPeriod,NlmPrice,PctFilter,0,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,1,y);
      }
   }   
   return(0);
         
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; 
      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(_Period)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," NonLagMA trend changed to ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," NonLagMA "),message);
             if (alertsSound)   PlaySound("alert2.wav");
       
   }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

#define Pi       3.14159265358979323846264338327950288
#define _length  0
#define _len     1
#define _weight  2

double  nlmvalues[3][1];
double  nlmprices[ ][1];
double  nlmalphas[ ][1];

//
//
//
//
//

double iNonLagMa(double price, double length, int r, int instanceNo=0)
{
   r = Bars-r-1;
   if (ArrayRange(nlmprices,0) != Bars) ArrayResize(nlmprices,Bars);
                               nlmprices[r][instanceNo]=price;
   if (length<3 || r<3) return(nlmprices[r][instanceNo]);
   
   //
   //
   //
   //
   //
   
   if (nlmvalues[_length][instanceNo] != length)
   {
      double Cycle = 4.0;
      double Coeff = 3.0*Pi;
      int    Phase = length-1;
      
         nlmvalues[_length][instanceNo] = length;
         nlmvalues[_len   ][instanceNo] = length*4 + Phase;  
         nlmvalues[_weight][instanceNo] = 0;

         if (ArrayRange(nlmalphas,0) < nlmvalues[_len][instanceNo]) ArrayResize(nlmalphas,nlmvalues[_len][instanceNo]);
         for (int k=0; k<nlmvalues[_len][instanceNo]; 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;
      
            nlmalphas[k][instanceNo]        = g * beta;
            nlmvalues[_weight][instanceNo] += nlmalphas[k][instanceNo];
         }
   }
   
   //
   //
   //
   //
   //
   
   if (nlmvalues[_weight][instanceNo]>0)
   {
      double sum = 0;
           for (k=0; k < nlmvalues[_len][instanceNo]; k++) sum += nlmalphas[k][instanceNo]*nlmprices[r-k][instanceNo];
           return( sum / nlmvalues[_weight][instanceNo]);
   }
   else return(0);           
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}