//+------------------------------------------------------------------+
//|                                                          cfb.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1  Orange
#property indicator_width1  2
#property indicator_minimum 0

//
//
//
//
//

extern string TimeFrame          = "Current time frame";
extern int    Depth              = 3;
extern int    Price              = PRICE_WEIGHTED;
extern int    BarsToCount        = 1000;
extern int    Smooth             = 8;
extern int    SmoothResultPeriod = 5;
extern double SmoothCoeff        = 3.0;
extern bool   SmoothAdaptive     = true;
extern bool   Interpolate        = true;

//
//
//
//
//

double buffer1[];
double storec[][5];
double stored[][35];
string IndicatorFileName;
bool   CalculatingCFBBasic;
bool   CalculatingCFB;
bool   ReturningBars;
int    Depths[] = {2,3,4,6,8,12,16,24,32,48,64,96,128,192};
int    timeFrame;



//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   SetIndexBuffer(0,buffer1);

   //
   //
   //
   //
   //
   
      IndicatorFileName   = WindowExpertName();
      CalculatingCFBBasic = (TimeFrame=="CalculateCFBBasic"); if (CalculatingCFBBasic) return(0);
      CalculatingCFB      = (TimeFrame=="CalculateCFB");      if (CalculatingCFB)      return(0);
      ReturningBars       = (TimeFrame=="returnBars");        if (ReturningBars)       return(0);

      //
      //
      //
      //
      //
      
      Depth              = MathMax(MathMin(Depth,7),1)+7;
      SmoothResultPeriod = MathMax(SmoothResultPeriod,1);
      SmoothCoeff        = MathMax(SmoothCoeff,-1.5);
                           SetIndexDrawBegin(0,Depths[Depth-1]);
      timeFrame = stringToTimeFrame(TimeFrame);
         
   //
   //
   //
   //
   //
               
   IndicatorShortName("cfb "+timeFrameToString(timeFrame)+" ("+(Depth-7)+")");
   return(0);
}
int deinit() { return(0); }



//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,r,limit;
   
   if(counted_bars < 0) return(-1);
   if(counted_bars > 0) counted_bars--;
           limit = MathMin(Bars-counted_bars,Bars-1);
           if (BarsToCount>100)
                     limit = MathMin(limit,BarsToCount+192);
           if (ReturningBars)  { buffer1[0] = limit; return(0); }

   //
   //
   //
   //
   //
   
      if (timeFrame > Period()) limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,IndicatorFileName,"returnBars",0,0)*timeFrame/Period()));
      if (CalculatingCFBBasic)
      {
         if (ArrayRange(storec,0) != Bars) ArrayResize(storec,Bars);
               for(i=limit, r=Bars-i-1; i>=0; i--, r++) buffer1[i] = calculateCFBBasic(i,r,Depth);
         return(0);
      }
      if (CalculatingCFB) { calculateCFB(limit); return(0); }

   //
   //
   //
   //
   //

      for(i=limit; i>=0; i--)
      {
         int y = iBarShift(NULL,timeFrame,Time[i]);
         buffer1[i] = iCustom(NULL,timeFrame,IndicatorFileName,"CalculateCFB",Depth,Price,BarsToCount,Smooth,SmoothResultPeriod,SmoothCoeff,SmoothAdaptive,0,y);

         //
         //
         //
         //
         //
      
         if (timeFrame <= Period() || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
         if (!Interpolate) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            double factor = 1.0 / n;
            for(int k = 1; k < n; k++)
  	             buffer1[i+k] = k*factor*buffer1[i+n] + (1.0-k*factor)*buffer1[i];
      }
      
   //
   //
   //
   //
   //
      
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void calculateCFB(int limit)
{
   double avg;
   int i,k,r;

   if (ArrayRange(stored,0) != Bars) ArrayResize(stored,Bars);
   if (BarsToCount>100) SetIndexDrawBegin(0,Bars-BarsToCount);
   for(i=limit, r=Bars-i-1; i>=0; i--, r++)
   {
      double suma     = 0;
      double sumb     = 0;
      double cfb      = 0;
      double evenCoef = 1;
      double oddCoef  = 1;
         
      //
      //
      //
      //
      //

         for (k=Depth-1; k>=0; k--)
         {
            stored[r][k]    = iCustom(NULL,0,IndicatorFileName,"CalculateCFBBasic",Depths[k],Price,BarsToCount,0,i);
            stored[r][k+14] = stored[r-1][k+14] + (stored[r][k]-stored[r-Smooth][k])/Smooth;

               if ((k%2)==0)
                     { avg = oddCoef  * stored[r][k+14]; oddCoef  = oddCoef  * (1 - avg); }
               else  { avg = evenCoef * stored[r][k+14]; evenCoef = evenCoef * (1 - avg); }
               
            suma += avg*avg*Depths[k];
            sumb += avg;
         }

      //
      //
      //
      //
      //

      if (sumb != 0) cfb = suma/sumb;
      if (SmoothResultPeriod>1)
            buffer1[i] = iAverage(cfb,SmoothResultPeriod,SmoothCoeff,SmoothAdaptive,r,28);
      else  buffer1[i] = cfb;
  }
}  


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

#define _prices 0
#define _roc    1
#define _value1 2
#define _value2 3
#define _value3 4

//
//
//
//

double calculateCFBBasic(int i, int r, int depth)
{
   storec[r][_prices] = iMA(NULL,0,1,0,MODE_SMA,Price,i);

   //
   //
   //
   //
   //

      storec[r][_roc]    = MathAbs(storec[r][_prices] - storec[r-1][_prices]);
      storec[r][_value1] = storec[r-1][_value1] - storec[r-depth][_roc] + storec[r][_roc];
      storec[r][_value2] = storec[r-1][_value2] - storec[r-1][_value1] + storec[r][_roc]*depth;
      storec[r][_value3] = storec[r-1][_value3] - storec[r-1-depth][_prices] + storec[r-1][_prices];
   
   if (r<depth) return(0);
      double dividend = MathAbs(depth*storec[r][_prices]-storec[r][_value3]);

      //
      //
      //
      //
      //
         
   if (storec[r][_value2] != 0)
         return( dividend / storec[r][_value2]);
   else  return(0.00);            
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

#define F01 0
#define F02 1
#define F03 2
#define F04 3
#define F05 4
#define F06 5
#define prc 6

//
//
//
//
//

double iAverage(double price, double averagePeriod, double tconst, bool adaptive, int r, int s)
{
   double f01=stored[r-1][F01+s];  double f02=stored[r-1][F02+s];
   double f03=stored[r-1][F03+s];  double f04=stored[r-1][F04+s];
   double f05=stored[r-1][F05+s];  double f06=stored[r-1][F06+s];

   //
   //
   //
   //
   //

      if (adaptive && (averagePeriod > 1))
      {
         double minPeriod = averagePeriod/2.0;
         double maxPeriod = minPeriod*5.0;
         int    endPeriod = MathCeil(maxPeriod);
         double signal    = MathAbs((price-stored[r-endPeriod][prc+s]));
         double noise     = 0.00000000001;

            for(int i=1; i<endPeriod; i++) noise=noise+MathAbs(price-stored[r-i][prc+s]);

         averagePeriod = ((signal/noise)*(maxPeriod-minPeriod))+minPeriod;
      }
      
      //
      //
      //
      //
      //
      
      double Kg = (2.0+tconst)/(1.0+tconst+averagePeriod);
      double Hg = 1.0-Kg;

      f01 = Kg * price + Hg * f01; f02 = Kg * f01 + Hg * f02; double v01 = 1.5 * f01 - 0.5 * f02;
      f03 = Kg * v01   + Hg * f03; f04 = Kg * f03 + Hg * f04; double v02 = 1.5 * f03 - 0.5 * f04;
      f05 = Kg * v02   + Hg * f05; f06 = Kg * f05 + Hg * f06; double v03 = 1.5 * f05 - 0.5 * f06;

   //
   //
   //
   //
   //

   stored[r][F01+s] = f01;  stored[r][F02+s] = f02;
   stored[r][F03+s] = f03;  stored[r][F04+s] = f04;
   stored[r][F05+s] = f05;  stored[r][F06+s] = f06;
   stored[r][prc+s] = price;
   return(v03);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

//
//
//
//
//

int stringToTimeFrame(string tfs)
{
   tfs = StringUpperCase(tfs);
   for (int i=ArraySize(iTfTable)-1; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[i],Period()));
                                                      return(Period());
}
string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//
//
//
//
//

string StringUpperCase(string str)
{
   string   s = str;

   for (int length=StringLen(str)-1; length>=0; length--)
   {
      int tchar = StringGetChar(s, length);
         if((tchar > 96 && tchar < 123) || (tchar > 223 && tchar < 256))
                     s = StringSetChar(s, length, tchar - 32);
         else if(tchar > -33 && tchar < 0)
                     s = StringSetChar(s, length, tchar + 224);
   }
   return(s);
}