//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
#property copyright "www,forex-tsd.com"
#property link      "www,forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1  PaleVioletRed
#property indicator_width1  2
#property indicator_minimum 0
#property indicator_maximum 1

//
//
//
//
//

extern int MaeDevLength = 14;
extern int Price        = PRICE_CLOSE;

double alpha[];
double ma[];

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(2);
      SetIndexBuffer(0,alpha);
      SetIndexBuffer(1,ma);
   return(0);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int i,limit,counted_bars=IndicatorCounted();

      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-counted_bars,Bars-1);

   //
   //
   //
   //
   //

   for(i=limit; i>=0; i--)
   {
      double price = iMA(NULL,0,1,0,MODE_SMA,Price,i+1);
      double dev   = iStdDev(NULL,0,MaeDevLength,0,MODE_SMA,Price,i+1);
      double map   = ma[i+1];
      static bool first = true;
         if (first) { first=false; map=price; }
      
         //
         //
         //
         //
         //
         
         double mae = iMae(price,map,MaeDevLength,i);
         if (dev!=0)
               alpha[i] = MathMin(mae/dev,1);
         else  alpha[i] = 1;
         ma[i] = ma[i+1]+alpha[i]*(iMA(NULL,0,1,0,MODE_SMA,Price,i)-ma[i+1]);
   }
   return(0);           
}


//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

double workMae[][2];
double iMae(double price, double value, double length, int i)
{
   if (ArrayRange(workMae,0)!=Bars) ArrayResize(workMae,Bars); i = Bars-i-1;
   
      workMae[i][0] = price;
      workMae[i][1] = value;

   double mae = 0; for (int k=0; k<length; k++) mae += MathAbs(workMae[i-k][0]-workMae[i-k][1]); 
   return(mae / length);
}