alertcondition() in MQL5: Alert() on a confirmed bar, once

Short answer

MQL5 has no direct equivalent: alertcondition() only registers a condition for TradingView's alert dialog. In MetaTrader the indicator calls Alert(), SendNotification() or SendMail() itself from OnCalculate, evaluating the closed bar and firing once per bar.

alertcondition() does not send anything by itself. It registers a named condition that a TradingView user can later pick in the "Create alert" dialog, together with the frequency (once per bar, once per bar close, once only). MetaTrader has no such registry: an indicator that wants to notify someone calls Alert() (a pop-up with sound in the terminal), SendNotification() (a push message to the MetaTrader mobile app) or SendMail() itself, from OnCalculate. So the conversion turns a declaration into code, and that code has to do what TradingView's alert engine did for you: evaluate the right bar, fire once per bar, and stay silent while history loads.

What alertcondition() computes

alertcondition(condition, title, message) is evaluated on every bar but has no visible effect and returns nothing. condition is a series bool; title names the entry in the alert dialog; message is the default text, which may contain placeholders such as {{close}}, {{ticker}} or {{plot_0}} that TradingView substitutes when the alert fires. It must be called at global scope. Once the user creates an alert from it, TradingView's servers evaluate the script on realtime bars only. With "Once per bar" (the default) the alert fires the first time the condition is true during a bar, even if the bar later closes with the condition false; with "Once per bar close" it is checked only when the bar closes, which is the setting that matches what you see on historical bars.

The MQL5 equivalent

The Pine version declares two crossover conditions.

//@version=6
indicator("Alertcondition demo", overlay=true)
f = ta.ema(close, 9)
s = ta.ema(close, 21)
up = ta.crossover(f, s)
dn = ta.crossunder(f, s)
plot(f, "Fast")
plot(s, "Slow")
alertcondition(up, "Bull cross", "EMA 9 crossed above EMA 21")
alertcondition(dn, "Bear cross", "EMA 9 crossed below EMA 21")

In MQL5 the conditions are computed per bar into calculation buffers (so an EA can read them with iCustom), and the alert is raised in code. The example implements "once per bar close": when a new bar appears it tests the bar that just closed (rates_total - 2), and the static datetime guard makes sure each bar is reported once however many ticks arrive. The first call, with prev_calculated == 0, only records the time, so loading the chart does not open a pop-up for every historical crossover. Inputs switch the pop-up and the push notification on and off, which is the closest thing to choosing alert actions in TradingView's dialog.

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots   2
#property indicator_label1  "Fast"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_label2  "Slow"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrOrange

input int  InpFast   = 9;      // Fast EMA
input int  InpSlow   = 21;     // Slow EMA
input bool InpPopup  = true;   // Pop-up alert
input bool InpPush   = false;  // Push notification to the MetaTrader app

double BufFast[], BufSlow[], BufBull[], BufBear[];
int    hFast, hSlow;

int OnInit()
{
   SetIndexBuffer(0, BufFast, INDICATOR_DATA);
   SetIndexBuffer(1, BufSlow, INDICATOR_DATA);
   // the conditions as data, so an EA can read them with iCustom + CopyBuffer
   SetIndexBuffer(2, BufBull, INDICATOR_CALCULATIONS);
   SetIndexBuffer(3, BufBear, INDICATOR_CALCULATIONS);
   hFast = iMA(_Symbol, _Period, InpFast, 0, MODE_EMA, PRICE_CLOSE);
   hSlow = iMA(_Symbol, _Period, InpSlow, 0, MODE_EMA, PRICE_CLOSE);
   return (hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE) ? INIT_FAILED : INIT_SUCCEEDED;
}

void Notify(const string msg)
{
   string text = _Symbol + " " + EnumToString(_Period) + ": " + msg;
   if(InpPopup) Alert(text);
   if(InpPush)  SendNotification(text);
}

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(hFast) < rates_total || BarsCalculated(hSlow) < rates_total)
      return 0;
   if(CopyBuffer(hFast, 0, 0, rates_total, BufFast) < 0 || CopyBuffer(hSlow, 0, 0, rates_total, BufSlow) < 0)
      return 0;
   int start = MathMax(prev_calculated - 1, 1);
   for(int i = start; i < rates_total; i++)
     {
      BufBull[i] = (BufFast[i] > BufSlow[i] && BufFast[i - 1] <= BufSlow[i - 1]) ? 1.0 : 0.0;
      BufBear[i] = (BufFast[i] < BufSlow[i] && BufFast[i - 1] >= BufSlow[i - 1]) ? 1.0 : 0.0;
     }
   // alertcondition(...) with "Once per bar close": test the bar that just closed,
   // once per new bar, and never while the history is being loaded
   static datetime lastAlerted = 0;
   int closed = rates_total - 2;
   if(prev_calculated == 0)
      lastAlerted = time[rates_total - 1];          // history: remember, do not alert
   else if(closed >= 1 && time[rates_total - 1] != lastAlerted)
     {
      lastAlerted = time[rates_total - 1];
      if(BufBull[closed] > 0.0) Notify("EMA 9 crossed above EMA 21");
      if(BufBear[closed] > 0.0) Notify("EMA 9 crossed below EMA 21");
     }
   return rates_total;
}

To reproduce "Once per bar" instead, test the forming bar (rates_total - 1) on every call and keep the guard: the first tick that meets the condition fires, later ticks in the same bar do not. SendNotification needs a MetaQuotes ID in Tools, Options, Notifications, and is limited by the platform to a few messages per second and a few per minute; Alert has no such limit but only reaches someone sitting at the terminal.

Where the two differ

TopicPine ScriptMQL5
Who decides to alertThe user, in the alert dialogThe code; expose inputs to let the user switch it
Where it runsTradingView's servers, chart closed or notThe user's terminal, which must be running with the chart open
FrequencyChosen per alertWhatever your guard implements
HistoryNever alerts on historical barsOnCalculate runs over all history first; you must skip it
Placeholders{{close}}, {{ticker}} and othersNone; build the string with DoubleToString, _Symbol and so on
DeliveryPop-up, app, email, webhookAlert, SendNotification, SendMail; webhooks need WebRequest and an allowed URL
Strategy TesterNot applicableAlert writes to the tester journal; SendNotification and SendMail do nothing there

What the Stratlate converter emits

Each alertcondition(cond, title, message) becomes a call to the runtime helper pine_alertcond(cond, message, site, bar, lastBar) at the same point in the bar's code, using message as the text and title when there is no message. The helper (PineRuntime.mqh) calls pine_alert with the "once per bar" frequency: it never fires during the first OnCalculate pass over history, fires only on the live bar, and remembers the call site and bar so it fires once per bar. That matches TradingView's default alert setting, which also means it can fire intrabar on a crossover that is gone by the bar's close; in an EA conversion every evaluation is a closed bar, so the same helper behaves as "once per bar close". The text is passed verbatim to Alert(): placeholders like {{close}} are not substituted, and no push notification is sent. The sample converts CLEAN; compile it and watch a live chart to confirm when it fires.

Pitfalls

  • Calling Alert() inside the bar loop without a history check. Loading the chart opens one pop-up per historical signal, which can be hundreds.
  • Testing the forming bar and expecting the alerts to match the arrows on history. Intrabar alerts fire on crossovers that disappear before the close; test rates_total - 2 for confirmed signals.
  • Using a guard keyed only on a boolean. After one alert it never resets; key the guard on time[] of the bar.
  • Leaving {{close}} in the message. MetaTrader prints the braces literally.
  • Relying on the alert while the terminal is closed. Unlike TradingView server-side alerts, nothing runs unless MetaTrader is running; use a VPS for unattended alerts.
  • Forgetting that a timeframe switch or input change restarts the indicator with prev_calculated == 0. That is history again, and must stay silent.

FAQ

Can an EA use my converted indicator's alert conditions?

Yes, if the conditions are stored in buffers as in the example. The EA creates the indicator with iCustom and reads buffers 2 and 3 with CopyBuffer; a value of 1 on the closed bar is the signal. Alerts raised inside an indicator are not visible to an EA.

How do I send the alert to my phone?

Install the MetaTrader 5 mobile app, copy its MetaQuotes ID into the desktop terminal under Tools, Options, Notifications, enable push notifications, and call SendNotification(text). Keep the rate low: the terminal limits how many it will send.

Why does MetaTrader alert once when I attach the indicator?

Usually because the code tests the last closed bar on the first realtime tick and that bar's signal is historical. Record the current bar time during the prev_calculated == 0 pass, as the example does, and the first alert waits for a bar that closes while the indicator is running.

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