//+------------------------------------------------------------------+
//|                                                          CMA.mq4 |
//|                                                             Raff |
//|                                          just_raff1410@yahoo.com |
//+------------------------------------------------------------------+

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 Yellow
#property indicator_color2 Aqua
#property indicator_color3 Red
#property indicator_width1 2
#property indicator_width2 2
#property indicator_width3 3

extern int Ma_Period = 2;
extern int Ma_PeriodStd = 5;
extern int Ma_Method = 3;
extern int Ma_Price = 4;
extern int Count_bars = 1500;

double K;
double v1;
double v2;
//---- buffers
double CA[];
double DIR[];
double UpBuffer[];
double DnBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   IndicatorBuffers(4);
   SetIndexStyle(0,DRAW_LINE);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(0,CA);
   SetIndexBuffer(1,UpBuffer);
   SetIndexBuffer(2,DnBuffer);
   SetIndexBuffer(3,DIR);

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   if (Count_bars+1>Bars-2)  Count_bars=Bars-2;
   CA[Count_bars+1]=Close[Count_bars+1];
   for(int i=Count_bars;i>=0;i--)
   {
    v1=MathSqrt(iStdDev(NULL,0,Ma_PeriodStd,0,Ma_Method,Ma_Price,i));
    v2=MathSqrt(MathAbs(CA[i+1]-iMA(NULL,0,Ma_Period,0,Ma_Method,Ma_Price,i)));
    if (v2<v1) {K=0;}
    else {K=1-(v1/v2);}
    CA[i]=CA[i+1]+K*(iMA(NULL,0,Ma_Period,0,Ma_Method,Ma_Price,i)-CA[i+1]);

     DIR[i]=DIR[i+1];
     if (CA[i]-CA[i+1] > 0) DIR[i]= 1; 
     if (CA[i+1]-CA[i] > 0) DIR[i]=-1; 
        if (DIR[i]>0)
        {  
        UpBuffer[i] = CA[i];
        if (DIR[i+1]<0) UpBuffer[i+1]=CA[i+1];
        DnBuffer[i] = EMPTY_VALUE;
        }
        else if (DIR[i]<0) 
        {
        DnBuffer[i] = CA[i];
        if (DIR[i+1]>0) DnBuffer[i+1]=CA[i+1];
        UpBuffer[i] = EMPTY_VALUE;
        }
        
   }
//----
   return(0);
  }
//+------------------------------------------------------------------+