//+------------------------------------------------------------------
//| cci  adaptive smoother 
//+------------------------------------------------------------------
//
//

#property copyright "www,forex-station.com"
#property link      "www,forex-station.com"

#property indicator_separate_window
#property indicator_buffers    4
#property indicator_color1     clrGold
#property indicator_color2     clrLimeGreen
#property indicator_color3     clrRed
#property indicator_color4     clrDarkSlateGray
#property indicator_width1     2
#property indicator_width2     2
#property indicator_width3     2
#property indicator_width4     2
#property strict

//
//
//
//
//

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
};
enum enMaTypes
{
   ma_sma,     // Simple moving average
   ma_ema,     // Exponential moving average
   ma_smma,    // Smoothed MA
   ma_lwma,    // Linear weighted MA
};

input int            CciPeriod       = 14;                // Cci period
input enPrices       CciPrice        = pr_close;          // Cci and adaptive price to use
input int            AdaptPeriod     = 21;                // Adapt period
input bool           DeviationSample = false;             // Deviation with sample correction true/false?
input int            CciMaPeriod     = 7;                 // Cci ma period
input enMaTypes      CciMaMethod     = ma_sma;            // Cci moving average method  
input bool           ShowHistogram   = true;              // Show histogram true/false?
input bool           ShowCciMa       = true;              // Show cci ma true/false?
input double         OverSold        = -150;              // Over sold level
input double         OverBought      = 150;               // Over bought level
input bool           alertsOn        = true;              // Alerts on true/false?
input bool           alertsOnCurrent = true;              // Alerts on current open bar true/false?
input bool           alertsMessage   = true;              // Alerts message true/false?
input bool           alertsSound     = true;              // Alerts sound true/false?
input bool           alertsEmail     = false;             // Alerts email true/false? 
input bool           alertsNotify    = false;             // Alerts notification true/false?

double cci[],cciU[],cciD[],cciMa[],trend[];

//
//
//
//
//

int OnInit()
{
    IndicatorBuffers(5);
    SetIndexBuffer(0,cci,  INDICATOR_DATA);  SetIndexStyle(0,DRAW_LINE);
    SetIndexBuffer(1,cciU, INDICATOR_DATA);  SetIndexStyle(1,ShowHistogram ? DRAW_HISTOGRAM : DRAW_NONE);     
    SetIndexBuffer(2,cciD, INDICATOR_DATA);  SetIndexStyle(2,ShowHistogram ? DRAW_HISTOGRAM : DRAW_NONE);   
    SetIndexBuffer(3,cciMa,INDICATOR_DATA);  SetIndexStyle(3,ShowCciMa     ? DRAW_LINE : DRAW_NONE);
    SetIndexBuffer(4,trend,INDICATOR_CALCULATIONS); 
      
    IndicatorSetInteger(INDICATOR_LEVELS,3);
    IndicatorSetDouble( INDICATOR_LEVELVALUE,0,OverBought);
    IndicatorSetInteger(INDICATOR_LEVELSTYLE,0,STYLE_DOT);
    IndicatorSetDouble( INDICATOR_LEVELVALUE,1,OverSold);
    IndicatorSetInteger(INDICATOR_LEVELSTYLE,1,STYLE_DOT); 
    IndicatorSetDouble( INDICATOR_LEVELVALUE,2,0);
    IndicatorSetInteger(INDICATOR_LEVELSTYLE,2,STYLE_DOT);
 
      
    IndicatorSetString(INDICATOR_SHORTNAME," Cci Adaptive Smoother(" +(string)CciPeriod+ ", " +(string)AdaptPeriod+")");
return(INIT_SUCCEEDED);
}

//
//
//
//

      int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
  
   int i=rates_total-prev_calculated+1; if (i>=rates_total) i=rates_total-1; 

   //
   //
   //
   //
   //
   
   for (; i>=0 && !_StopFlag; i--)
   {
      double price  = getPrice(CciPrice,open,close,high,low,i,rates_total);
      double dev    = iDeviation(price,AdaptPeriod,DeviationSample,i,rates_total);
      double avg    = iCustomMa(CciMaMethod,dev,AdaptPeriod,i,rates_total,0);
      double period = (dev!=0) ? fmax(CciPeriod*avg/dev,2) : fmax(CciPeriod,1);
      if (period<3) period = 3;
      
      //
      //
      //
      //
      //
      
      cci[i]   = iSmooth(iCci(price,CciPeriod,i,rates_total),period,0,i,rates_total);
      cciMa[i] = iCustomMa(CciMaMethod,cci[i],CciMaPeriod,i,rates_total,1);
      trend[i] = (i<rates_total-1) ? (cci[i]>0) ? 1 : (cci[i]<0) ? -1 : trend[i+1] : 0;  
      cciU[i] = (trend[i] == 1) ? cci[i] : EMPTY_VALUE;
      cciD[i] = (trend[i] ==-1) ? cci[i] : EMPTY_VALUE;     
   }  
   manageAlerts();
return(rates_total);
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

#define _maInstances 2
#define _maWorkBufferx1 1*_maInstances
#define _maWorkBufferx2 2*_maInstances
#define _maWorkBufferx3 3*_maInstances

double iCustomMa(int mode, double price, double length, int r, int bars, int instanceNo=0)
{
   r = bars-r-1;
   switch (mode)
   {
      case ma_sma   : return(iSma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_ema   : return(iEma(price,length,r,bars,instanceNo));
      case ma_smma  : return(iSmma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_lwma  : return(iLwma(price,(int)ceil(length),r,bars,instanceNo));
      default       : return(price);
   }
}

//
//
//
//
//

double workSma[][_maWorkBufferx1];
double iSma(double price, int period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= _bars) ArrayResize(workSma,_bars);

   workSma[r][instanceNo+0] = price;
   double avg = price; int k=1;  for(; k<period && (r-k)>=0; k++) avg += workSma[r-k][instanceNo+0];  
   return(avg/(double)k);
}

//
//
//
//
//

double workEma[][_maWorkBufferx1];
double iEma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= _bars) ArrayResize(workEma,_bars);

   workEma[r][instanceNo] = price;
   if (r>0 && period>1)
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+(2.0/(1.0+period))*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//
//
//
//
//

double workSmma[][_maWorkBufferx1];
double iSmma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSmma,0)!= _bars) ArrayResize(workSmma,_bars);

   workSmma[r][instanceNo] = price;
   if (r>1 && period>1)
          workSmma[r][instanceNo] = workSmma[r-1][instanceNo]+(price-workSmma[r-1][instanceNo])/period;
   return(workSmma[r][instanceNo]);
}

//
//
//
//
//

double workLwma[][_maWorkBufferx1];
double iLwma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workLwma,0)!= _bars) ArrayResize(workLwma,_bars);
   
   workLwma[r][instanceNo] = price; if (period<=1) return(price);
      double sumw = period;
      double sum  = period*price;

      for(int k=1; k<period && (r-k)>=0; k++)
      {
         double weight = period-k;
                sumw  += weight;
                sum   += weight*workLwma[r-k][instanceNo];  
      }             
      return(sum/sumw);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#define _smoothInstances     1
#define _smoothInstancesSize 10
double  _smthWork[][_smoothInstances*_smoothInstancesSize];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iSmooth(double price, double length, double phase, int r, int bars, int instanceNo=0)
{
   if (ArrayRange(_smthWork,0)!=bars) ArrayResize(_smthWork,bars); instanceNo*=_smoothInstancesSize; r = bars-r-1;
   if (price==EMPTY_VALUE) price=0;

   if (r==0 || length<=1){ int k=0; for(; k<volty; k++) _smthWork[0][instanceNo+k]=price; for(; k<_smoothInstancesSize; k++) _smthWork[0][instanceNo+k]=0; return(price); }

      //
      //
      //
      //
      //
  
      double len1   = fmax(log(sqrt(0.5*(length-1)))/log(2.0)+2.0,0);
      double pow1   = fmax(len1-2.0,0.5);
      double del1   = price - _smthWork[r-1][instanceNo+bsmax],absDel1 = fabs(del1);
      double del2   = price - _smthWork[r-1][instanceNo+bsmin],absDel2 = fabs(del2);
      int    forBar = (int)fmin(r,10);
      
         _smthWork[r][instanceNo+volty]  = (absDel1 > absDel2) ? absDel1 : (absDel1 < absDel2) ? absDel2 : 0;
         _smthWork[r][instanceNo+vsum]   = _smthWork[r-1][instanceNo+vsum] + (_smthWork[r][instanceNo+volty]-_smthWork[r-forBar][instanceNo+volty])*0.1;
         _smthWork[r][instanceNo+avolty] = _smthWork[r-1][instanceNo+avolty]+(2.0/(fmax(4.0*length,30)+1.0))*(_smthWork[r][instanceNo+vsum]-_smthWork[r-1][instanceNo+avolty]);
        
         //
         //
         //
         //
         //
              
         double dVolty    = (_smthWork[r][instanceNo+avolty]>0) ? _smthWork[r][instanceNo+volty]/_smthWork[r][instanceNo+avolty] : 0;  
         double dVoltyTmp = pow(len1,1.0/pow1);
         if (dVolty > dVoltyTmp) dVolty = dVoltyTmp;
         if (dVolty < 1.0)       dVolty = 1.0;
         
         //
         //
         //
         //
         //
        
         double pow2 = pow(dVolty, pow1);
         double len2 = sqrt(0.5*(length-1))*len1;
         double Kv   = pow(len2/(len2+1),sqrt(pow2));

            _smthWork[r][instanceNo+bsmax] = (del1>0) ? price : price - Kv*del1;
            _smthWork[r][instanceNo+bsmin] = (del2<0) ? price : price - Kv*del2;
             
      //
      //
      //
      //
      //
      
      double corr  = fmax(fmin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = pow(beta,pow2);

         _smthWork[r][instanceNo+0] = price + alpha*(_smthWork[r-1][instanceNo+0]-price);
         _smthWork[r][instanceNo+1] = (price - _smthWork[r][instanceNo+0])*(1-beta) + beta*_smthWork[r-1][instanceNo+1];
         _smthWork[r][instanceNo+2] = (_smthWork[r][instanceNo+0]   + corr*_smthWork[r][instanceNo+1]);
         _smthWork[r][instanceNo+3] = (_smthWork[r][instanceNo+2]   - _smthWork[r-1][instanceNo+4])*((1-alpha)*(1-alpha)) + (alpha*alpha)*_smthWork[r-1][instanceNo+3];
         _smthWork[r][instanceNo+4] = (_smthWork[r-1][instanceNo+4] + _smthWork[r][instanceNo+3]);
  return(_smthWork[r][instanceNo+4]);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//

double workCci[][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(int 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);
}


//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
// 
//
//
//
//

#define _devInstances 1
double workDev[][_devInstances];
double iDeviation(double value, int length, bool isSample, int i, int bars, int instanceNo=0)
{
   if (ArrayRange(workDev,0)!=bars) ArrayResize(workDev,bars); i=bars-i-1; workDev[i][instanceNo] = value;
                 
   //
   //
   //
   //
   //
   
      double oldMean   = value;
      double newMean   = value;
      double squares   = 0; int k;
      for (k=1; k<length && (i-k)>=0; k++)
      {
         newMean  = (workDev[i-k][instanceNo]-oldMean)/(k+1)+oldMean;
         squares += (workDev[i-k][instanceNo]-oldMean)*(workDev[i-k][instanceNo]-newMean);
         oldMean  = newMean;
      }
      return(sqrt(squares/fmax(k-isSample,1)));
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     1
#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) ? (open[i+1]+close[i+1])*0.5 : (open[i]+close[i])*0.5;
         double haClose = (open[i]+high[i]+low[i]+close[i])*0.25;
         if (_prHABF(tprice))
               if (high[i]!=low[i])
                     haClose = (open[i]+close[i])/2.0+(((close[i]-open[i])/(high[i]-low[i]))*fabs((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("");
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar]== 1) doAlert(whichBar,"trend changed to up");
         if (trend[whichBar]==-1) doAlert(whichBar,"trend changed to down");
      }
   }
}

//
//
//
//
//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message = timeFrameToString(_Period)+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" cci adaptive smoother "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," cci adaptive smoother "),message);
          if (alertsNotify)  SendNotification(message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}


