//+------------------------------------------------------------------+
//---- indicator settings
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1  DodgerBlue
#property indicator_color2  Gold

//---- indicator parameters
extern int P = 400;
extern double fast = 2; 
extern double slow = 10;
extern double dK = 3;

//---- indicator buffers
double buf1[];
double buf2[];

double K1, K2;
double AMA, AMA0;
double Noise, Signal;
double ER, SSC;
int MyBars;

int init()
{  
   
//---- вычисляем сглаживающие константы
   K1 = 2/(1+slow);
   K2 = 2/(1+fast)-K1;
      
   Noise = 0;
   for(int j = Bars-2; j >= Bars-P-1; j--) {
      Noise += MathAbs(Open[j] - Open[j+1]);
/*
      abs[O[Bars-2] - O[Bars-1]]
      ...
      abs[O[Bars-P-1] - O[Bars-P]]
*/
   }
       
   AMA0 = Open[Bars-P-1];   
   MyBars = P+1;
   

   SetIndexStyle(0, DRAW_ARROW);
   SetIndexArrow(0, 159);
   SetIndexStyle(1, DRAW_ARROW);
   SetIndexArrow(1, 159);
   
      
   //IndicatorDigits(MarketInfo(Symbol(), MODE_DIGITS) + 1);

   SetIndexBuffer(0, buf1);
   SetIndexBuffer(1, buf2);
   SetIndexDrawBegin(0, P+1);
   SetIndexDrawBegin(1, P+1);
   
   IndicatorShortName("AMASig("+ P + ", " + fast + ", " + slow + ")");      
   return(0);
}
  
int start()
{ 
   if (MyBars >= Bars) return(0);
  
   for(int j = Bars-MyBars-1; j >= 0; j--) {
      Signal = MathAbs(Open[j] - Open[j+P]);            
/*
      abs(O[Bars-MyBars-1] - O[Bars-MyBars-1+P])    
      abs(O[Bars-P-2] - O[Bars-2])
      ...
      abs(O[0] - O[P])
*/
    
      Noise += MathAbs(Open[j] - Open[j+1]) - MathAbs(Open[j+P] - Open[j+P+1]);
/*
      abs(O[Bars-MyBars-1] - O[Bars-MyBars]) - abs(O[Bars-MyBars-1+P] - O[Bars-MyBars+P])
      abs(O[Bars-P-2] - O[Bars-P-1]) - abs(O[Bars-2] - O[Bars-1])
      ...
      abs(O[0] - O[1]) - abs(O[P] - O[P+1])
*/
  	  	   
   	if (Noise > 0) ER = Signal/Noise; else ER = 1;
   	//SSC = MathPow(K1+ER*K2, 2);
   	SSC = (K1+ER*K2)*(K1+ER*K2);
   	
      AMA = AMA0 + SSC*(Open[j]-AMA0);            
/*
      O[Bars-MyBars-1]
      O[Bars-P-2]
      ...
      O[0]
*/

      buf1[j] = -1;
      buf2[j] = -1;
      if (AMA-AMA0 > dK*Point) buf1[j] = AMA;
      if (AMA-AMA0 < -dK*Point) buf2[j] = AMA;

      AMA0 = AMA;
   }
     
   MyBars = Bars;
   return(0);
}