//+------------------------------------------------------------------+
//|                             normalized deviations oscillator.mq4 |
//|                                            25 August 2012 mladen |
//|                                                                  |
//|              original developed by William Cringan (TASC 2/2003) |
//+------------------------------------------------------------------+

#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_label1  "Normalized ATR"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_width1  2
#property strict

//
//
//
//
//

input int    AtrPeriod        = 12;

double natr[],atr[];

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

int OnInit()
{
   IndicatorBuffers(2);
   SetIndexBuffer(0,natr,INDICATOR_DATA);
   SetIndexBuffer(1,atr);
   
   IndicatorSetString(INDICATOR_SHORTNAME," Normalized atr ");
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason) {  }

//+------------------------------------------------------------------
//|                                                                                                                             |
//+------------------------------------------------------------------
//
//
//
//
//

int OnCalculate (const int       rates_total,
                 const int       prev_calculated,
                 const datetime& time[],
                 const double&   open[],
                 const double&   high[],
                 const double&   low[],
                 const double&   close[],
                 const long&     tick_volume[],
                 const long&     volume[],
                 const int&      spread[])
{
   int i=rates_total-prev_calculated+1; if (i>=rates_total) i=rates_total-1; 
   
   //
   //
   //
   
   for (; i>=0 && !_StopFlag; i--)
   {
       atr[i] = 0; 
       for (int k=0; k<AtrPeriod && (i+k+1)<rates_total-1; k++) 
          atr[i] += fmax(high[i+k],close[i+k+1])-fmin(low[i+k],close[i+k+1]); 
          atr[i] /= AtrPeriod;
               
          double max  = atr[ArrayMaximum(atr,AtrPeriod,i)];            
          double min  = atr[ArrayMinimum(atr,AtrPeriod,i)];  
          natr[i] = (min != max) ? (atr[i]-min)/(max-min) : 0.5;          
                         
   }
return(rates_total);
}
          
   