//+------------------------------------------------------------------+
//|                                                momentum-alert.mq4 |
//|  Plots Momentum in a separate window and alerts when it crosses   |
//|  its 100 centerline.                                              |
//|  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

extern int    MomentumPeriod = 14;
extern int    AppliedPrice   = PRICE_CLOSE;
extern bool   EnableAlert    = true;
extern bool   EnablePush     = false;

double MomentumBuffer[];

int lastSignal = 0; // 0 = none, 1 = above 100, -1 = below 100

int OnInit()
{
   SetIndexBuffer(0, MomentumBuffer);
   SetIndexStyle(0, DRAW_LINE);
   SetIndexLabel(0, "Momentum (" + IntegerToString(MomentumPeriod) + ")");

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

   for (int i = start; i >= 0; i--)
      MomentumBuffer[i] = iMomentum(NULL, 0, MomentumPeriod, AppliedPrice, i);

   CheckCrossSignal();
   return(rates_total);
}

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

   double momPrev = iMomentum(NULL, 0, MomentumPeriod, AppliedPrice, 2);
   double momLast = iMomentum(NULL, 0, MomentumPeriod, AppliedPrice, 1);

   int signal = 0;
   if (momPrev <= 100 && momLast > 100)
      signal = 1;  // crossed above 100
   else if (momPrev >= 100 && momLast < 100)
      signal = -1; // crossed below 100

   if (signal != 0 && signal != lastSignal)
   {
      string msg = (signal == 1)
         ? Symbol() + " " + EnumToString((ENUM_TIMEFRAMES)Period()) + ": Momentum crossed above 100"
         : Symbol() + " " + EnumToString((ENUM_TIMEFRAMES)Period()) + ": Momentum crossed below 100";

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

      lastSignal = signal;
   }
}
