ta.cross in MQL5: either-direction cross as a sign change

Short answer

Test for a sign change of d = a - b: (d0 > 0 && d1 <= 0) || (d0 < 0 && d1 >= 0), strict on the current bar and non-strict on the previous one. That equals crossover or crossunder.

ta.cross(source1, source2) is true when the two series cross in either direction on the current bar. It equals ta.crossover(a, b) or ta.crossunder(a, b), and in MQL5 the shortest faithful form is a sign change of the difference a - b between the previous bar and this one, keeping the strict inequality on the current bar and the non-strict one on the previous bar.

What ta.cross computes

With d = source1 - source2, the current bar is a cross when d > 0 and d[1] <= 0 or d < 0 and d[1] >= 0. A bar where d == 0 is never a cross itself; the cross is reported on the next bar that leaves zero, which is what makes the function well defined when a price sits exactly on a moving average for a bar. Like the other two cross functions it returns a bool, and na anywhere in the four values makes it false.

Note that ta.cross(a, b) and ta.cross(b, a) are the same thing, which is not true of crossover and crossunder. If your script later needs the direction, keep the two one-directional tests instead of recovering the direction from the sign of d afterwards.

The MQL5 equivalent

Pine: mark every bar where the close crosses a 20-bar SMA.

//@version=6
indicator("Price / SMA cross", overlay=true)
sma = ta.sma(close, 20)
crossed = ta.cross(close, sma)
plot(sma, "SMA")
plotshape(crossed, "Cross", shape.circle, location.absolute)

MQL5. The SMA is computed by hand so the example has no indicator handle; the cross test is the sign-change form. Arrays are oldest first.

//+------------------------------------------------------------------+
//| Price / SMA cross marker: Pine's ta.cross(close, sma) in MQL5    |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_label1  "SMA"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrOrange
#property indicator_label2  "Cross"
#property indicator_type2   DRAW_ARROW
#property indicator_color2  clrMagenta
#property indicator_width2  2

input int Length = 20;

double Sma[], Cross[];

// ta.cross(a, b): a crossover or a crossunder on this bar. Written as a
// sign change of the difference, which is the same test in one line.
// EMPTY_VALUE stands in for na: any missing value gives false.
bool CrossAt(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;
   double d0 = a[i] - b[i], d1 = a[i - 1] - b[i - 1];
   return (d0 > 0 && d1 <= 0) || (d0 < 0 && d1 >= 0);
}

int OnInit()
{
   SetIndexBuffer(0, Sma,   INDICATOR_DATA);
   SetIndexBuffer(1, Cross, INDICATOR_DATA);
   PlotIndexSetInteger(1, PLOT_ARROW, 159);
   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 start = (prev_calculated > 1) ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      if(i < Length - 1) { Sma[i] = EMPTY_VALUE; Cross[i] = EMPTY_VALUE; continue; }
      double sum = 0.0;
      for(int k = 0; k < Length; k++) sum += close[i - k];
      Sma[i] = sum / Length;
      Cross[i] = CrossAt(close, Sma, i) ? close[i] : EMPTY_VALUE;
   }
   return rates_total;
}

Where the two differ

TopicPine ScriptMQL5
FormulaBuilt inSign change of a - b, or Crossover() || Crossunder()
EqualityA bar with a == b is not a cross; the cross lands on the next bar that moves off equalitySame, provided the current-bar comparison stays strict and the previous-bar one non-strict
naReturns falseReturn false whenever either array holds EMPTY_VALUE on bar i or i - 1
Index direction[1] is the previous bari - 1 oldest-first, i + 1 after ArraySetAsSeries(true)
Realtime barThe cross can flicker on the forming barSame on index rates_total - 1; read bar rates_total - 2 for a final answer

What the Stratlate converter emits

The engine emits pine_cross(a, b, bar), which the runtime defines literally as pine_crossover(a, b, i) || pine_crossunder(a, b, i), so it inherits the na guard and the strict/non-strict pair from those helpers. If one operand is a computed expression rather than a named series, the call site becomes pine_cross_step(x, y, state1, state2, bar), which writes both values into per-call-site state arrays and evaluates the same two tests. In the example above ta.cross(close, sma) converts to pine_cross(close, __ti1, __pineBar) after the SMA value is materialised into an array. The mapping is exact.

Pitfalls

  • Writing d0 * d1 < 0. Symptom: a cross that passes through an exactly-equal bar is never reported, because one of the two products is zero.
  • Writing d0 * d1 <= 0. Symptom: the opposite error; every bar where the lines touch counts as a cross, and a touch without a crossing counts twice.
  • Treating ta.cross as directional. Symptom: logic that reads the sign of a - b after a cross flips when the operands are swapped in a refactor.
  • Comparing a price array against a buffer that has not been filled for early bars. Symptom: a cluster of markers on the first bars of the chart.
  • Computing the SMA on series-ordered arrays with the oldest-first loop. Symptom: the average lags or leads by the window length and the crosses are nonsense.

FAQ

Is ta.cross just crossover OR crossunder?

Yes. Both the Pine definition and the Stratlate runtime define it that way, so the strict current-bar and non-strict previous-bar rules carry over unchanged.

What happens when the two series are exactly equal on a bar?

That bar is not a cross. The next bar that moves strictly above or below is, because the previous-bar comparison is greater-or-equal and less-or-equal.

Does ta.cross return na on the first bar?

No, it returns false. In MQL5 the helper returns false for i less than 1 and for any EMPTY_VALUE among the four compared values.

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