//+------------------------------------------------------------------+
//|                                                 FN Diver Osc.mq4 |
//|                                                          Belomor |
//|                                                 belomor@inbox.ru |
//+------------------------------------------------------------------+
#property copyright "Belomor"
#property link      "belomor@inbox.ru"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- input parameters
extern int        FN=26;
if(FN<2)
FN=2;

extern int        Smoothing=5;
if(Smoothing<1)
Smoothing=1;

extern int        Shift=1;
if(Shift<0)
Shift=1;

extern double     Deviation=3;
if(Deviation<0)
Deviation=1;

//---- buffers
double ExtMapBuffer1[];
double ExtMapBuffer2[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   IndicatorBuffers(2);
   SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,2);
   SetIndexBuffer(0,ExtMapBuffer1);  
   SetIndexBuffer(1,ExtMapBuffer2);
   SetIndexDrawBegin(0,FN+Shift);
   IndicatorShortName("FN Diver Osc ("+FN+","+Smoothing+","+Shift+")");
   SetIndexLabel(0,"FN Diver");
   IndicatorDigits(4);
//----
   return(0);
  }
  
double FisherX(int F_period, double Dev, int i)
   {
   double result;
   double A;
   double S;
   double C;
   double X;
   double D;
   if(i<Bars-F_period)
   {
   D=Dev;
   C=Close[i];
   A=iMA(NULL,0,F_period,0,MODE_SMA,PRICE_CLOSE,i);
   S=iStdDev(NULL,0,F_period,MODE_SMA,0,PRICE_CLOSE,i);
   X=(C-A)/(D*S);
   }
   else
   result=0;
   if(X>0.99)
   X=0.99;
   if(X<-0.99)
   X=-0.99;
   result=X;
   return(result);
   }
   
double FisherY(int F_period, double Dev, int i)
   {
   double result;
   double X;
   if(i<Bars-F_period)
   {
   X=FisherX(F_period,Dev,i);
   result=0.5*MathLog((1+X)/(1-X));
   }
   else
   result=0;
   return(result);
   }
   
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   int limit;
   int counted_bars=IndicatorCounted();
//---- check for possible errors
   if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
   if(counted_bars>0) counted_bars--;
   limit=Bars-counted_bars;
   for(int i=0; i<limit; i++)
      ExtMapBuffer2[i]=FisherY(FN,Deviation,i);
   for(i=0; i<limit; i++)
      ExtMapBuffer1[i]=iMAOnArray(ExtMapBuffer2,Bars,Smoothing,0,MODE_EMA,i)-iMAOnArray(ExtMapBuffer2,Bars,Smoothing,0,MODE_EMA,i+Shift);
//---- done
   return(0);
  }
//+------------------------------------------------------------------+