//+------------------------------------------------------------------+
//|                                        wpr + bollinger bands.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  DeepSkyBlue
#property indicator_color2  Snow
#property indicator_color3  DarkOrange
#property indicator_color4  Snow
#property indicator_style2  STYLE_DASH
#property indicator_style3  STYLE_DASH
#property indicator_style4  STYLE_DASH
#property indicator_width1  4
#property indicator_levelstyle STYLE_DOT
#property indicator_levelcolor Magenta

//
//
//
//
//

extern string TimeFrame        = "Current time frame";
extern int    CCIPeriod        = 50;
extern int    CCIPrice         = PRICE_TYPICAL;
extern double OverSold         = -200;
extern double OverBought       = 200;
extern int    SmoothLength     = 14;
extern double SmoothPhase      = 0;
extern int    BandsPeriod      = 50;
extern double BandsDeviations  = 2; 
extern bool   Interpolate      = true;

extern string  __              = "arrows settings";
extern bool   ShowArrows       = true; 
extern string ArrowsIdentifier = "cciba";
extern color  ArrowUpColor     = Aqua;
extern color  ArrowDownColor   = Red; 
extern int    ArrowUpWidth     = 1; 
extern int    ArrowDownWidth   = 1; 


extern string  _               = "alerts settings";
extern bool    alertsOn        = true;
extern bool    alertsOnCurrent = true;
extern bool    alertsMessage   = true;
extern bool    alertsSound     = false;
extern bool    alertsEmail     = false;

//
//
//
//
//

double cci[];
double bandsUp[];
double bandsMi[];
double bandsDo[];
double prices[];
double trend[];
double atrend[];

string IndicatorFileName;
bool   Calculatingcci;
bool   ReturningBars;
int    timeFrame;

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

int init()
{
   IndicatorBuffers(7);
   SetIndexBuffer(0,cci);
   SetIndexBuffer(1,bandsUp);
   SetIndexBuffer(2,bandsMi);
   SetIndexBuffer(3,bandsDo);
   SetIndexBuffer(4,prices);
   SetIndexBuffer(5,trend);
   SetIndexBuffer(6,atrend);
   SetLevelValue(0,OverBought);
   SetLevelValue(1,OverSold);
   

   //
   //
   //
   //
   //
   
      IndicatorFileName   = WindowExpertName();
      Calculatingcci      = (TimeFrame=="Calculatingcci"); if (Calculatingcci) return(0);
      ReturningBars       = (TimeFrame=="returnBars");   if (ReturningBars)  return(0);
      timeFrame           = stringToTimeFrame(TimeFrame);
         
   //
   //
   //
   //
   //
               
   IndicatorShortName(" Cci with bands "+timeFrameToString(timeFrame)+" ("+CCIPeriod+","+BandsPeriod+","+DoubleToStr(BandsDeviations,2)+")");
   return(0);
}

int deinit()
{
   if (ShowArrows)
   {
      int compareLength = StringLen(ArrowsIdentifier);
      for (int i=ObjectsTotal(); i>= 0; i--)
      {
         string name = ObjectName(i);
            if (StringSubstr(name,0,compareLength) == ArrowsIdentifier)
                ObjectDelete(name);  
      }
   }
   return(0);
}




int start()
{
   int counted_bars=IndicatorCounted();
   int i,k,limit;
   
   if(counted_bars < 0) return(-1);
   if(counted_bars > 0) counted_bars--;
           limit = MathMin(Bars-counted_bars,Bars-1);
           if (ReturningBars)  { cci[0] = limit+1; return(0); }

   
 
      if (Calculatingcci || timeFrame==Period())
      {
          
      for(i=limit; i>=0; i--)
      {
      prices[i]  = iSmooth(iMA(NULL,0,1,0,MODE_SMA,CCIPrice,i),SmoothLength,SmoothPhase,i);
      double avg = 0; for(k=0; k<CCIPeriod; k++) avg +=         prices[i+k];      avg /= CCIPeriod;
      double dev = 0; for(k=0; k<CCIPeriod; k++) dev += MathAbs(prices[i+k]-avg); dev /= CCIPeriod;
      if (dev!=0)
      cci[i] = (prices[i]-avg)/(0.015*dev);
      else  cci[i] = 0;  
      }
      for(i=limit; i>=0; i--)
      {
      double deviations = iStdDevOnArray(cci,0,BandsPeriod,0,MODE_LWMA,i);
      bandsMi[i] = iMAOnArray(cci,0,BandsPeriod,0,MODE_LWMA,i);
      bandsUp[i] = bandsMi[i]+deviations*BandsDeviations;
      bandsDo[i] = bandsMi[i]-deviations*BandsDeviations;
      
      trend[i] = trend[i+1];
      if (cci[i] < bandsDo[i] && cci[i+1] >= bandsDo[i+1] ) trend[i] =  1;
      if (cci[i] > bandsUp[i] && cci[i+1] <= bandsUp[i+1] ) trend[i] = -1;  
      manageArrow(i);  
     }
     manageAlerts();
     return(0);
   }

   
      limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,IndicatorFileName,"","returnBars",0,0)*timeFrame/Period()));
      for(i=limit; i>=0; i--)
      {
            int y      = iBarShift(NULL,timeFrame,Time[i]);
            cci[i]     = iCustom(NULL,timeFrame,IndicatorFileName,"Calculatingcci",CCIPeriod,CCIPrice,OverSold,OverBought,SmoothLength,SmoothPhase,BandsPeriod,BandsDeviations,0,y);
            bandsUp[i] = iCustom(NULL,timeFrame,IndicatorFileName,"Calculatingcci",CCIPeriod,CCIPrice,OverSold,OverBought,SmoothLength,SmoothPhase,BandsPeriod,BandsDeviations,1,y);
            bandsMi[i] = iCustom(NULL,timeFrame,IndicatorFileName,"Calculatingcci",CCIPeriod,CCIPrice,OverSold,OverBought,SmoothLength,SmoothPhase,BandsPeriod,BandsDeviations,2,y);
            bandsDo[i] = iCustom(NULL,timeFrame,IndicatorFileName,"Calculatingcci",CCIPeriod,CCIPrice,OverSold,OverBought,SmoothLength,SmoothPhase,BandsPeriod,BandsDeviations,3,y);
            prices[i]  = iCustom(NULL,timeFrame,IndicatorFileName,"Calculatingcci",CCIPeriod,CCIPrice,OverSold,OverBought,SmoothLength,SmoothPhase,BandsPeriod,BandsDeviations,4,y);
            trend[i]   = iCustom(NULL,timeFrame,IndicatorFileName,"Calculatingcci",CCIPeriod,CCIPrice,OverSold,OverBought,SmoothLength,SmoothPhase,BandsPeriod,BandsDeviations,5,y);
            manageArrow(i);
         
         if (timeFrame <= Period() || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
         if (!Interpolate) continue;

         

         datetime time = iTime(NULL,timeFrame,y);
         for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
         double factor = 1.0 / n;
         for(int j = 1; j < n; j++)
         {
  	      cci[i+j]     = j*factor*cci[i+n]     + (1.0-j*factor)*cci[i];
  	      bandsUp[i+j] = j*factor*bandsUp[i+n] + (1.0-j*factor)*bandsUp[i];
  	      bandsMi[i+j] = j*factor*bandsMi[i+n] + (1.0-j*factor)*bandsMi[i];
  	      bandsDo[i+j] = j*factor*bandsDo[i+n] + (1.0-j*factor)*bandsDo[i];
  	      prices[i+j]  = j*factor*prices[i+n]  + (1.0-j*factor)*prices[i];
        }  	            
   }
      
   
   manageAlerts();   
   return(0);
}



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

void manageArrow(int i)
{
   if (ShowArrows && !Calculatingcci)
   {
      double dist = iATR(NULL,0,20,i)/2.0;
      ObjectDelete(ArrowsIdentifier+Time[0]);         
            
      //
      //
      //
      //
      //
           
      atrend[i] = atrend[i+1];
         if (cci[i] < bandsDo[i] && cci[i+1] >= bandsDo[i+1] ) atrend[i] =  1;
         if (cci[i] > bandsUp[i] && cci[i+1] <= bandsUp[i+1] ) atrend[i] = -1;
         if (atrend[i] !=atrend[i+1])
         {
            string name = ArrowsIdentifier+Time[i];
            if (atrend[i] == 1)
            {
               ObjectCreate(name,OBJ_ARROW,0, Time[i],Low[i]-dist );
                  ObjectSet(name,OBJPROP_ARROWCODE,241);
                  ObjectSet(name,OBJPROP_COLOR,ArrowUpColor);
                  ObjectSet(name,OBJPROP_WIDTH,ArrowUpWidth);
            }
            else
            {
               ObjectCreate(name,OBJ_ARROW,0, Time[i],High[i]+dist );
                  ObjectSet(name,OBJPROP_ARROWCODE,242);
                  ObjectSet(name,OBJPROP_COLOR,ArrowDownColor);
                  ObjectSet(name,OBJPROP_WIDTH,ArrowDownWidth);
            }
         }
   }
}



void manageAlerts()
{
   if (!Calculatingcci && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] == 1) doAlert(whichBar,"buy");
         if (trend[whichBar] ==-1) doAlert(whichBar,"sell");
      }         
   }
}   

//
//
//
//
//

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 =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," - ",timeFrameToString(timeFrame)+" Cci bands on jurik trend changed to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Cci bands on jurik "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

double wrk[][10];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iSmooth(double price, double length, double phase, int i)
{
   if (ArrayRange(wrk,0) != Bars) ArrayResize(wrk,Bars);
   
   int r = Bars-i-1; 
      if (r==0) { for(int k=0; k<7; k++) wrk[0][k]=price; for(; k<10; k++) wrk[0][k]=0; return(price); }

   //
   //
   //
   //
   //
   
      double len1   = MathMax(MathLog(MathSqrt(0.5*(length-1)))/MathLog(2.0)+2.0,0);
      double pow1   = MathMax(len1-2.0,0.5);
      double del1   = price - wrk[r-1][bsmax];
      double del2   = price - wrk[r-1][bsmin];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = MathMin(r,10);
	
         wrk[r][volty] = 0;
               if(MathAbs(del1) > MathAbs(del2)) wrk[r][volty] = MathAbs(del1); 
               if(MathAbs(del1) < MathAbs(del2)) wrk[r][volty] = MathAbs(del2); 
         wrk[r][vsum] =	wrk[r-1][vsum] + (wrk[r][volty]-wrk[r-forBar][volty])*div;
   
         //
         //
         //
         //
         //
   
         wrk[r][avolty] = wrk[r-1][avolty]+(2.0/(MathMax(4.0*length,30)+1.0))*(wrk[r][vsum]-wrk[r-1][avolty]);
            if (wrk[r][avolty] > 0)
               double dVolty = wrk[r][volty]/wrk[r][avolty]; else dVolty = 0;   
	               if (dVolty > MathPow(len1,1.0/pow1)) dVolty = MathPow(len1,1.0/pow1);
                  if (dVolty < 1)                      dVolty = 1.0;

      //
      //
      //
      //
      //
	        
   	double pow2 = MathPow(dVolty, pow1);
      double len2 = MathSqrt(0.5*(length-1))*len1;
      double Kv   = MathPow(len2/(len2+1), MathSqrt(pow2));

         if (del1 > 0) wrk[r][bsmax] = price; else wrk[r][bsmax] = price - Kv*del1;
         if (del2 < 0) wrk[r][bsmin] = price; else wrk[r][bsmin] = price - Kv*del2;
	
   //
   //
   //
   //
   //
      
      double R     = MathMax(MathMin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = MathPow(beta,pow2);

         wrk[r][0] = price + alpha*(wrk[r-1][0]-price);
         wrk[r][1] = (price - wrk[r][0])*(1-beta) + beta*wrk[r-1][1];
         wrk[r][2] = (wrk[r][0] + R*wrk[r][1]);
         wrk[r][3] = (wrk[r][2] - wrk[r-1][4])*MathPow((1-alpha),2) + MathPow(alpha,2)*wrk[r-1][3];
         wrk[r][4] = (wrk[r-1][4] + wrk[r][3]); 

   //
   //
   //
   //
   //

   return(wrk[r][4]);
}


