//+------------------------------------------------------------------+
//|                                                     forecast.mq4 |
//|                               Copyright © 2014, Gehtsoft USA LLC |
//|                                            http://fxcodebase.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2014, Gehtsoft USA LLC"
#property link      "http://fxcodebase.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Yellow

extern int Length=20;
extern int Price=0;    // Applied price
                       // 0 - Close
                       // 1 - Open
                       // 2 - High
                       // 3 - Low
                       // 4 - Median
                       // 5 - Typical
                       // 6 - Weighted  

double FO[];

int init()
{
 IndicatorShortName("Forecast Oscillator");
 IndicatorDigits(Digits);
 SetIndexStyle(0,DRAW_LINE);
 SetIndexBuffer(0,FO);

 return(0);
}

int deinit()
{

 return(0);
}

int start()
{
 if(Bars<=3) return(0);
 int ExtCountedBars=IndicatorCounted();
 if (ExtCountedBars<0) return(-1);
 int limit=Bars-2;
 if(ExtCountedBars>2) limit=Bars-ExtCountedBars-1;
 int pos;
 double sx, sy, sxy, sx2, a, b, tsf;
 double Pr;
 int i, t;
 pos=limit;
 while(pos>=0)
 {
  t=Length;
  sx=0.;
  sy=0.;
  sxy=0.;
  sx2=0.;
  for (i=pos+Length;i>=pos+1;i--)
  {
   Pr=iMA(NULL, 0, 1, 0, MODE_SMA, Price, i);
   sy=sy+Pr;
   sx=sx+t;
   sx2=sx2+t*t;
   sxy=sxy+Pr*t;
   t--;
  }
  b=(Length*sxy-sx*sy)/(Length*sx2-sx*sx);
  a=(sy-b*sx)/Length;
  tsf=a+b;
  
  Pr=iMA(NULL, 0, 1, 0, MODE_SMA, Price, pos);
  if (Pr!=0.)
  {
   FO[pos]=100.*(Pr-tsf)/Pr;
  } 

  pos--;
 } 
 return(0);
}

