Pine alertcondition() and alert() in MetaTrader 5

Short answer

A Pine alertcondition() or alert() runs on TradingView's servers once you create an alert in its dialog; in MetaTrader 5 an alert is a function call in your MQL5 code, running in your terminal. It works only while the terminal is open and the program attached, for example on a VPS.

TradingView alerts and MetaTrader alerts look similar but work in different places. A Pine Script alertcondition() or alert() does nothing until you create an alert in TradingView's dialog, and then it runs on TradingView's servers. In MetaTrader 5, an alert is a function call in your MQL5 code that runs in your terminal. This guide is for developers converting an indicator or strategy whose alerts matter, and shows how to reproduce each Pine alert type without flooding the screen with popups.

What MetaTrader offers

  • Alert(...) opens the terminal's alert window with a sound. It takes up to 64 comma-separated values, like Print.
  • PlaySound("alert.wav") plays a sound file from the terminal's Sounds folder, without a window.
  • SendNotification(text) sends a push message to the MetaTrader mobile app. The user must enter their MetaQuotes ID under Tools > Options > Notifications. Messages are limited to 255 characters, and MetaTrader restricts how often the function may be called (at most 2 calls per second and 10 per minute).
  • SendMail(subject, text) sends email through the SMTP server set under Tools > Options > Email.
  • WebRequest can post to a webhook, but only from an Expert Advisor or script, not from an indicator, and only to URLs the user has allowed under Tools > Options > Expert Advisors.

All of these run only while the terminal is open and the program is attached to a chart. A TradingView alert keeps working when your browser is closed; the MetaTrader equivalent needs the terminal running, for example on a VPS.

The Pine example

This indicator declares an alertcondition for a moving-average cross and also calls alert() when the bar closes with a cross.

//@version=6
indicator("MA cross alerts", overlay = true)
fast = ta.sma(close, 9)
slow = ta.sma(close, 21)
plot(fast, "Fast", color.blue)
plot(slow, "Slow", color.orange)
up = ta.crossover(fast, slow)
alertcondition(up, "Bullish cross", "Fast SMA crossed above slow on {{ticker}}")
if up
    alert("Bullish cross at " + str.tostring(close), alert.freq_once_per_bar_close)

alert() and its frequency

Pine's alert() takes a frequency that decides how often a true condition fires:

  • alert.freq_once_per_bar (the default): the first time the call runs on the live bar, then not again until the next bar.
  • alert.freq_once_per_bar_close: only when the live bar closes and the call ran on its final tick.
  • alert.freq_all: every time the call runs, which on the live bar means every tick.

In MQL5 you build the frequency yourself, normally by remembering the bar time you last alerted on. Once per bar close means looking at the bar that has just closed, rates_total - 2 in an oldest-first array, the first time OnCalculate runs on the new bar:

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

input int  InpFast   = 9;     // Fast length
input int  InpSlow   = 21;    // Slow length
input bool InpPush   = false; // Also send push notification

double Fast[], Slow[];

double Sma(const double &src[], const int i, const int len)
{
   double s = 0.0;
   for(int k = 0; k < len; k++) s += src[i - k];
   return s / len;
}

int OnInit()
{
   SetIndexBuffer(0, Fast, INDICATOR_DATA);
   SetIndexBuffer(1, Slow, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   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 need = MathMax(InpFast, InpSlow);
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      Fast[i] = Slow[i] = EMPTY_VALUE;
      if(i < need - 1) continue;
      Fast[i] = Sma(close, i, InpFast);
      Slow[i] = Sma(close, i, InpSlow);
   }

   // alert.freq_once_per_bar_close: check the bar that just closed, once.
   static datetime lastAlerted = 0;
   int b = rates_total - 2;                       // last closed bar
   if(prev_calculated > 0 && b >= need && time[b] != lastAlerted)
   {
      lastAlerted = time[b];                      // evaluate each closed bar once
      bool up = Fast[b] > Slow[b] && Fast[b - 1] <= Slow[b - 1];  // ta.crossover
      if(up)
      {
         string msg = "Bullish cross on " + _Symbol + " at "
                      + DoubleToString(close[b], _Digits);
         Alert(msg);
         if(InpPush) SendNotification(msg);
      }
   }
   return rates_total;
}

Two guards do the work. prev_calculated > 0 skips the first call, when MetaTrader calculates the whole history; Pine never fires alerts on historical bars, and without the guard every past cross pops up when the indicator loads. The lastAlerted time makes sure each closed bar is checked once, however many ticks arrive. The message is built from _Symbol and DoubleToString, because TradingView's placeholders such as {{ticker}}, {{close}} and {{interval}} are filled in by TradingView's alert system; MetaTrader prints the braces literally.

For the default once-per-bar frequency, check the live bar instead and remember its time:

// alert.freq_once_per_bar (the default): first tick of the live bar where the
// condition is true, at most once per bar. Inside OnCalculate:
static datetime firedOn = 0;
int last = rates_total - 1;
if(prev_calculated > 0 && condition && time[last] != firedOn)
{
   firedOn = time[last];
   Alert("Condition met on ", _Symbol, " ", EnumToString(_Period));
}

For alert.freq_all, drop the time check, and expect an alert on every tick while the condition holds.

alertcondition()

alertcondition() has no MetaTrader counterpart, because it is not an action: it only adds an entry to TradingView's "Create alert" dialog. You have two reasonable conversions. If the user wanted the alert, fire it in code, live and once per bar, which is one of the frequencies TradingView's dialog offers and the most common choice. If the condition is meant to drive something else, write it into a buffer (1 when true, 0 otherwise) so an Expert Advisor can read it with iCustom and CopyBuffer; that is the closest MetaTrader gets to "other things can subscribe to this condition".

Alerts in strategies and Expert Advisors

A Pine strategy can send order-fill alerts, with alert_message on strategy.entry and strategy.exit. In an Expert Advisor, place the Alert or SendNotification call next to the trade request, after checking the result of OrderSend or CTrade, so you only announce orders that were accepted. An EA that evaluates its logic once per new bar naturally gets once-per-bar-close behaviour. In the Strategy Tester no alert window opens and no notifications or emails are sent, so test alert logic on a demo chart.

What Stratlate does with alerts

The converter maps alert() to a runtime call that respects the Pine frequency: once per bar on the live bar, once per bar close when a bar has closed, or on every evaluation of the live bar for freq_all, with each call site tracked separately. No alert fires during the first calculation over history. alertcondition() is converted to fire live and once per bar when its condition is true; the condition itself is still evaluated as before. The alert text is the Pine message expression, so check any TradingView placeholders in it. Compile the result and watch it on a demo chart before relying on it for trading.

Pitfalls

  • Alerting during the history pass. Symptom: dozens of popups as soon as the indicator is attached or the chart reloads.
  • No per-bar memory. Symptom: the same alert repeats on every tick until the bar closes.
  • Checking the live bar for a close-confirmed signal. Symptom: alerts for crosses that disappear before the bar closes, which TradingView's once-per-bar-close alert would never have sent.
  • Calling SendNotification too often. Symptom: messages silently dropped and an error in the Experts log.
  • Using WebRequest in an indicator. Symptom: the call fails; move webhook posting into an Expert Advisor.
  • Placeholders left in the text. Symptom: messages that read "crossed above slow on {{ticker}}".
  • Terminal closed. Symptom: no alerts overnight. MetaTrader alerts need a running terminal.

FAQ

Does MetaTrader 5 have alertcondition()?

No. alertcondition() only adds an entry to TradingView's alert dialog. In MQL5 either fire Alert() in code when the condition is true, once per bar, or write the condition to a buffer for an Expert Advisor to read.

Why do I get many alerts when I attach a converted indicator?

The code alerts during the first calculation over history. Skip alerts when prev_calculated is 0, as Pine never fires alerts on historical bars.

Do MetaTrader alerts work when the terminal is closed?

No. Alert, SendNotification and SendMail run inside the terminal, so it must be running with the program attached, for example on a VPS.

Convert alerts with the rest of the script

Paste a Pine indicator or strategy; the converter keeps its alert() and alertcondition() calls firing on live bars only, at the frequency the script asked for.

Open the converter

Related guides