#property copyright "Copyright © 2008, Mistigri LLC"
#property link      "http://www.mistigrifx.com"

#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_buffers 1
#property indicator_color1 DodgerBlue

//---- input parameters
extern int Periods=14;

//---- buffers
double RSIBuffer[];
double PosBuffer[];
double NegBuffer[];
double RocUpBuffer[];
double RocDnBuffer[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{
   string short_name;
   IndicatorBuffers(5);
   SetIndexBuffer(1,PosBuffer);
   SetIndexBuffer(2,NegBuffer);
   SetIndexBuffer(3,RocUpBuffer);
   SetIndexBuffer(4,RocDnBuffer);
   //---- indicator line
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,RSIBuffer);
   SetIndexDrawBegin(0,Periods);
   //---- name for DataWindow and indicator subwindow label
   short_name="RSI("+Periods+")";
   IndicatorShortName(short_name);
   SetIndexLabel(0,short_name);
   //---- Set indicator Levels
   SetLevelValue( 0, 30.0); 
   SetLevelValue( 1, 70.0); 
   SetLevelStyle( 2, 1, Gray );
   //----
   return(0);
}
//+------------------------------------------------------------------+
//| Relative Strength Index                                          |
//+------------------------------------------------------------------+
int start()
{
   int counted_bars=IndicatorCounted();  
   //----
   if(Bars<=Periods) { return(0); }
   //---- initial zero
   if( counted_bars < 1 )
   for(int i=1;i<=Periods;i++) { RSIBuffer[Bars-i] = 0.0; }
   //---- Set ROC Arrays
   i=Bars-1;
   while(i>=0)
   {
      double rel=Close[i]-Close[i+1];
      if( rel >= 0 ) { RocUpBuffer[i] = rel; RocDnBuffer[i] =  0.0; }
      else           { RocUpBuffer[i] = 0.0; RocDnBuffer[i] = -rel; }
      i--;
   }
   //---- Calculate RSI
   i=Bars-Periods-1;
   if(counted_bars>=Periods) { i=Bars-counted_bars-1; }
   while(i>=0)
   {
      if(i==Bars-Periods-1)
      {
         PosBuffer[i]= iMAOnArray( RocUpBuffer, 0, Periods, 0, MODE_SMA, i );
         NegBuffer[i]= iMAOnArray( RocDnBuffer, 0, Periods, 0, MODE_SMA, i );
      }     
      else
      {
         PosBuffer[i] = (PosBuffer[i+1]*(Periods-1)+RocUpBuffer[i])/Periods;
         NegBuffer[i] = (NegBuffer[i+1]*(Periods-1)+RocDnBuffer[i])/Periods;
      }
      if(NegBuffer[i] == 0.0) { RSIBuffer[i] = 0.0; }
      else                    { RSIBuffer[i]=100.0-(100.0/(1+PosBuffer[i]/NegBuffer[i])); }
      i--;
   }
   return(0);
  }
//+------------------------------------------------------------------+