//+------------------------------------------------------------------+
//|                                                  cmf 4 color mtf |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers    5
#property indicator_color1     Red
#property indicator_color2     Maroon
#property indicator_color3     LimeGreen
#property indicator_color4     DarkGreen
#property indicator_color5     DimGray
#property indicator_width1     2
#property indicator_width2     2
#property indicator_width3     2
#property indicator_width4     2
#property indicator_width5     2
#property indicator_level3     0
#property indicator_levelcolor MediumOrchid

//
//
//
//
//

extern string TimeFrame                 = "Current time frame";
extern int    CmfPeriod                 = 20;
extern int    SmoothLength              = 5;
extern double SmoothPhase               = 0;
extern bool   SmoothDouble              = false;
extern bool   divergenceVisible         = true;
extern bool   divergenceOnValuesVisible = true;
extern bool   divergenceOnChartVisible  = true;
extern color  divergenceBullishColor    = Green;
extern color  divergenceBearishColor    = OrangeRed;
extern string divergenceUniqueID        = "cmf jurik";
extern double levelOs                   = -0.20;
extern double levelOb                   = 0.20; 
extern bool   HistogramOnSlope          = true;
extern bool   Interpolate               = true;

extern bool   alertsOn                  = true;
extern bool   alertsOnSlopeChange       = true;
extern bool   alertsOnZeroCross         = true;
extern bool   alertsOnOsObCross         = true;
extern bool   alertsOnCurrent           = false;
extern bool   alertsMessage             = true;
extern bool   alertsSound               = true;
extern bool   alertsEmail               = false;

//
//
//
//
//

double cmf[];
double cmfUpa[];
double cmfUpb[];
double cmfDna[];
double cmfDnb[];
double trend[];
double slope[];
double cmfw[];
double trends[][3];

//
//
//
//
//

#define _tdn1 0
#define _tup1 1
#define _tmi  2

//
//
//
//
//

int    timeFrame;
string indicatorFileName;
bool   returnBars;
bool   calculateValue;
string shortName;

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
// 
//
//
//
//
int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,cmfDna); SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1,cmfDnb); SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexBuffer(2,cmfUpa); SetIndexStyle(2,DRAW_HISTOGRAM);
   SetIndexBuffer(3,cmfUpb); SetIndexStyle(3,DRAW_HISTOGRAM);
   SetIndexBuffer(4,cmf);
   SetIndexBuffer(5,trend);
   SetIndexBuffer(6,slope);
   SetIndexBuffer(7,cmfw);
   
   SetLevelValue(0,levelOs);
   SetLevelValue(1,levelOb);
   SetLevelValue(2,0);
   
      //
      //
      //
      //
      //
      
      indicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      calculateValue    = (TimeFrame=="calculateValue");
      if (calculateValue)
      {
         int s = StringFind(divergenceUniqueID,":",0);
               shortName = divergenceUniqueID;
               divergenceUniqueID = StringSubstr(divergenceUniqueID,0,s);
               return(0);
      }            
      timeFrame = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //
      
   shortName = divergenceUniqueID+": "+timeFrameToString(timeFrame)+ "   cmf on jurik ("+CmfPeriod+")";
   IndicatorShortName(shortName);
   return(0);
}

//
//
//
//
//

int deinit() {

   int lookForLength = StringLen(divergenceUniqueID);
   for (int i=ObjectsTotal()-1; i>=0; i--) {
      string objectName = ObjectName(i);
      if (StringSubstr(objectName,0,lookForLength) == divergenceUniqueID) ObjectDelete(objectName);
   }
   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) { cmfDna[0] = limit+1; return(0); }

   
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
     if (ArrayRange(trends,0)!=Bars) {  ArrayResize(trends,Bars); }
     for(i = limit, r=Bars-i-1; i>=0; i--,r++)
     {
        if((High[i]-Low[i]) != 0)
                 cmfw[i] = Volume[i]*((Close[i]-Low[i])-(High[i]-Close[i]))/(High[i]-Low[i]);
            else cmfw[i] =  0;
               
            //
            //
            //
            //
            //
               
            double suma = cmfw[i];
            double sumv = Volume[i];
            for (int k=1; k<CmfPeriod; k++)
            {
               suma += cmfw[i+k];
               sumv += Volume[i+k];
            }
            if (sumv!=0)
                  cmf[i] = iDSmooth(suma/sumv,SmoothLength,SmoothPhase,SmoothDouble,i);
            else  cmf[i] = iDSmooth(0        ,SmoothLength,SmoothPhase,SmoothDouble,i); 
            
            //
            //
            //
            //
            //
                 
            cmfDna[i] = EMPTY_VALUE;
            cmfDnb[i] = EMPTY_VALUE;
            cmfUpa[i] = EMPTY_VALUE;
            cmfUpb[i] = EMPTY_VALUE; 
            trend[i]  = trend[i+1];
            slope[i]  = slope[i+1];
            if (cmf[i] > 0)        trend[i] =  1;
            if (cmf[i] < 0)        trend[i] = -1;
            if (cmf[i] > cmf[i+1]) slope[i] =  1;
            if (cmf[i] < cmf[i+1]) slope[i] = -1;
         
            setTrends(i,r);
               
            if (divergenceVisible)
            {
              CatchBullishDivergence(cmf,i);
              CatchBearishDivergence(cmf,i);
            }
                                     
            if (HistogramOnSlope)
            {
                if (trend[i]== 1 && slope[i] == 1) cmfUpa[i] = cmf[i];
                if (trend[i]== 1 && slope[i] ==-1) cmfUpb[i] = cmf[i];
                if (trend[i]==-1 && slope[i] ==-1) cmfDna[i] = cmf[i];
                if (trend[i]==-1 && slope[i] == 1) cmfDnb[i] = cmf[i];
            }
            else
            {                  
                if (trend[i]== 1) cmfUpa[i] = cmf[i];
                if (trend[i]==-1) cmfDna[i] = cmf[i];
            }
               
      }
      manageAlerts();
      return(0);
   }      
  
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (ArrayRange(trends,0)!=Bars) {  ArrayResize(trends,Bars); }
   for(i = limit, r=Bars-i-1; i>=0; i--,r++)
   {
     int y = iBarShift(NULL,timeFrame,Time[i]);
         cmf[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,SmoothLength,SmoothPhase,SmoothDouble,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,levelOs,levelOb,Interpolate,4,y);
         trend[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,SmoothLength,SmoothPhase,SmoothDouble,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,levelOs,levelOb,Interpolate,5,y);
         slope[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,SmoothLength,SmoothPhase,SmoothDouble,divergenceVisible,divergenceOnValuesVisible,divergenceOnChartVisible,divergenceBullishColor,divergenceBearishColor,shortName,levelOs,levelOb,Interpolate,6,y);
         cmfDna[i] = EMPTY_VALUE;
         cmfDnb[i] = EMPTY_VALUE;
         cmfUpa[i] = EMPTY_VALUE;
         cmfUpb[i] = EMPTY_VALUE;

         setTrends(i,r);

         //
         //
         //
         //
         //
      
         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++)
            {
               cmf[i+x] = cmf[i] + (cmf[i+n] - cmf[i])*x/n;
               if (cmfDna[i] != EMPTY_VALUE) cmfDna[i+x] = cmf[i+x];
               if (cmfDnb[i] != EMPTY_VALUE) cmfDnb[i+x] = cmf[i+x];
               if (cmfUpa[i] != EMPTY_VALUE) cmfUpa[i+x] = cmf[i+x];
               if (cmfUpb[i] != EMPTY_VALUE) cmfUpb[i+x] = cmf[i+x];
            }
   }
   for (i=limit;i>=0;i--)
   {
      if (HistogramOnSlope)
      {
         if (trend[i]== 1 && slope[i] == 1) cmfUpa[i] = cmf[i];
         if (trend[i]== 1 && slope[i] ==-1) cmfUpb[i] = cmf[i];
         if (trend[i]==-1 && slope[i] ==-1) cmfDna[i] = cmf[i];
         if (trend[i]==-1 && slope[i] == 1) cmfDnb[i] = cmf[i];
      }
      else
      {                  
         if (trend[i]== 1) cmfUpa[i] = cmf[i];
         if (trend[i]==-1) cmfDna[i] = cmf[i];
      } 
                               
   }
   manageAlerts();
   return(0);
}



//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+


void setTrends(int i, int r)
{
   trends[r][_tdn1] = trends[r-1][_tdn1];
   trends[r][_tup1] = trends[r-1][_tup1];
   trends[r][_tmi]  = trends[r-1][_tmi];

      if (cmf[i] > cmf[i+1])                       trends[r][_tdn1] =  1;
      if (cmf[i] < cmf[i+1])                       trends[r][_tdn1] = -1;
      if (cmf[i] > 0)                              trends[r][_tup1] =  1;
      if (cmf[i] < 0)                              trends[r][_tup1] = -1;
      if (cmf[i] < levelOs && cmf[i+1] >= levelOs) trends[r][_tmi]  =  1;
      if (cmf[i] > levelOb && cmf[i+1] <= levelOb) trends[r][_tmi]  = -1;
}


//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar)); 
                             whichBar = Bars-whichBar-1;

      //
      //
      //
      //
      //
            
      static datetime time1 = 0;
      static string   mess1 = "";
      if (alertsOnSlopeChange && trends[whichBar][_tdn1] != trends[whichBar-1][_tdn1])
      {
         if (trends[whichBar][_tdn1] ==  1) doAlert(time1,mess1,whichBar,"slope change up");
         if (trends[whichBar][_tdn1] == -1) doAlert(time1,mess1,whichBar,"slope change down");
      }
      static datetime time2 = 0;
      static string   mess2 = "";
      if (alertsOnZeroCross && trends[whichBar][_tup1] != trends[whichBar-1][_tup1])
      {
         if (trends[whichBar][_tup1] ==  1) doAlert(time2,mess2,whichBar,"crossed zero up");
         if (trends[whichBar][_tup1] == -1) doAlert(time2,mess2,whichBar,"crossed zero down");
      }
      static datetime time3 = 0;
      static string   mess3 = "";
      if (alertsOnOsObCross && trends[whichBar][_tmi] != trends[whichBar-1][_tmi])
      {
         if (trends[whichBar][_tmi] ==  1) doAlert(time3,mess3,whichBar,"crossed oversold line up");
         if (trends[whichBar][_tmi] == -1) doAlert(time3,mess3,whichBar,"crossed overbought line down");
      }
   }
}

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, int forBar, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," Chalkin Money Flow ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Chalkin Money Flow "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

double wrk[][20];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iDSmooth(double price, double length, double phase, bool isDouble, int i, int s=0)
{
   if (isDouble)
         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 CatchBullishDivergence(double& values[], int i)
{
   i++;
            ObjectDelete(divergenceUniqueID+"l"+DoubleToStr(Time[i],0));
            ObjectDelete(divergenceUniqueID+"l"+"os" + DoubleToStr(Time[i],0));            
   if (!IsIndicatorLow(values,i)) return;  

   //
   //
   //
   //
   //

   int currentLow = i;
   int lastLow    = GetIndicatorLastLow(values,i+1);
      if (values[currentLow] > values[lastLow] && Low[currentLow] < Low[lastLow])
      {
         if(divergenceOnChartVisible)  DrawPriceTrendLine("l",Time[currentLow],Time[lastLow],Low[currentLow],Low[lastLow],divergenceBullishColor,STYLE_SOLID);
         if(divergenceOnValuesVisible) DrawIndicatorTrendLine("l",Time[currentLow],Time[lastLow],values[currentLow],values[lastLow],divergenceBullishColor,STYLE_SOLID);
      }
      if (values[currentLow] < values[lastLow] && Low[currentLow] > Low[lastLow])
      {
         if(divergenceOnChartVisible)  DrawPriceTrendLine("l",Time[currentLow],Time[lastLow],Low[currentLow],Low[lastLow], divergenceBullishColor, STYLE_DOT);
         if(divergenceOnValuesVisible) DrawIndicatorTrendLine("l",Time[currentLow],Time[lastLow],values[currentLow],values[lastLow], divergenceBullishColor, STYLE_DOT);
      }
}

//
//
//
//
//

void CatchBearishDivergence(double& values[], int i)
{
   i++; 
            ObjectDelete(divergenceUniqueID+"h"+DoubleToStr(Time[i],0));
            ObjectDelete(divergenceUniqueID+"h"+"os" + DoubleToStr(Time[i],0));            
   if (IsIndicatorPeak(values,i) == false) return;

   //
   //
   //
   //
   //
      
   int currentPeak = i;
   int lastPeak = GetIndicatorLastPeak(values,i+1);
      if (values[currentPeak] < values[lastPeak] && High[currentPeak]>High[lastPeak])
      {
         if (divergenceOnChartVisible)  DrawPriceTrendLine("h",Time[currentPeak],Time[lastPeak],High[currentPeak],High[lastPeak],divergenceBearishColor,STYLE_SOLID);
         if (divergenceOnValuesVisible) DrawIndicatorTrendLine("h",Time[currentPeak],Time[lastPeak],values[currentPeak],values[lastPeak],divergenceBearishColor,STYLE_SOLID);
      }
      if(values[currentPeak] > values[lastPeak] && High[currentPeak] < High[lastPeak])
      {
         if (divergenceOnChartVisible)  DrawPriceTrendLine("h",Time[currentPeak],Time[lastPeak],High[currentPeak],High[lastPeak], divergenceBearishColor, STYLE_DOT);
         if (divergenceOnValuesVisible) DrawIndicatorTrendLine("h",Time[currentPeak],Time[lastPeak],values[currentPeak],values[lastPeak], divergenceBearishColor, STYLE_DOT);
      }
}

//
//
//
//
//

bool IsIndicatorPeak(double& values[], int i) { return(values[i] >= values[i+1] && values[i] > values[i+2] && values[i] > values[i-1]); }
bool IsIndicatorLow( double& values[], int i) { return(values[i] <= values[i+1] && values[i] < values[i+2] && values[i] < values[i-1]); }

int GetIndicatorLastPeak(double& values[], int shift)
{
   for(int i = shift+5; i<Bars; i++)
         if (values[i] >= values[i+1] && values[i] > values[i+2] && values[i] >= values[i-1] && values[i] > values[i-2]) return(i);
   return(-1);
}
int GetIndicatorLastLow(double& values[], int shift)
{
   for(int i = shift+5; i<Bars; i++)
         if (values[i] <= values[i+1] && values[i] < values[i+2] && values[i] <= values[i-1] && values[i] < values[i-2]) return(i);
   return(-1);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

void DrawPriceTrendLine(string first,datetime t1, datetime t2, double p1, double p2, color lineColor, double style)
{
   string   label = divergenceUniqueID+first+"os"+DoubleToStr(t1,0);
   if (Interpolate) t2 += Period()*60-1;
    
   ObjectDelete(label);
      ObjectCreate(label, OBJ_TREND, 0, t1+Period()*60-1, p1, t2, p2, 0, 0);
         ObjectSet(label, OBJPROP_RAY, false);
         ObjectSet(label, OBJPROP_COLOR, lineColor);
         ObjectSet(label, OBJPROP_STYLE, style);
}
void DrawIndicatorTrendLine(string first,datetime t1, datetime t2, double p1, double p2, color lineColor, double style)
{
   int indicatorWindow = WindowFind(shortName);
   if (indicatorWindow < 0) return;
   if (Interpolate) t2 += Period()*60-1;
   
   string label = divergenceUniqueID+first+DoubleToStr(t1,0);
   ObjectDelete(label);
      ObjectCreate(label, OBJ_TREND, indicatorWindow, t1+Period()*60-1, p1, t2, p2, 0, 0);
         ObjectSet(label, OBJPROP_RAY, false);
         ObjectSet(label, OBJPROP_COLOR, lineColor);
         ObjectSet(label, OBJPROP_STYLE, style);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------

string sTfTable[] = {"M1","M5","M10","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,10,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);
}