//+------------------------------------------------------------------+
//|                                             Congestion index.mq4 |
//| forex-tsd elite section only                                     |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers  2
#property indicator_color1   Green
#property indicator_color2   DarkOrange
#property indicator_width1   2
#property indicator_minimum -100
#property indicator_maximum  100
#property indicator_level1  -85
#property indicator_level2  -20
#property indicator_level3    0
#property indicator_level4   20
#property indicator_level5   85
#property indicator_levelcolor DarkSlateGray

//
//
//
//
//

extern int LookBack     = 28;
extern int Price        = PRICE_CLOSE;
extern int SmoothPeriod = 10;
extern int SignalPeriod = 10;

//
//
//
//
//

double buffer[];
double signal[];
double prices[];

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

int init()
{
   IndicatorBuffers(3);
   SetIndexBuffer(0,buffer);
   SetIndexBuffer(1,signal);
   SetIndexBuffer(2,prices);
   return(0);
}
int deinit()
{
   return(0);
}

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

int start()
{
   double alpha        = 2.0/(1.0 + SmoothPeriod);
   double alphas       = 2.0/(1.0 + SignalPeriod);
   int    counted_bars = IndicatorCounted();
   int    i,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-counted_bars,Bars-1);

   //
   //
   //
   //
   //

   for(i=limit; i>=0; i--)
   {
      prices[i] = iMA(NULL,0,1,0,MODE_SMA,Price,i);

      double dividend = 0;
      double divisor  = 0;
      double lowest   = Low[ArrayMinimum(Low,LookBack,i)];

      if (prices[i+LookBack-1] != 0) dividend = 100.00 * (prices[i]-prices[i+LookBack-1])/prices[i+LookBack-1];
      if (lowest != 0)               divisor  = (High[ArrayMaximum(High,LookBack,i)]-lowest)/lowest;
      
      //
      //
      //
      //
      //
  
      if (divisor != 0)
            double ci = dividend/divisor;
      else         ci = 0;       
      if (SmoothPeriod>1)
            buffer[i] = buffer[i+1]+alpha*(ci-buffer[i+1]);
      else  buffer[i] = ci;       
      if (SignalPeriod>1)
            signal[i] = signal[i+1]+alphas*(buffer[i]-signal[i+1]);
   }
   return(0);
}