//+------------------------------------------------------------------+
//|                                                     mfi-alert.mq4 |
//|  Plots the Money Flow Index 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_minimum 0
#property indicator_maximum 100
#property indicator_level1 20
#property indicator_level2 80

extern int    MFIPeriod    = 14;
extern double Overbought   = 80.0;
extern double Oversold     = 20.0;
extern bool   EnableAlert  = true;
extern bool   EnablePush   = false;

double MFIBuffer[];

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

int OnInit()
{
   SetIndexBuffer(0, MFIBuffer);
   SetIndexStyle(0, DRAW_LINE);
   SetIndexLabel(0, "MFI (" + IntegerToString(MFIPeriod) + ")");

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

   for (int i = start; i >= 0; i--)
      MFIBuffer[i] = iMFI(NULL, 0, MFIPeriod, i);

   CheckZoneSignal();
   return(rates_total);
}

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

   double mfiLast = iMFI(NULL, 0, MFIPeriod, 1);

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

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

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

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