//+------------------------------------------------------------------+
//|                                                     obv-alert.mq4 |
//|  Plots On-Balance Volume in a separate window and alerts when OBV |
//|  crosses its own signal moving average.                          |
//|  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

extern int    AppliedPrice  = PRICE_CLOSE;
extern int    SignalPeriod  = 20;
extern bool   EnableAlert   = true;
extern bool   EnablePush    = false;

double OBVBuffer[];

int lastSignal = 0; // 0 = none, 1 = OBV above its SMA, -1 = OBV below its SMA

int OnInit()
{
   SetIndexBuffer(0, OBVBuffer);
   SetIndexStyle(0, DRAW_LINE);
   SetIndexLabel(0, "OBV");

   IndicatorShortName("OBV Alert");
   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 - SignalPeriod - 1)
      start = rates_total - SignalPeriod - 1;
   if (start < 0)
      return(rates_total);

   for (int i = start; i >= 0; i--)
      OBVBuffer[i] = iOBV(NULL, 0, AppliedPrice, i);

   CheckCrossSignal();
   return(rates_total);
}

double CalcObvSma(int startShift, int period)
{
   double sum = 0;
   for (int i = startShift; i < startShift + period; i++)
      sum += iOBV(NULL, 0, AppliedPrice, i);
   return(sum / period);
}

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

   double obvPrev = iOBV(NULL, 0, AppliedPrice, 2);
   double obvLast = iOBV(NULL, 0, AppliedPrice, 1);
   double smaPrev = CalcObvSma(3, SignalPeriod);
   double smaLast = CalcObvSma(2, SignalPeriod);

   int signal = 0;
   if (obvPrev <= smaPrev && obvLast > smaLast)
      signal = 1;  // OBV crossed above its own SMA
   else if (obvPrev >= smaPrev && obvLast < smaLast)
      signal = -1; // OBV crossed below its own SMA

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

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

      lastSignal = signal;
   }
}
