//+------------------------------------------------------------------+
//|                                                 dynamic zone cci |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  clrDeepSkyBlue
#property indicator_color2  clrLimeGreen
#property indicator_color3  clrRed
#property indicator_color4  clrDimGray
#property indicator_width1  2
#property indicator_style4  STYLE_DOT

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuy(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i );
   double dzSell(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i );
#import

//
//
//
//
//

//
//
//
//
//

enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_tbiased2,   // Trend biased (extreme) price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased,  // Heiken ashi trend biased price
   pr_hatbiased2, // Heiken ashi trend biased (extreme) price
   pr_habclose,   // Heiken ashi (better formula) close
   pr_habopen ,   // Heiken ashi (better formula) open
   pr_habhigh,    // Heiken ashi (better formula) high
   pr_hablow,     // Heiken ashi (better formula) low
   pr_habmedian,  // Heiken ashi (better formula) median
   pr_habtypical, // Heiken ashi (better formula) typical
   pr_habweighted,// Heiken ashi (better formula) weighted
   pr_habaverage, // Heiken ashi (better formula) average
   pr_habmedianb, // Heiken ashi (better formula) median body
   pr_habtbiased, // Heiken ashi (better formula) trend biased price
   pr_habtbiased2 // Heiken ashi (better formula) trend biased (extreme) price
};

extern ENUM_TIMEFRAMES TimeFrame     = PERIOD_CURRENT;     // Time frame to use
extern int    CciLength              = 10;
extern enPrices CciPrice             = pr_typical;
extern int    CciSmooth              = 3;
extern int    DzLookBackBars         = 70;
extern double DzStartBuyProbability  = 0.05;
extern double DzStartSellProbability = 0.05;
input bool    showAllZoneBreakOut    = true;
extern bool   alertsOn               = false;
extern bool   alertsOnZeroCross      = false;
extern bool   alertsOnUpLowCross     = true;
extern bool   alertsOnCurrent        = true;
extern bool   alertsMessage          = true;
extern bool   alertsSound            = false;
extern bool   alertsEmail            = false;
input bool    alertsNotify           = false;
extern bool   arrowsVisible          = true;
extern string arrowsIdentifier       = "Dz cci Arrows";
input bool    arrowsOnNewest         = false;              // Arrows drawn on newst bar of higher time frame bar?
extern double arrowsDisplacement     = 1.0;
extern bool   arrowsOnZeroCross      = false;
extern color  arrowsZeroCrossUpColor = clrLime;
extern color  arrowsZeroCrossDnColor = clrRed;
extern int    arrowsZeroCrossUpCode  = 233;
extern int    arrowsZeroCrossDnCode  = 234;
extern int    arrowsZeroCrossUpSize  = 1;
extern int    arrowsZeroCrossDnSize  = 1;
extern bool   arrowsOnUpLowCross     = true;
extern color  arrowsUpLowCrossUpColor= clrPaleGreen;
extern color  arrowsUpLowCrossDnColor= clrRed;
extern int    arrowsUpLowCrossUpCode = 233;
extern int    arrowsUpLowCrossDnCode = 234;
extern int    arrowsUpLowCrossUpSize = 1;
extern int    arrowsUpLowCrossDnSize = 1;  
input bool    Interpolate            = true;               // Interpolate in multi time frame mode?

double cci[],ccs[],ccw[],cen[],bli[],sli[],trend1[],trend2[],count[],alpha;
string indicatorFileName;
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,CciLength,CciPrice,CciSmooth,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,showAllZoneBreakOut,alertsOn,alertsOnZeroCross,alertsOnUpLowCross,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotify,arrowsVisible,arrowsIdentifier,arrowsOnNewest,arrowsDisplacement,arrowsOnZeroCross,arrowsZeroCrossUpColor,arrowsZeroCrossDnColor,arrowsZeroCrossUpCode,arrowsZeroCrossDnCode,arrowsZeroCrossUpSize,arrowsZeroCrossDnSize,arrowsOnUpLowCross,arrowsUpLowCrossUpColor,arrowsUpLowCrossDnColor,arrowsUpLowCrossUpCode,arrowsUpLowCrossDnCode,arrowsUpLowCrossUpSize,arrowsUpLowCrossDnSize,_buff,_ind)

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int OnInit()
{
   if (!IsDllsAllowed())
   {
      Alert("and then attach it to the chart again");
      Alert("Please enable DLL imports in the indicator properties");
      Alert("This indicator needs dlls to work");
      return(INIT_FAILED);
   }
   IndicatorBuffers(9);
   SetIndexBuffer(0,ccs); SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(1,bli); SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(2,sli); SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(3,cen); SetIndexStyle(3,DRAW_LINE);
   SetIndexBuffer(4,cci);
   SetIndexBuffer(5,ccw);
   SetIndexBuffer(6,trend1);
   SetIndexBuffer(7,trend2);
   SetIndexBuffer(8,count);

   CciLength         = fmax(CciLength ,1);
   alpha             = 2.0 /(1.0+sqrt(CciSmooth));
   indicatorFileName = WindowExpertName();
   TimeFrame         = fmax(TimeFrame,_Period); 
   
   IndicatorShortName(timeFrameToString(TimeFrame)+" Dynamic zone CCI ("+(string)CciLength+","+(string)DzLookBackBars+","+DoubleToStr(DzStartBuyProbability,3)+","+DoubleToStr(DzStartSellProbability,3)+")");
   return(INIT_SUCCEEDED);
}
int deinit()
{
   if (arrowsVisible) deleteArrows();
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int i,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = fmin(Bars-counted_bars,Bars-1); count[0]=limit;
            if (TimeFrame!=_Period)
            {
               limit = (int)fmax(limit,fmin(Bars-1,_mtfCall(8,0)*TimeFrame/_Period));
               for (i=limit;i>=0 && !_StopFlag; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                     ccs[i] = _mtfCall(0,y);
                     bli[i] = _mtfCall(1,y);
                     sli[i] = _mtfCall(2,y);
                     cen[i] = _mtfCall(3,y);
                     
                     //
                     //
                     //
                     //
                     //
                     
                     if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,Time[i-1]))) continue;
                        #define _interpolate(buff) buff[i+k] = buff[i]+(buff[i+n]-buff[i])*k/n
                        int n,k; datetime time = iTime(NULL,TimeFrame,y);
                           for(n = 1; (i+n)<Bars && Time[i+n] >= time; n++) continue;	
                           for(k = 1; k<n && (i+n)<Bars && (i+k)<Bars; k++) 
                           {
                              _interpolate(ccs);
                              _interpolate(bli);
                              _interpolate(sli);
                              _interpolate(cen);
                           }                           
               }
   return(0);
   }

   //
   //
   //
   //
   //
   //

   for(i=limit; i >= 0; i--)
   {
      cci[i] = iCci(getPrice(CciPrice,Open,Close,High,Low,i,Bars),CciLength,i,Bars);
         if (i==Bars-1)
         {
            ccw[i] = cci[i];
            ccs[i] = cci[i];
            continue;
         }
      
      //
      //
      //
      //
      //
      
      if (CciSmooth>1)
      {
            ccw[i] = ccw[i+1]+alpha*(cci[i]-ccw[i+1]);
            ccs[i] = ccs[i+1]+alpha*(ccw[i]-ccs[i+1]);
      }
      else  ccs[i] = cci[i];         
      bli[i] = dzBuy (ccs, DzStartBuyProbability,  DzLookBackBars, Bars, i);
      sli[i] = dzSell(ccs, DzStartSellProbability, DzLookBackBars, Bars, i);
      cen[i] = dzSell(ccs, 0.5,                    DzLookBackBars, Bars, i);
      trend2[i] = (i<Bars-1 && !showAllZoneBreakOut) ? trend2[i+1] : 0;
      trend1[i] = trend1[i+1];
         if (ccs[i]>cen[i])                        trend1[i] =  1;
         if (ccs[i]<cen[i])                        trend1[i] = -1;
         if (ccs[i]>bli[i] && ccs[i+1]<= bli[i+1]) trend2[i] =  1;
         if (ccs[i]<sli[i] && ccs[i+1]>= sli[i+1]) trend2[i] = -1;
         manageArrow(i);
   }
   manageAlerts();
return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//

#define cciInstances 1
double workCci[][cciInstances*1];
double iCci(double price, int period, int r, int bars, int instanceNo=0)
{
   if (ArrayRange(workCci,0)!= bars) ArrayResize(workCci,bars); r=bars-r-1;
   
   //
   //
   //
   //
   //
   
      workCci[r][instanceNo] = price;
         double tcci = 0;
         double avg  = 0; for(int k=0; k<period && (r-k)>=0; k++) avg +=         workCci[r-k][instanceNo];   avg /= period;
         double dev  = 0; for(k=0; k<period && (r-k)>=0; k++) dev += fabs(workCci[r-k][instanceNo]-avg); dev /= period;
         if (dev!=0)
               tcci = (price-avg)/(0.015*dev);
   return(tcci);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,0,whichBar));
      
      //
      //
      //
      //
      //
      
      static datetime time1 = 0;
      static string   mess1 = "";
         if (alertsOnZeroCross && trend1[whichBar] != trend1[whichBar+1])
         {
            if (trend1[whichBar] ==  1) doAlert(time1,mess1,whichBar,"  zero line cross");
            if (trend1[whichBar] == -1) doAlert(time1,mess1,whichBar,"  zero line cross");
         }            
      static datetime time2 = 0;
      static string   mess2 = "";
         if (alertsOnUpLowCross && trend2[whichBar] != trend2[whichBar+1])
         {
            if (trend2[whichBar] ==  1) doAlert(time2,mess2,whichBar," lower line cross up");
            if (trend2[whichBar] == -1) doAlert(time2,mess2,whichBar," upper line cross 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 = timeFrameToString(_Period)+" "+_Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" DZ CCI "+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(_Symbol+" DZ CCI ",message);
             if (alertsNotify)  SendNotification(message);
             if (alertsSound)   PlaySound("alert2.wav");
             
      }
}

//
//
//
//
//

void manageArrow(int i)
{
   if (arrowsVisible)
   {
      deleteArrow(Time[i]);
      if (arrowsOnZeroCross && trend1[i]!= trend1[i+1])
      {
         if (trend1[i] == 1) drawArrow(i,arrowsZeroCrossUpColor,arrowsZeroCrossUpCode,arrowsZeroCrossUpSize,false);
         if (trend1[i] ==-1) drawArrow(i,arrowsZeroCrossDnColor,arrowsZeroCrossDnCode,arrowsZeroCrossDnSize, true);
      }
      if (arrowsOnUpLowCross && trend2[i]!= trend2[i+1])
      {
         if (trend2[i] == 1) drawArrow(i,arrowsUpLowCrossUpColor,arrowsUpLowCrossUpCode,arrowsUpLowCrossUpSize,false);
         if (trend2[i] ==-1) drawArrow(i,arrowsUpLowCrossDnColor,arrowsUpLowCrossDnCode,arrowsUpLowCrossDnSize, true);
      }
      
   }
}               

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,int theSize, bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = iATR(NULL,0,20,i);   
   
      //
      //
      //
      //
      //
      
      int add = 0; if (!arrowsOnNewest) add = _Period*60-1;
      ObjectCreate(name,OBJ_ARROW,0,Time[i]+add,0); 
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,   theColor);
         ObjectSet(name,OBJPROP_WIDTH,    theSize);      
         
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i] + arrowsDisplacement * gap);
         else  ObjectSet(name,OBJPROP_PRICE1, Low[i] - arrowsDisplacement * gap);
}

//
//
//
//
//

void deleteArrows()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}

//
//
//
//
//

void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     2
#define _priceInstancesSize 4
double workHa[][_priceInstances*_priceInstancesSize];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars, int instanceNo=0)
{
  if (tprice>=pr_haclose)
   {
      if (ArrayRange(workHa,0)!= bars) ArrayResize(workHa,bars); instanceNo*=_priceInstancesSize; int r = bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen  = (r>0) ? (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0 : (open[i]+close[i])/2;;
         double haClose = (open[i]+high[i]+low[i]+close[i]) / 4.0;
         if (_prHABF(tprice))
               if (high[i]!=low[i])
                     haClose = (open[i]+close[i])/2.0+(((close[i]-open[i])/(high[i]-low[i]))*MathAbs((close[i]-open[i])/2.0));
               else  haClose = (open[i]+close[i])/2.0; 
         double haHigh  = fmax(high[i], fmax(haOpen,haClose));
         double haLow   = fmin(low[i] , fmin(haOpen,haClose));

         //
         //
         //
         //
         //
         
         if(haOpen<haClose) { workHa[r][instanceNo+0] = haLow;  workHa[r][instanceNo+1] = haHigh; } 
         else               { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow;  } 
                              workHa[r][instanceNo+2] = haOpen;
                              workHa[r][instanceNo+3] = haClose;
         //
         //
         //
         //
         //
         
         switch (tprice)
         {
            case pr_haclose:
            case pr_habclose:    return(haClose);
            case pr_haopen:   
            case pr_habopen:     return(haOpen);
            case pr_hahigh: 
            case pr_habhigh:     return(haHigh);
            case pr_halow:    
            case pr_hablow:      return(haLow);
            case pr_hamedian:
            case pr_habmedian:   return((haHigh+haLow)/2.0);
            case pr_hamedianb:
            case pr_habmedianb:  return((haOpen+haClose)/2.0);
            case pr_hatypical:
            case pr_habtypical:  return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:
            case pr_habweighted: return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:  
            case pr_habaverage:  return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
            case pr_habtbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
            case pr_hatbiased2:
            case pr_habtbiased2:
               if (haClose>haOpen)  return(haHigh);
               if (haClose<haOpen)  return(haLow);
                                    return(haClose);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (tprice)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
      case pr_tbiased2:   
               if (close[i]>open[i]) return(high[i]);
               if (close[i]<open[i]) return(low[i]);
                                     return(close[i]);        
   }
   return(0);
}

//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}



