alert() in MQL5: once per bar and once per bar close

Short answer

Pine's alert() becomes MQL5's Alert(), or SendNotification() for the mobile app. MQL5 leaves the frequency to you: freq_once_per_bar and freq_once_per_bar_close become a guard keyed on the bar's open time, and not firing on history becomes a check on prev_calculated.

alert() raises an alert event from inside a script, with a message built at run time and a frequency chosen in code. Unlike alertcondition(), the text can include computed values and the call can sit inside any if block. MQL5's Alert() is the direct counterpart: it shows a pop-up with sound in the terminal and accepts several arguments that it joins into one message. The part MQL5 leaves to you is the frequency: alert.freq_once_per_bar and alert.freq_once_per_bar_close become a small guard keyed on the bar's open time, and "do not fire on history" becomes a check on prev_calculated.

What alert() computes

alert(message, freq) takes a series string message and one of three frequencies. alert.freq_once_per_bar (the default) delivers the first call made during a realtime bar and ignores further calls in that bar. alert.freq_once_per_bar_close delivers only calls made on the tick that closes the bar, so the condition is judged on the final values. alert.freq_all delivers every call, on every tick. Nothing happens on historical bars, and nothing happens at all until the user creates an alert on the script with the "Any alert() function call" condition. The function works in indicators and strategies, inside local blocks and loops, which is why it is the usual way to send messages that contain prices or indicator values.

The MQL5 equivalent

The Pine version alerts once per bar close when RSI leaves oversold, and once per bar when RSI is above 70.

//@version=6
indicator("Alert demo", overlay=false)
r = ta.rsi(close, 14)
plot(r, "RSI")
if ta.crossover(r, 30)
    alert("RSI left oversold: " + str.tostring(r, "#.##"), alert.freq_once_per_bar_close)
if r > 70
    alert("RSI overbought", alert.freq_once_per_bar)

In an MQL5 indicator both frequencies run in OnCalculate after the history pass. "Once per bar close" is evaluated when a new bar appears and tests the bar that just closed (rates_total - 2), which is exactly the moment TradingView's close-of-bar alert fires. "Once per bar" tests the forming bar on each tick and remembers which bar it already reported. Alert() joins its arguments, so the value can be passed separately.

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "RSI"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrPurple

input int InpLength = 14;   // RSI length

double BufRsi[];
int    hRsi;

int OnInit()
{
   SetIndexBuffer(0, BufRsi, INDICATOR_DATA);
   hRsi = iRSI(_Symbol, _Period, InpLength, PRICE_CLOSE);
   return hRsi == INVALID_HANDLE ? INIT_FAILED : 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[])
{
   if(BarsCalculated(hRsi) < rates_total || rates_total < 3)
      return 0;
   if(CopyBuffer(hRsi, 0, 0, rates_total, BufRsi) < 0)
      return 0;
   int live = rates_total - 1, done = rates_total - 2;
   static datetime closeAlerted = 0, barAlerted = 0;
   if(prev_calculated == 0)
     {
      closeAlerted = time[live];          // alert() never fires on historical bars
      return rates_total;
     }

   // alert(..., alert.freq_once_per_bar_close): evaluate the bar that just closed, once
   if(time[live] != closeAlerted)
     {
      closeAlerted = time[live];
      if(BufRsi[done] > 30.0 && BufRsi[done - 1] <= 30.0)
         Alert("RSI left oversold: ", DoubleToString(BufRsi[done], 2));
     }
   // alert(..., alert.freq_once_per_bar): the forming bar, first tick that meets the test
   if(BufRsi[live] > 70.0 && time[live] != barAlerted)
     {
      barAlerted = time[live];
      Alert("RSI overbought");
     }
   return rates_total;
}

The same logic in an Expert Advisor lives in OnTick(). The common pattern is a new-bar check on iTime(_Symbol, _Period, 0), after which index 1 of a series-ordered array is the bar that just closed. That gives "once per bar close" by construction; an EA that wants intrabar alerts drops the new-bar return and keeps a time guard instead.

// An Expert Advisor: alerts from OnTick on each newly closed bar
input int  InpLength = 14;     // RSI length
input bool InpPush   = false;  // Also send a push notification

int      hRsi;
datetime lastBar = 0;

int OnInit()
{
   hRsi = iRSI(_Symbol, _Period, InpLength, PRICE_CLOSE);
   return hRsi == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED;
}

void OnTick()
{
   datetime bar = iTime(_Symbol, _Period, 0);
   if(bar == lastBar)
      return;                          // still the same bar: once per bar close
   lastBar = bar;
   double r[];
   ArraySetAsSeries(r, true);          // r[0] = forming bar, r[1] = just closed
   if(CopyBuffer(hRsi, 0, 0, 3, r) != 3)
     {
      lastBar = 0;                     // data not ready: try again next tick
      return;
     }
   if(r[1] > 30.0 && r[2] <= 30.0)
     {
      string msg = _Symbol + ": RSI left oversold at " + DoubleToString(r[1], 2);
      Alert(msg);
      if(InpPush)
         SendNotification(msg);
     }
}
Pine frequencyMQL5 pattern
alert.freq_once_per_barTest the forming bar on each call; fire when time[live] differs from the stored time
alert.freq_once_per_bar_closeWhen a new bar starts, test the previous bar once
alert.freq_allTest and fire on every tick, no guard

Where the two differ

TopicPine ScriptMQL5
ActivationUser must create an "Any alert() function call" alertFires as soon as the code calls it
HistoryIgnored automaticallySkip the prev_calculated == 0 pass yourself
Close-of-bar timingOn the closing tick of the barOn the first tick of the next bar; the same values, a tick later
Where it runsTradingView serversThe local terminal, which must be running
MessageOne stringAlert() takes up to 64 arguments of any type and joins them
Other channelsApp, email, webhook chosen in the dialogSendNotification, SendMail, WebRequest in code
Strategy TesterAlerts do not fire in backtestsAlert prints to the journal; notifications and mail are skipped

What the Stratlate converter emits

Every alert(message, freq) becomes pine_alert(message, freq, site, bar, lastBar), with the frequency coded 0 for freq_once_per_bar, 1 for freq_once_per_bar_close and 2 for freq_all (BuiltinMapping.java). The runtime helper in PineRuntime.mqh returns immediately during the first OnCalculate pass, so loading history is silent. With frequency 0 it fires on the live bar once per call site per bar; with 1 it fires only for a bar that has closed (in an indicator, when the loop re-evaluates the previous bar on the new bar's first tick), once per site per bar; with 2 it fires on every evaluation of the live bar. In an EA every evaluation is a closed bar, so both 0 and 1 act as "once per bar close" there. Messages built with str.tostring are converted to DoubleToString and delivered with Alert(); push notifications and webhooks are not generated. The example converts CLEAN; compile it and watch the alerts on a live chart or in a visual tester run.

Pitfalls

  • Testing rates_total - 1 for a close-of-bar alert. That is the bar that just opened, with one tick of data; the condition is judged on the wrong bar.
  • Initialising the close-of-bar guard to 0. On the first realtime tick the code evaluates the last historical bar and fires an old signal; store the current bar time during the history pass.
  • Putting the alert inside the per-bar loop with no guard. A tick that re-runs the last two bars can alert twice.
  • Expecting alert.freq_all to be harmless. On a busy symbol it means dozens of pop-ups a minute in MetaTrader as well.
  • Calling SendNotification on every tick. The terminal limits the rate and drops the excess, so the important message may be the one that is lost.
  • Assuming an EA's alerts run when the terminal is closed. They only run while the EA is attached and the terminal is online.

FAQ

What is the difference between alert() and alertcondition() in MQL5 terms?

None at the MQL5 end: both become code that calls Alert(). The difference is on the Pine side, where alertcondition lets the user choose the frequency in a dialog and alert fixes it in code. See the alertcondition page for the declaration form.

How do I include indicator values in the message?

Pass them as extra arguments, Alert("RSI ", DoubleToString(r, 2)), or build one string with StringFormat("RSI %.2f on %s", r, _Symbol). Use _Digits for prices so the number of decimals matches the symbol.

Can MQL5 send a webhook like TradingView alerts?

Yes, with WebRequest(), after adding the URL under Tools, Options, Expert Advisors, "Allow WebRequest for listed URL". It works in EAs and scripts but not in indicators, so an indicator that should post to a webhook needs a small EA to read its buffers and send the request.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related