ta.crossover in MQL5: the exact two-bar test, with na handling
Short answer
MQL5 has no built-in. Write a[i] > b[i] && a[i-1] <= b[i-1] on oldest-first arrays, and return false when any of the four values is missing.
ta.crossover(source1, source2) returns true on the bar where source1 moves above source2: strictly greater now, and less than or equal one bar earlier. MQL5 has no built-in for it; the equivalent is a two-bar comparison you write yourself, and the only things that can go wrong are the index direction and what you do with missing values.
What ta.crossover computes
On every bar Pine evaluates source1 > source2 and source1[1] <= source2[1]. Both halves matter: the strict inequality on the current bar means a touch that ends exactly equal is not a cross yet, and the non-strict inequality on the previous bar means a bar that was exactly equal and then moves above does count. The function returns a bool, never na: if any of the four values is na (the first bar of the chart, or a moving average that has not warmed up), the result is false. A crossover is therefore impossible on bar 0 and on the first bar after an average becomes defined.
Because it compares two series, both arguments must have a history. In Pine that is automatic. In MQL5 a value you computed into a plain double variable has no previous bar, so each operand needs an array: an indicator buffer, an array filled by CopyBuffer, or a price array passed into OnCalculate.
The MQL5 equivalent
Pine first. The script marks the bar where a 9-period EMA crosses above a 21-period EMA.
//@version=6
indicator("EMA crossover", overlay=true)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
up = ta.crossover(fast, slow)
plot(fast, "Fast")
plot(slow, "Slow")
plotshape(up, "Crossover", shape.triangleup, location.belowbar)The MQL5 indicator reads both averages through iMA handles into buffers and applies the same test. The arrays stay in the default OnCalculate order, oldest first, so "the previous bar" is i - 1.
//+------------------------------------------------------------------+
//| EMA crossover marker: Pine's ta.crossover(fast, slow) in MQL5 |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 3
#property indicator_label1 "Fast EMA"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_label2 "Slow EMA"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrOrange
#property indicator_label3 "Crossover"
#property indicator_type3 DRAW_ARROW
#property indicator_color3 clrLime
#property indicator_width3 2
input int FastLen = 9;
input int SlowLen = 21;
double Fast[], Slow[], Up[];
int hFast, hSlow;
// ta.crossover(a, b): a is above b now and was not above it one bar earlier.
// Arrays are oldest-first here, so "one bar earlier" is i - 1.
// Any missing value on either bar gives false, as na does in Pine.
bool Crossover(const double &a[], const double &b[], const int i)
{
if(i < 1) return false;
if(a[i] == EMPTY_VALUE || b[i] == EMPTY_VALUE ||
a[i - 1] == EMPTY_VALUE || b[i - 1] == EMPTY_VALUE) return false;
return a[i] > b[i] && a[i - 1] <= b[i - 1];
}
int OnInit()
{
SetIndexBuffer(0, Fast, INDICATOR_DATA);
SetIndexBuffer(1, Slow, INDICATOR_DATA);
SetIndexBuffer(2, Up, INDICATOR_DATA);
PlotIndexSetInteger(2, PLOT_ARROW, 233);
PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);
hFast = iMA(_Symbol, _Period, FastLen, 0, MODE_EMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, SlowLen, 0, MODE_EMA, PRICE_CLOSE);
return (hFast != INVALID_HANDLE && hSlow != INVALID_HANDLE) ? INIT_SUCCEEDED : INIT_FAILED;
}
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, Fast) != rates_total) return 0;
if(CopyBuffer(hSlow, 0, 0, rates_total, Slow) != rates_total) return 0;
int start = (prev_calculated > 1) ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
// Skip the bars where the slow average is not seeded yet (Pine: na).
if(i < SlowLen - 1) { Up[i] = EMPTY_VALUE; continue; }
Up[i] = Crossover(Fast, Slow, i) ? low[i] : EMPTY_VALUE;
}
return rates_total;
}Crossover() is the whole translation. Everything else is plumbing to give both operands a history.
Where the two differ
| Topic | Pine Script | MQL5 |
|---|---|---|
| Previous bar | x[1] | x[i - 1] with oldest-first arrays; x[i + 1] (or x[1] for the last closed bar) after ArraySetAsSeries(x, true) |
| Missing values | na in any operand gives false | Nothing is automatic: test for EMPTY_VALUE (or whatever your buffers hold before warm-up) and return false |
| Warm-up | An EMA is na for its first length - 1 bars | iMA buffers hold placeholder values on those bars; skip them explicitly |
| Realtime bar | Recomputed on every tick; the cross can appear and disappear until the bar closes | The same if you evaluate the forming bar (index rates_total - 1); test the last closed bar for a signal that cannot un-fire |
| Return type | bool | bool; store it in a buffer as a price (arrow) or 1/0 |
What the Stratlate converter emits
The engine maps ta.crossover to the runtime helper pine_crossover(a, b, bar), which implements the test above including the four-value na check (PineRuntime.mqh). When an operand is a computed value rather than a named series, as in ta.crossover(ta.ema(close, 9), ta.ema(close, 21)), the emitter either materialises it into a per-script array or switches to pine_crossover_step, which records both values per bar in that call site's own state buffers and runs the same comparison. A shifted cross, ta.crossover(fast[n], slow[n]) with the same offset on both sides, becomes pine_crossover(fast, slow, bar - n). The mapping is exact and is not reported as an approximation.
Pitfalls
- Testing
a > balone. Symptom: the signal fires on every bar the fast line is above the slow line, not just the first. - Using
>=on the current bar or<on the previous bar. Symptom: extra or missing signals on bars where the two lines are exactly equal, typically on rounded prices or flat markets. - Mixing index directions. With series arrays (
ArraySetAsSeries(true)) the previous bar isi + 1; with oldest-first arrays it isi - 1. Symptom: signals one bar late, or a cross that fires one bar before it is visible. - Comparing values before the averages are seeded. Symptom: a spurious crossover on the first bars of the chart where TradingView shows nothing.
- Alerting on the forming bar. Symptom: an alert that fires, then the cross vanishes when the bar closes. Evaluate the last closed bar for alerts and orders.
FAQ
Is there an MQL5 function equivalent to ta.crossover?
No. MQL5 has no cross detector in its standard library; the comparison a[i] > b[i] && a[i - 1] <= b[i - 1] on two arrays is the equivalent, plus a guard for values that are not yet defined.
Why does my converted crossover fire one bar later than on TradingView?
Usually the test runs on the last closed bar (index 1 in series order) while TradingView draws it on the realtime bar. Both are correct; the TradingView one can still disappear before the bar closes, the MQL5 one cannot.
Can ta.crossover return na?
No. It returns a bool, and any na among the four compared values makes it false. In MQL5 you reproduce that by returning false when either array holds EMPTY_VALUE on the current or previous bar.
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 converterRelated
- ta.crossunder in MQL5: closed-bar test in an Expert Advisor
- ta.cross in MQL5: either-direction cross as a sign change
- ta.ema in MQL5: iMA MODE_EMA, seeding and the first bars
- Pine close[1] vs MQL5 arrays: indexing and ArraySetAsSeries
- Convert Pine Script to MQL5 — online TradingView to MT5 converter