//+------------------------------------------------------------------+
//|                                        TriangularMA centered.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_chart_window
#property indicator_buffers    3
#property indicator_color1     LimeGreen
#property indicator_color2     Red
#property indicator_color3     Green
#property indicator_style2     STYLE_DOT
#property indicator_style3     STYLE_DOT

//
//
//
//
//

extern int    HalfLength    = 12;
extern int    Price         = PRICE_CLOSE;
extern int    AtrLength     = 20;
extern double AtrMultiplier = 1.0;

//
//
//
//
//

double buffer1[];
double buffer2[];
double buffer3[];

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//

int init()
{
   HalfLength=MathMax(HalfLength,1);
         SetIndexBuffer(0,buffer1); SetIndexDrawBegin(0,HalfLength);
         SetIndexBuffer(1,buffer2); SetIndexDrawBegin(1,HalfLength);
         SetIndexBuffer(2,buffer3); SetIndexDrawBegin(2,HalfLength);
   return(0);
}
int deinit() { return(0); }




//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,j,k,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-1,MathMax(Bars-counted_bars,HalfLength));

   //
   //
   //
   //
   //
   
   for (i=limit; i>=0; i--)
   {
      double sum  = (HalfLength+1)*iMA(NULL,0,1,0,MODE_SMA,Price,i);
      double sumw = (HalfLength+1);
      for(j=1, k=HalfLength; j<=HalfLength; j++, k--)
      {
         sum  += k*iMA(NULL,0,1,0,MODE_SMA,Price,i+j);
         sumw += k;

         if (j<=i)
         {
            sum  += k*iMA(NULL,0,1,0,MODE_SMA,Price,i-j);
            sumw += k;
         }
      }

      //
      //
      //
      //
      //
      
      double range = iATR(NULL,0,AtrLength,i+10)*AtrMultiplier;
         buffer1[i] = sum/sumw;
         buffer2[i] = buffer1[i]+range;
         buffer3[i] = buffer1[i]-range;
   }
   
   //
   //
   //
   //
   //
   
   return(0);
}