//+------------------------------------------------------------------+
//|                                                           mladen |
//|                                               mladenfx@gmail.com |
//+------------------------------------------------------------------+
#property copyright "copyright mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers    4
#property indicator_color1     LimeGreen
#property indicator_color2     Orange
#property indicator_color3     Orange
#property indicator_color4     Gold
#property indicator_width1     2
#property indicator_width2     2
#property indicator_width3     2
#property indicator_style4     STYLE_DOT
#property indicator_level1     0

//
//
//
//
//

extern string TimeFrame       = "Current time frame";
extern int    LowLimit        = 10;
extern int    HighLimit       = 30;
extern double SmoothLength    = 5;
extern double SmoothPhase     = 0;
extern int    Price           = 0;
extern int    CfbNormLength   = 50;
extern int    CfbDepth        = 6;
extern int    CfbPrice        = PRICE_WEIGHTED;
extern int    CfbSmooth       = 8;
extern int    CfbResultSmooth = 5;
extern double CfbResultPhase  = 0;
extern bool   SmoothDouble    = false;
extern int    SignalLength    = 9;
extern int    SignalMethod    = MODE_EMA;
extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = true;
extern bool   alertsOnSlope   = true;
extern bool   alertsOnCrosses = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;
extern bool   Interpolate     = true; 
extern int    Shift           = 0;

//
//
//
//
//

double vel[];
double velda[];
double veldb[];
double cfb[];
double prices[];
double signal[];
double slope[];
double cross[];

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,vel);  
   SetIndexBuffer(1,velda); 
   SetIndexBuffer(2,veldb); 
   SetIndexBuffer(3,signal); 
   SetIndexBuffer(4,cfb);
   SetIndexBuffer(5,prices);
   SetIndexBuffer(6,slope);
   SetIndexBuffer(7,cross);
   
   //
   //
   //
   //
   //
       
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame == "returnBars";     if (returnBars)     return(0);
      calculateValue    = TimeFrame == "calculateValue"; if (calculateValue) return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);
          
   //
   //
   //
   //
   //
   
   for (int i=0; i<4; i++) SetIndexShift(i,Shift*timeFrame/Period());   
   IndicatorShortName(timeFrameToString(timeFrame)+" velocity cfb adaptive ("+LowLimit+","+HighLimit+","+DoubleToStr(SmoothLength,2)+")");
   return(0);
}



//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int i,r,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { vel[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
      if (slope[limit]==-1) CleanPoint(limit,velda,veldb);
      for(i=limit; i>=0; i--)
      {
         cfb[i] = iDSmooth(iCfb(Bars,iMA(NULL,0,1,0,MODE_SMA,CfbPrice,i),CfbDepth,CfbSmooth,r),CfbResultSmooth,CfbResultPhase,i);
    
         //
         //
         //
         //
         //
         
         double cfbMax = cfb[i];
         double cfbMin = cfb[i];
         for (int k=1; k<CfbNormLength && (i+k)<Bars; k++ )
            {
               cfbMax = MathMax(cfb[i+k],cfbMax);
               cfbMin = MathMin(cfb[i+k],cfbMin);
            }
            double denominator = cfbMax-cfbMin;
               if (denominator> 0)
                  double ratio = (cfb[i]-cfbMin)/denominator;
               else      ratio = 0.5;                 

         //
         //
         //
         //
         //

         double length = MathCeil(LowLimit+ratio*(HighLimit-LowLimit));
         prices[i] = iMA(NULL,0,1,0,MODE_SMA,Price,i);
         vel[i]    = iDSmooth(iVEL(length,i),SmoothLength,SmoothPhase,i,20);
         velda[i]  = EMPTY_VALUE;
         veldb[i]  = EMPTY_VALUE;
         slope[i]  = slope[i+1];
            if (vel[i]>vel[i+1]) slope[i] =  1;
            if (vel[i]<vel[i+1]) slope[i] = -1;
            if (slope[i] == -1) PlotPoint(i,velda,veldb,vel);
      }            
      for(i=limit; i>=0; i--)
      {
         signal[i] = iMAOnArray(vel,0,SignalLength,0,SignalMethod,i);
         cross[i]  = cross[i+1];
            if (vel[i]>signal[i]) cross[i] =  1;
            if (vel[i]<signal[i]) cross[i] = -1;
      }
      manageAlerts();
      return(0);
   }
   
   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for (i=limit; i>=0; i--)
   {
       int y = iBarShift(NULL,timeFrame,Time[i]);               
          vel[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",LowLimit,HighLimit,SmoothLength,SmoothPhase,Price,CfbNormLength,CfbDepth,CfbPrice,CfbSmooth,CfbResultSmooth,CfbResultPhase,SmoothDouble,SignalLength,SignalMethod,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnCrosses,alertsMessage,alertsSound,alertsEmail,0,y);
          signal[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",LowLimit,HighLimit,SmoothLength,SmoothPhase,Price,CfbNormLength,CfbDepth,CfbPrice,CfbSmooth,CfbResultSmooth,CfbResultPhase,SmoothDouble,SignalLength,SignalMethod,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnCrosses,alertsMessage,alertsSound,alertsEmail,3,y);
          velda[i]  = EMPTY_VALUE;
          veldb[i]  = EMPTY_VALUE;
          slope[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",LowLimit,HighLimit,SmoothLength,SmoothPhase,Price,CfbNormLength,CfbDepth,CfbPrice,CfbSmooth,CfbResultSmooth,CfbResultPhase,SmoothDouble,SignalLength,SignalMethod,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnCrosses,alertsMessage,alertsSound,alertsEmail,6,y);
          
          //
          //
          //
          //
          //
       
          if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

          //
          //
          //
          //
          //

          datetime time = iTime(NULL,timeFrame,y);
             for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
             for(int x = 1; x < n; x++)
             {
                vel[i+x]    = vel[i]    + (vel[i+n]    - vel[i])    * x/n;
                signal[i+x] = signal[i] + (signal[i+n] - signal[i]) * x/n;
             }               
   }
   for (i=limit; i>=0; i--) if (slope[i] == -1) PlotPoint(i,velda,veldb,vel);
   return(0);
}

  
//+------------------------------------------------------------------
//|                                                                 
//+------------------------------------------------------------------
//
//
//
//
//

double iVEL(double length,int i)
{
   static int vel_length = -1;
          if (vel_length != length)
          {
              vel_length = length;
                  static double coeff0; coeff0 = length + 1;
                  static double coeff1; coeff1 = coeff0 * (    coeff0+1.0)/2.0;
                  static double coeff2; coeff2 = coeff1 * (2.0*coeff0+1.0)/3.0;
                  static double coeff3; coeff3 = coeff1 * coeff1 * coeff1 - coeff2 * coeff2; 
          }
   
   //
   //
   //
   //
   //

   double suma = 0.0;
   double sumb = 0.0;
      for(int l=0; l<=length; l++)
      {
         suma += prices[i+l] * (coeff0-l);
         sumb += prices[i+l] * (coeff0-l) * (coeff0-l);
      }
   double tvel = (sumb*coeff1 - suma*coeff2) / (coeff3*Point); 
   return(tvel);
}


//+------------------------------------------------------------------
//|                                                                 
//+------------------------------------------------------------------
//
//
//
//
//

int    Depths[] = {2,3,4,6,8,12,16,24,32,48,64,96,128,192};
double workCfb[][28];

//
//
//
//
//

double iCfb(int totalBars, double price, int depth, int smooth, int i)
{
   if (ArrayRange(workCfb,0) != totalBars) ArrayResize(workCfb,totalBars);
         
   //
   //
   //
   //
   //

   double suma     = 0;
   double sumb     = 0;
   double tcfb      = 0;
   double evenCoef = 1;
   double oddCoef  = 1;
   double avg      = 0;
         
      if (i>=smooth)
         for (int k=depth-1; k>=0; k--)
         {
            workCfb[i][k]    = iCfbFunc(totalBars,price,i,Depths[k],k);
            workCfb[i][k+14] = workCfb[i-1][k+14] + (workCfb[i][k]-workCfb[i-smooth][k])/smooth;

                  if ((k%2)==0)
                        { avg = oddCoef  * workCfb[i][k+14]; oddCoef  = oddCoef  * (1 - avg); }
                  else  { avg = evenCoef * workCfb[i][k+14]; evenCoef = evenCoef * (1 - avg); }
               
               suma += avg*avg*Depths[k];
               sumb += avg;
         }
      else for (k=depth-1; k>=0; k--) { workCfb[i][k] = 0; workCfb[i][k+14] = 0; }            

   //
   //
   //
   //
   //

   if (sumb != 0) tcfb = suma/sumb;
   return(tcfb);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

double  workCfbFunc[][70];
#define _prices 0
#define _roc    1
#define _value1 2
#define _value2 3
#define _value3 4

//
//
//
//

double iCfbFunc(int totalBars, double price, int r, int depth, int k)
{
   k *= 5;
      if (ArrayRange(workCfbFunc,0) != totalBars) ArrayResize(workCfbFunc,totalBars);
      if (r<=(depth+1))
      {
         workCfbFunc[r][k+_prices] = 0;
         workCfbFunc[r][k+_roc]    = 0;
         workCfbFunc[r][k+_value1] = 0;
         workCfbFunc[r][k+_value2] = 0;
         workCfbFunc[r][k+_value3] = 0;
         return(0);
      }         
      workCfbFunc[r][k+_prices] = price; 

   //
   //
   //
   //
   //

      workCfbFunc[r][k+_roc]    = MathAbs(workCfbFunc[r][k+_prices] - workCfbFunc[r-1][k+_prices]);
      workCfbFunc[r][k+_value1] = workCfbFunc[r-1][k+_value1] - workCfbFunc[r-depth][k+_roc] + workCfbFunc[r][k+_roc];
      workCfbFunc[r][k+_value2] = workCfbFunc[r-1][k+_value2] - workCfbFunc[r-1][k+_value1] + workCfbFunc[r][k+_roc]*depth;
      workCfbFunc[r][k+_value3] = workCfbFunc[r-1][k+_value3] - workCfbFunc[r-1-depth][k+_prices] + workCfbFunc[r-1][k+_prices];
   
      double dividend = MathAbs(depth*workCfbFunc[r][k+_prices]-workCfbFunc[r][k+_value3]);

      //
      //
      //
      //
      //
         
   if (workCfbFunc[r][k+_value2] != 0)
         return( dividend / workCfbFunc[r][k+_value2]);
   else  return(0.00);            
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

double wrk[][40];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iDSmooth(double price, double length, double phase, int i, int s=0)
{
   if (SmoothDouble)
         return (iSmooth(iSmooth(price,MathSqrt(length),phase,i,s),MathSqrt(length),phase,i,s+10));
   else  return (iSmooth(price,length,phase,i,s));
}

//
//
//
//
//

double iSmooth(double price, double length, double phase, int i, int s=0)
{
   if (length <=1) return(price);
   if (ArrayRange(wrk,0) != Bars) ArrayResize(wrk,Bars);
   
   int r = Bars-i-1; 
      if (r==0) { for(int k=0; k<7; k++) wrk[r][k+s]=price; for(; k<10; k++) wrk[r][k+s]=0; return(price); }

   //
   //
   //
   //
   //
   
      double len1   = MathMax(MathLog(MathSqrt(0.5*(length-1)))/MathLog(2.0)+2.0,0);
      double pow1   = MathMax(len1-2.0,0.5);
      double del1   = price - wrk[r-1][bsmax+s];
      double del2   = price - wrk[r-1][bsmin+s];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = MathMin(r,10);
	
         wrk[r][volty+s] = 0;
               if(MathAbs(del1) > MathAbs(del2)) wrk[r][volty+s] = MathAbs(del1); 
               if(MathAbs(del1) < MathAbs(del2)) wrk[r][volty+s] = MathAbs(del2); 
         wrk[r][vsum+s] =	wrk[r-1][vsum+s] + (wrk[r][volty+s]-wrk[r-forBar][volty+s])*div;
         
         //
         //
         //
         //
         //
   
         wrk[r][avolty+s] = wrk[r-1][avolty+s]+(2.0/(MathMax(4.0*length,30)+1.0))*(wrk[r][vsum+s]-wrk[r-1][avolty+s]);
            if (wrk[r][avolty+s] > 0)
               double dVolty = wrk[r][volty+s]/wrk[r][avolty+s]; else dVolty = 0;   
	               if (dVolty > MathPow(len1,1.0/pow1)) dVolty = MathPow(len1,1.0/pow1);
                  if (dVolty < 1)                      dVolty = 1.0;

      //
      //
      //
      //
      //
	        
   	double pow2 = MathPow(dVolty, pow1);
      double len2 = MathSqrt(0.5*(length-1))*len1;
      double Kv   = MathPow(len2/(len2+1), MathSqrt(pow2));

         if (del1 > 0) wrk[r][bsmax+s] = price; else wrk[r][bsmax+s] = price - Kv*del1;
         if (del2 < 0) wrk[r][bsmin+s] = price; else wrk[r][bsmin+s] = price - Kv*del2;
	
   //
   //
   //
   //
   //
      
      double R     = MathMax(MathMin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = MathPow(beta,pow2);

         wrk[r][0+s] = price + alpha*(wrk[r-1][0+s]-price);
         wrk[r][1+s] = (price - wrk[r][0+s])*(1-beta) + beta*wrk[r-1][1+s];
         wrk[r][2+s] = (wrk[r][0+s] + R*wrk[r][1+s]);
         wrk[r][3+s] = (wrk[r][2+s] - wrk[r-1][4+s])*MathPow((1-alpha),2) + MathPow(alpha,2)*wrk[r-1][3+s];
         wrk[r][4+s] = (wrk[r-1][4+s] + wrk[r][3+s]); 

   //
   //
   //
   //
   //

   return(wrk[r][4+s]);
}  

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

//
//
//
//
//

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (first[i+1] == EMPTY_VALUE)
      {
         if (first[i+2] == EMPTY_VALUE) {
                first[i]   = from[i];
                first[i+1] = from[i+1];
                second[i]  = EMPTY_VALUE;
            }
         else {
                second[i]   =  from[i];
                second[i+1] =  from[i+1];
                first[i]    = EMPTY_VALUE;
            }
      }
   else
      {
         first[i]  = from[i];
         second[i] = EMPTY_VALUE;
      }
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      
      //
      //
      //
      //
      //
      
      static string   what1 = "";
      static datetime when1 = 0;
      if (alertsOnSlope && slope[whichBar] != slope[whichBar+1])
      {
         if (slope[whichBar] ==  1) doAlert(what1,when1," slope of cfb velocity changed to up");
         if (slope[whichBar] == -1) doAlert(what1,when1," slope of cfb velocity changed to down");
      }
      static string   what2 = "";
      static datetime when2 = 0;
      if (alertsOnCrosses && cross[whichBar] != cross[whichBar+1])
      {
         if (cross[whichBar] ==  1) doAlert(what2,when2," cfb velocity crossed signal line up");
         if (cross[whichBar] == -1) doAlert(what2,when2," cfb velocity crossed signal line down");
      }
   }
}

//
//
//
//
//

void doAlert(string& previousAlert, datetime& previousTime, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[0]) {
       previousAlert  = doWhat;
       previousTime   = Time[0];

       //
       //
       //
       //
       //

       message = timeFrameToString(Period())+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," velocity cfb "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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);
}