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

#property indicator_separate_window
#property indicator_buffers    6
#property indicator_color1     DeepSkyBlue
#property indicator_color2     PaleVioletRed
#property indicator_color3     PaleVioletRed
#property indicator_width1     2
#property indicator_width2     2
#property indicator_width3     2
#property indicator_color4     LimeGreen
#property indicator_color5     Red
#property indicator_color6     DimGray
#property indicator_style6     STYLE_DASHDOT



//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuyP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision);
   double dzSellP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision);
#import


//
//
//
//
//

extern string TimeFrame               = "Current time frame";
extern int    CmfPeriod               = 20;
extern int    T3Period                = 5;
extern double T3Hot                   = 0.70;
extern bool   T3Original              = true;
extern int    DzLookBackBars          = 70;
extern double DzStartBuyProbability   = 0.05;
extern double DzStartSellProbability  = 0.05;
extern bool   Interpolate             = true;
extern bool   MultiColor              = true;

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

//
//
//
//
//

double cmf[];
double cmfUa[];
double cmfUb[];
double bli[];
double sli[];
double zli[];
double slope[];
double emas[][6];
double trends[][4];

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

double alpha;
double c1;
double c2;
double c3;
double c4;

//
//
//
//
//

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

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

int init()
{
   IndicatorBuffers(7);
   SetIndexBuffer(0,cmf);
   SetIndexBuffer(1,cmfUa);
   SetIndexBuffer(2,cmfUb);
   SetIndexBuffer(3,bli);
   SetIndexBuffer(4,sli);
   SetIndexBuffer(5,zli);
   SetIndexBuffer(6,slope);
   
   //
   //
   //
   //
   //
   
   double a = T3Hot;
      c1 = -a*a*a;
      c2 =  3*(a*a+a*a*a);
      c3 = -3*(2*a*a+a+a*a*a);
      c4 = 1+3*a+a*a*a+3*a*a;

      T3Period = MathMax(1,T3Period);
      if (T3Original)
           alpha = 2.0/(1.0 + T3Period);
      else alpha = 2.0/(2.0 + (T3Period-1.0)/2.0);
      
   //
   //
   //
   //
   //
      
   indicatorFileName = WindowExpertName();
   calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
   returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
   timeFrame         = stringToTimeFrame(TimeFrame);
      
   //
   //
   //
   //
   //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" Dynamic zone Cmf T3 ");
   return(0);
}

//
//
//
//
//

int deinit() { return(0); }

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


int start()
  {
   
   int counted_bars=IndicatorCounted();
   int i,j,n,k,r,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit=MathMin(Bars-counted_bars,Bars-1);
         
         
   
         if (returnBars)  { cmf[0] = limit+1; return(0); }
   
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
   
   if (ArrayRange(trends,0)!=Bars) {  ArrayResize(trends,Bars); }
   
   if (MultiColor && !calculateValue && slope[limit]==-1) CleanPoint(limit,cmfUa,cmfUb);
   
   
   
   for(i = limit, r=Bars-i-1; i>=0; i--,r++)
   {
   double dN_Sum     = 0.0;
   double Volume_Sum = 0.0;
   
   //
   //
   //
   //
   //
   
      for(j=0; j < CmfPeriod; j++) { Volume_Sum += Volume[i+j];
      
      if((High[i+j]-Low[i+j]) > 0) dN_Sum += Volume[i+j]*(Close[i+j]-Open[i+j])/(High[i+j]-Low[i+j]); }
      
      //
      //
      //
      //
      //
      
       cmf[i]  = iT3(dN_Sum/Volume_Sum,i);
       bli[i]  = dzBuyP (cmf, DzStartBuyProbability,  DzLookBackBars, Bars, i,0.0001);
       sli[i]  = dzSellP(cmf, DzStartSellProbability, DzLookBackBars, Bars, i,0.0001);
       zli[i]  = dzSellP(cmf, 0.5,                    DzLookBackBars, Bars, i,0.0001);
       slope[i]= slope[i+1];
      
            if (cmf[i]>cmf[i+1]) slope[i] =  1;
            if (cmf[i]<cmf[i+1]) slope[i] = -1;
            
            if (MultiColor && !calculateValue && slope[i]==-1) PlotPoint(i,cmfUa,cmfUb,cmf);
            
      setTrends(i,r);
      
      }
      
      manageAlerts();
      return(0);
   }
  
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (MultiColor && slope[limit]==-1) CleanPoint(limit,cmfUa,cmfUb);
   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,T3Period,T3Hot,T3Original,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,0,y);
      cmfUa[i]= EMPTY_VALUE;
      cmfUb[i]= EMPTY_VALUE;
      bli[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,T3Period,T3Hot,T3Original,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,3,y);
      sli[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,T3Period,T3Hot,T3Original,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,4,y);
      zli[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,T3Period,T3Hot,T3Original,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,5,y);
      slope[i]= iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,T3Period,T3Hot,T3Original,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,6,y);

      
      setTrends(i,r);

      if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(k = 1; k < n; k++)
            {
               cmf[i+k] = cmf[i]  + (cmf[i+n] -cmf[i])*k/n;
               bli[i+k] = bli[i]  + (bli[i+n] -bli[i])*k/n;
               sli[i+k] = sli[i]  + (sli[i+n] -sli[i])*k/n;
               zli[i+k] = zli[i]  + (zli[i+n] -zli[i])*k/n;
               
            }               
   }
   if (MultiColor) for (i=limit;i>=0;i--) if (slope[i]==-1) PlotPoint(i,cmfUa,cmfUb,cmf);
   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];
   trends[r][_tosob]  = trends[r-1][_tosob];

      if (cmf[i] > cmf[i+1])                     trends[r][_tdn1] =  1;
      if (cmf[i] < cmf[i+1])                     trends[r][_tdn1] = -1;
      if (cmf[i] > zli[i] && cmf[i] > cmf[i+1])  trends[r][_tup1] =  1;
      if (cmf[i] < zli[i] && cmf[i] < cmf[i+1])  trends[r][_tup1] = -1;
      if (cmf[i] > zli[i])                       trends[r][_tmi]  =  1;
      if (cmf[i] < zli[i])                       trends[r][_tmi]  = -1;
      if (cmf[i] < bli[i] && cmf[i] > cmf[i+1])  trends[r][_tosob]  =  1;
      if (cmf[i] > sli[i] && cmf[i] < cmf[i+1])  trends[r][_tosob]  = -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 (alertsOnZeroCrossSlope && trends[whichBar][_tup1] != trends[whichBar-1][_tup1])
      {
         if (trends[whichBar][_tup1] ==  1) doAlert(time2,mess2,whichBar,"crossed zero sloping up");
         if (trends[whichBar][_tup1] == -1) doAlert(time2,mess2,whichBar,"crossed zero sloping down");
      }
      static datetime time3 = 0;
      static string   mess3 = "";
      if (alertsOnZeroCross && trends[whichBar][_tmi] != trends[whichBar-1][_tmi])
      {
         if (trends[whichBar][_tmi] ==  1) doAlert(time3,mess3,whichBar,"crossed zero line up");
         if (trends[whichBar][_tmi] == -1) doAlert(time3,mess3,whichBar, "crossed zero line down");
      }
      static datetime time4 = 0;
      static string   mess4 = "";
      if (alertsOnSlopeOsOb && trends[whichBar][_tosob] != trends[whichBar-1][_tosob])
      {
         if (trends[whichBar][_tmi] ==  1) doAlert(time4,mess4,whichBar,"crossed buy line up");
         if (trends[whichBar][_tmi] == -1) doAlert(time4,mess4,whichBar, "crossed sell 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 iT3(double price,int shift)
{
   if (ArrayRange(emas,0) != Bars) ArrayResize(emas,Bars);
   
   int i = Bars-shift-1;
   if (i < 1)
      {
         emas[i][0] = price;
         emas[i][1] = price;
         emas[i][2] = price;
         emas[i][3] = price;
         emas[i][4] = price;
         emas[i][5] = price;
      }
   else
      {
         emas[i][0] = emas[i-1][0]+alpha*(price     -emas[i-1][0]);
         emas[i][1] = emas[i-1][1]+alpha*(emas[i][0]-emas[i-1][1]);
         emas[i][2] = emas[i-1][2]+alpha*(emas[i][1]-emas[i-1][2]);
         emas[i][3] = emas[i-1][3]+alpha*(emas[i][2]-emas[i-1][3]);
         emas[i][4] = emas[i-1][4]+alpha*(emas[i][3]-emas[i-1][4]);
         emas[i][5] = emas[i-1][5]+alpha*(emas[i][4]-emas[i-1][5]);
      }
   return(c1*emas[i][5] + c2*emas[i][4] + c3*emas[i][3] + c4*emas[i][2]);
}

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

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 char1 = StringGetChar(s, length);
         if((char1 > 96 && char1 < 123) || (char1 > 223 && char1 < 256))
                     s = StringSetChar(s, length, char1 - 32);
         else if(char1 > -33 && char1 < 0)
                     s = StringSetChar(s, length, char1 + 224);
   }
   return(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;
      }
}
  