//+------------------------------------------------------------------+
//|                                                 cci-alert.mq4     |
//|  Plots CCI in a separate window and alerts on overbought/oversold |
//|  Source: web-forex (educational, free to use and modify)          |
//+------------------------------------------------------------------+
#property copyright "web-forex"
#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 clrDodgerBlue
#property indicator_level1 -100
#property indicator_level2 0
#property indicator_level3 100

extern int    CCIPeriod    = 14;
extern int    AppliedPrice = PRICE_TYPICAL;
extern double Overbought   = 100.0;
extern double Oversold     = -100.0;
extern bool   EnableAlert  = true;
extern bool   EnablePush   = false;

double CCIBuffer[];

int lastZone = 0; // 0 = neutral, 1 = overbought, -1 = oversold

int OnInit()
{
   SetIndexBuffer(0, CCIBuffer);
   SetIndexStyle(0, DRAW_LINE);
   SetIndexLabel(0, "CCI (" + IntegerToString(CCIPeriod) + ")");

   IndicatorShortName("CCI Alert (" + IntegerToString(CCIPeriod) + ")");
   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 start = rates_total - prev_calculated;
   if (start > rates_total - CCIPeriod - 1)
      start = rates_total - CCIPeriod - 1;
   if (start < 0)
      return(rates_total);

   for (int i = start; i >= 0; i--)
      CCIBuffer[i] = iCCI(NULL, 0, CCIPeriod, AppliedPrice, i);

   CheckZoneSignal();
   return(rates_total);
}

void CheckZoneSignal()
{
   if (!EnableAlert && !EnablePush)
      return;

   double cciLast = iCCI(NULL, 0, CCIPeriod, AppliedPrice, 1);

   int zone = 0;
   if (cciLast >= Overbought)
      zone = 1;
   else if (cciLast <= Oversold)
      zone = -1;

   if (zone != 0 && zone != lastZone)
   {
      string msg = (zone == 1)
         ? Symbol() + " " + EnumToString((ENUM_TIMEFRAMES)Period()) + ": CCI Overbought (" + DoubleToString(cciLast, 1) + ")"
         : Symbol() + " " + EnumToString((ENUM_TIMEFRAMES)Period()) + ": CCI Oversold (" + DoubleToString(cciLast, 1) + ")";

      if (EnableAlert)
         Alert(msg);
      if (EnablePush)
         SendNotification(msg);
   }

   if (zone != 0)
      lastZone = zone;
   else if (cciLast > Oversold + 20 && cciLast < Overbought - 20)
      lastZone = 0;
}
