//+------------------------------------------------------------------+
//|                                                      CCI nrp.mq4 |
//+------------------------------------------------------------------+
#property copyright "www,forex-station.com"
#property link      "www,forex-station.com"

#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1  clrDimGray
#property indicator_color2  clrDeepSkyBlue
#property indicator_color3  clrRed
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_minimum 0
#property indicator_maximum 1

//
//
//
//
//

extern string TimeFrame              = "current time frame";
extern int    CCIPeriod              = 14;
extern ENUM_APPLIED_PRICE CCIPrice   = PRICE_TYPICAL;
extern double OverSold               = -100;
extern double OverBought             =  100;
extern color  OverSoldColor          = clrRed; 
extern color  OverBoughtColor        = clrDeepSkyBlue; 
extern bool   alertsOn               = true;
extern bool   alertsOnZoneEnter      = true;
extern bool   alertsOnZoneExit       = true;
extern bool   alertsOnEveryBreak     = true;
extern bool   alertsOnCurrent        = false;
extern bool   alertsMessage          = true;
extern bool   alertsSound            = true;
extern bool   alertsEmail            = false;
extern bool   alertsNotify           = false;

//
//
//
//
//

double cci[];
double cciNe[];
double cciUp[];
double cciDn[];
double prices[];
double trend[];

//
//
//
//
//

string indicatorFileName;
bool   calculateValue;
bool   returnBars;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(6);
      SetIndexBuffer(0,cciNe); SetIndexStyle(0,DRAW_HISTOGRAM);
      SetIndexBuffer(1,cciUp); SetIndexStyle(1,DRAW_HISTOGRAM);
      SetIndexBuffer(2,cciDn); SetIndexStyle(2,DRAW_HISTOGRAM);
      SetIndexBuffer(3,prices);
      SetIndexBuffer(4,trend);
      SetIndexBuffer(5,cci);

         //
         //
         //
         //
         //
                  
         indicatorFileName = WindowExpertName();
         calculateValue    = (TimeFrame=="CalculateValue"); if (calculateValue) return(0);
         returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
         
         //
         //
         //
         //
         //
         
   IndicatorShortName(timeFrameToString(timeFrame)+" CCI ("+CCIPeriod+")");
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//

int start()
{
   int k,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { cci[0] = limit+1; return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame==Period())
   {
      for(int i=limit; i>=0; i--)
      {
         prices[i]  = iMA(NULL,0,1,0,MODE_SMA,CCIPrice,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;
         
            //
            //
            //
            //
            //
         
            cciUp[i] = EMPTY_VALUE;
            cciDn[i] = EMPTY_VALUE;
            cciNe[i] = EMPTY_VALUE;
            trend[i] = trend[i+1];
               if (cci[i]>OverBought)                                          trend[i] =  1;
               if (cci[i]<OverSold)                                            trend[i] = -1;
               if (alertsOnEveryBreak && cci[i]>OverSold && cci[i]<OverBought) trend[i]= 0;
               if (trend[i] ==  1) cciUp[i] = 1;
               if (trend[i] == -1) cciDn[i] = 1;
               if (trend[i] ==  0) cciNe[i] = 1;
      }
      if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (alertsOnZoneEnter && trend[whichBar]   ==  1) doAlert(whichBar,DoubleToStr(OverBought,2)+" entering overbought");
         if (alertsOnZoneEnter && trend[whichBar]   == -1) doAlert(whichBar,DoubleToStr(OverSold,2) +" entering oversold");
         if (alertsOnZoneExit  && trend[whichBar+1] == -1) doAlert(whichBar,DoubleToStr(OverSold,2) +" exiting oversold");
         if (alertsOnZoneExit  && trend[whichBar+1] ==  1) doAlert(whichBar,DoubleToStr(OverBought,2)+" exiting overbought");
      }
   }
      return(0);
   }      
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for (i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         cciNe[i]  = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",CCIPeriod,CCIPrice,OverSold,OverBought,0,y);
         cciUp[i]  = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",CCIPeriod,CCIPrice,OverSold,OverBought,1,y);
         cciDn[i]  = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",CCIPeriod,CCIPrice,OverSold,OverBought,2,y);
   }

   //
   //
   //
   //
   //
   
   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 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);
}

//
//
//
//
//

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()," ",timeFrameToString(Period())," at ",TimeToStr(TimeLocal(),TIME_SECONDS),"CCI ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"CCI"),message);
          if (alertsSound)   PlaySound("alert2.wav");
          if (alertsNotify)  SendNotification(message);
   }
}
