//+------------------------------------------------------------------+
//|                                                      CCIVMA1.mq4 |                                     
//+------------------------------------------------------------------+
//Revision history; 
//Initially using FX Snipers T3 CCI which uses MT4s CCI function.


#property indicator_chart_window
#property indicator_buffers   1
#property indicator_color1    Yellow
#property indicator_width1    2 

//---- input parameters
extern int CCI_Period = 3;
extern int T3_Period = 8;
extern double b = 0.618;
//---- buffers
double MA[];
double cci[];//Not displayed

//double ADX[];//Not displayed
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
   IndicatorBuffers(2);
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,MA);
   SetIndexBuffer(1,cci);
 
//   SetIndexBuffer(5,ADX);

   
//---- name for DataWindow and indicator subwindow label
   string short_name="CCIVMA1";
   IndicatorShortName(short_name);
   SetIndexLabel(0,"CCIVMA1");

   //----
   SetIndexDrawBegin(0,2*CCI_Period);        
//--------- Safety overrides on user settings

   if(T3_Period<1)T3_Period=1;
   if(CCI_Period<2)CCI_Period=2;
   if(b<0.1)b=0.1;
//----
   return(0);
}

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   double n, b2, b3, c1, c2, c3, c4, e1, e2, e3, e4, e5, e6, w1, w2;

   int   limit, i, j, counted_bars=IndicatorCounted();

//----      
   if (counted_bars<0) return(-1);  //MT4 crash patch.
   if (counted_bars==0 ) 
   {
   limit=Bars-1;
   for(i=1;i<2*CCI_Period;i++) 
   {
   MA[Bars-i]=Close[Bars-i];
   cci[Bars-i]=0;
   }
   }
     
   limit=Bars-counted_bars-2*CCI_Period;
   if(counted_bars==0) limit--;

   for(i=limit; i>=0; i--) 
   {
   b2 = b*b;
   b3 = b2*b;
   c1 = -b3;
   c2 = (3*(b2 + b3));
   c3 = -3*(2*b2 + b + b3);
   c4 = (1 + 3*b + b3 + 3*b2);
   n = T3_Period;
   n = 1 + 0.5*(n - 1);
   w1 = 2 / (n + 1);
   w2 = 1 - w1; 
   j=CCI_Period; 
   cci[i] = iCCI(NULL, 0, CCI_Period, PRICE_MEDIAN, i);
   e1 = w1*cci[i] + w2*e1;
   e2 = w1*e1 + w2*e2;
   e3 = w1*e2 + w2*e3;
   e4 = w1*e3 + w2*e4;
   e5 = w1*e4 + w2*e5;
   e6 = w1*e5 + w2*e6;    
   cci[i] = c1*e6 + c2*e5 + c3*e4 + c4*e3;  

   if (cci[i]<0)cci[i]=-cci[i];//Invert the negative signal.
   if (cci[i]>cci[i+1]) MA[i]=Close[i];//Ladder
   else MA[i]=MA[i+1];//HE

   }
   return(0);
  }
//+------------------------------------------------------------------+

