//+------------------------------------------------------------------+
//|                                             force-index-alert.mq4 |
//|  Plots Elder's Force Index in a separate window and alerts when    |
//|  it crosses its zero line.                                         |
//|  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 0

extern int    ForcePeriod  = 13;
extern int    MAMethod     = MODE_EMA;    // 0=SMA, 1=EMA, 2=SMMA, 3=LWMA
extern int    AppliedPrice = PRICE_CLOSE;
extern bool   EnableAlert  = true;
extern bool   EnablePush   = false;

double ForceBuffer[];

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

int OnInit()
{
   SetIndexBuffer(0, ForceBuffer);
   SetIndexStyle(0, DRAW_LINE);
   SetIndexLabel(0, "Force Index (" + IntegerToString(ForcePeriod) + ")");

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

   for (int i = start; i >= 0; i--)
      ForceBuffer[i] = iForce(NULL, 0, ForcePeriod, MAMethod, AppliedPrice, i);

   CheckCrossSignal();
   return(rates_total);
}

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

   double forcePrev = iForce(NULL, 0, ForcePeriod, MAMethod, AppliedPrice, 2);
   double forceLast = iForce(NULL, 0, ForcePeriod, MAMethod, AppliedPrice, 1);

   int signal = 0;
   if (forcePrev <= 0 && forceLast > 0)
      signal = 1;  // crossed above zero
   else if (forcePrev >= 0 && forceLast < 0)
      signal = -1; // crossed below zero

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

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

      lastSignal = signal;
   }
}
