//------------------------------------------------------------------
#property copyright "www,forex-tsd.com"
#property link      "www,forex-tsd.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1  LimeGreen
#property indicator_color2  PaleVioletRed
#property indicator_width1  2
#property indicator_width2  2
#property indicator_minimum 0
#property indicator_maximum 1
//
//
//
//
//

extern int CCIPeriod  = 50;
extern int CCIPrice   = PRICE_TYPICAL;

double cci[];
double cciU[];
double cciD[];
double prices[];
double trend[];

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(5);
      SetIndexBuffer(0,cciU); SetIndexStyle(0,DRAW_HISTOGRAM);
      SetIndexBuffer(1,cciD); SetIndexStyle(1,DRAW_HISTOGRAM);
      SetIndexBuffer(2,cci);
      SetIndexBuffer(3,prices);
      SetIndexBuffer(4,trend);
   IndicatorShortName("CCI ("+CCIPeriod+")");
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//

int start()
{
   int k,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);

   //
   //
   //
   //
   //

   for(int i=limit; i>=0; i--)
   {
      prices[i] = iMA(NULL,0,1,0,MODE_SMA,CCIPrice,i);
      double avg = 0; for(k=0; k<CCIPeriod; k++) avg +=         prices[i+k];      avg /= (CCIPeriod);
      double dev = 0; for(k=0; k<CCIPeriod; k++) dev += MathAbs(prices[i+k]-avg); dev /= (CCIPeriod);
         if (dev!=0)
               cci[i]   = (prices[i]-avg)/(0.015*dev);
         else  cci[i]   = 0;          
               cciD[i]  = EMPTY_VALUE;
               cciU[i]  = EMPTY_VALUE;
               trend[i] = trend[i+1];
                  if (cci[i]>0) trend[i] =  1;
                  if (cci[i]<0) trend[i] = -1;
                  if (trend[i] ==  1) cciU[i] = 1;
                  if (trend[i] == -1) cciD[i] = 1;
   }
   return(0);
}