//+------------------------------------------------------------------+
//|                                                  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     LimeGreen
#property indicator_color2     DarkGreen
#property indicator_color3     Red
#property indicator_color4     Maroon
#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_level1     0
#property indicator_levelcolor Gold
#property indicator_levelstyle STYLE_DOT

//
//
//
//
//

extern string TimeFrame               = "Current time frame";
extern int    CmfPeriod               = 20;
extern int    T3Period                = 5;
extern double T3Hot                   = 0.70;
extern bool   T3Original              = true;
extern bool   Interpolate             = true;
extern bool   InterpolateColors       = false;

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

//
//
//
//
//

double cmf[];
double green_buffer[];
double dkgreen_buffer[];
double red_buffer[];
double maroon_buffer[];
double emas[][6];
double trends[][3];

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

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

//
//
//
//
//

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

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

int init()
{
   SetIndexBuffer(0,green_buffer);     SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID);
   SetIndexBuffer(1,dkgreen_buffer);   SetIndexStyle(1,DRAW_HISTOGRAM,STYLE_SOLID);
   SetIndexBuffer(2,red_buffer);       SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_SOLID);
   SetIndexBuffer(3,maroon_buffer);    SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_SOLID);
   SetIndexBuffer(4,cmf);
   
   //
   //
   //
   //
   //
   
   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)+" 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 (ArrayRange(emas,0) != Bars) ArrayResize(emas,Bars);
         if (returnBars)  { green_buffer[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++)
   {
   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);
      dkgreen_buffer[i] = 0;
      green_buffer[i]   = 0;
      red_buffer[i]     = 0;
      maroon_buffer[i]  = 0;
        
      if(cmf[i] > 0) 
      if(cmf[i] > cmf[i+1])
            green_buffer[i]   = cmf[i];
      else  dkgreen_buffer[i] = cmf[i];
      
      if(cmf[i] < 0) 
      if(cmf[i] < cmf[i+1])
            red_buffer[i]     = cmf[i];
      else  maroon_buffer[i]  = cmf[i];
      setTrends(i,r);
      
      }
      
      manageAlerts();
      return(0);
   }
  
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars,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,T3Period,T3Hot,T3Original,4,y);
      green_buffer[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,T3Period,T3Hot,T3Original,0,y);
      dkgreen_buffer[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,T3Period,T3Hot,T3Original,1,y);
      red_buffer[i]     = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,T3Period,T3Hot,T3Original,2,y);
      maroon_buffer[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CmfPeriod,T3Period,T3Hot,T3Original,3,y);
      
      setTrends(i,r);

      //
      //
      //
      //
      //
      
      if (timeFrame <= Period() || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
      if (!Interpolate) 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;
            
            if (InterpolateColors)
            {
               green_buffer[i+k]   = green_buffer[i]  + (green_buffer[i+n]  - green_buffer[i]  )*k/n;
               dkgreen_buffer[i+k] = dkgreen_buffer[i]+ (dkgreen_buffer[i+n]- dkgreen_buffer[i])*k/n;
               red_buffer[i+k]     = red_buffer[i]    + (red_buffer[i+n]    - red_buffer[i]    )*k/n;
               maroon_buffer[i+k]  = maroon_buffer[i] + (maroon_buffer[i+n] - maroon_buffer[i] )*k/n;
            }
            else
            {
               if (green_buffer[i]  !=0) green_buffer[i+k]   = cmf[i+k];
               if (dkgreen_buffer[i]!=0) dkgreen_buffer[i+k] = cmf[i+k];
               if (red_buffer[i]    !=0) red_buffer[i+k]     = cmf[i+k];
               if (maroon_buffer[i] !=0) maroon_buffer[i+k]  = cmf[i+k];
            }               
         }             
     }
   
   //
   //
   //
   //
   //
   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 && cmf[i] > cmf[i+1])  trends[r][_tup1] =  1;
      if (cmf[i] < 0 && cmf[i] < cmf[i+1])  trends[r][_tup1] = -1;
      if (cmf[i] > 0)                       trends[r][_tmi]  =  1;
      if (cmf[i] < 0)                       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 (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");
      }
   }
}

//
//
//
//
//

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)
{
   
   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 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);
}