//+------------------------------------------------------------------+
//|                                           autoenvelope bands.mq4 |
//|                                                                  |
//|                                                    Copyright     |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright "
#property link      "http://"
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 DodgerBlue
#property indicator_color2 White
#property indicator_color3 Tomato


double upper[], middle[], lower[], cavg[];
extern int     MA_PERIOD = 20;
extern int     MA_MODE = 0;
extern int     PRICE_MODE = 5;
extern int     factor = 27;

int init()
  {
   IndicatorBuffers(4);
   
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,upper);

   SetIndexStyle(1,DRAW_LINE,STYLE_DOT);
   SetIndexBuffer(1,middle);

   SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(2,lower);
   
   SetIndexBuffer(3,cavg);
    
   IndicatorDigits(Digits+1);
//---- indicators
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//---- 
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start() {
   int limit;
   int counted_bars=IndicatorCounted();
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
   limit=Bars-counted_bars;
   
   
   for(int x=limit; x>=0; x--) {
      
      double ma = iMA(NULL, 0, MA_PERIOD, 0, MA_MODE, PRICE_MODE, x);
      cavg[x] = 2*MathMax(MathAbs(High[x]-ma),MathAbs(Low[x]-ma))/MathMax(0.000001,ma);
      middle[x] = ma;
   }
    
   for(x=limit; x>=0; x--) {
      double csize = iStdDevOnArray(cavg,0,100,0,MODE_SMA,x)*factor/10;     
      upper[x] = middle[x]*(1+csize/2);
      lower[x] = middle[x]*(1-csize/2);
   }
   return(0);
  }


