//+------------------------------------------------------------------+
//|                                                 dynamic zone cci |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  DeepSkyBlue
#property indicator_color2  LimeGreen
#property indicator_color3  Red
#property indicator_color4  DimGray
#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 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;

extern string arrowsIdentifier       = "Dz cci Arrows";
extern bool   arrowsVisible          = TRUE;
extern double arrowsDisplacement     = 1.0;

extern bool   arrowsOnZeroCross      = false;
extern color  arrowsZeroCrossUpColor = Lime;
extern color  arrowsZeroCrossDnColor = Red;
extern int    arrowsZeroCrossUpCode  = 233;
extern int    arrowsZeroCrossDnCode  = 234;
extern int    arrowsZeroCrossUpSize  = 1;
extern int    arrowsZeroCrossDnSize  = 1;

extern bool   arrowsOnUpLowCross     = true;
extern color  arrowsUpLowCrossUpColor= PaleGreen;
extern color  arrowsUpLowCrossDnColor= Red;
extern int    arrowsUpLowCrossUpCode = 233;
extern int    arrowsUpLowCrossDnCode = 234;
extern int    arrowsUpLowCrossUpSize = 1;
extern int    arrowsUpLowCrossDnSize = 1;  

//
//
//
//
//

double cci[];
double ccs[];
double ccw[];
double cen[];
double bli[];
double sli[];
double trend1[];
double trend2[];
double alpha;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,ccs);
   SetIndexBuffer(1,bli);
   SetIndexBuffer(2,sli);
   SetIndexBuffer(3,cen);
   SetIndexBuffer(4,cci);
   SetIndexBuffer(5,ccw);
   SetIndexBuffer(6,trend1);
   SetIndexBuffer(7,trend2);

   

   CciLength = fmax(CciLength ,1);
   alpha     = 2.0 /(1.0+sqrt(CciSmooth));
   
   IndicatorShortName ("Dynamic zone CCI ("+CciLength+","+DzLookBackBars+","+DoubleToStr(DzStartBuyProbability,3)+","+DoubleToStr(DzStartSellProbability,3)+")");
   return(0);
}
int deinit()
{
   if (arrowsVisible) deleteArrows();
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);

   //
   //
   //
   //
   //
   //

   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 =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," DZ CCI ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," DZ CCI "),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);   
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],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);
}


