ta.crossunder in MQL5: closed-bar test in an Expert Advisor

Short answer

Write a[i] < b[i] && a[i-1] >= b[i-1] in an indicator. In an Expert Advisor reading series-indexed arrays from CopyBuffer, test the closed bar: a[1] < b[1] && a[2] >= b[2].

ta.crossunder(source1, source2) is the mirror of ta.crossover: true on the bar where source1 drops below source2, meaning strictly less now and greater than or equal one bar earlier. In MQL5 it is the comparison a[i] < b[i] && a[i - 1] >= b[i - 1], and in an Expert Advisor that reads indicator values through CopyBuffer the same test is usually written on series-indexed arrays as a[1] < b[1] && a[2] >= b[2].

What ta.crossunder computes

Per bar: source1 < source2 and source1[1] >= source2[1]. The current-bar inequality is strict; the previous-bar one is not. The result is a bool, so a na in any of the four values yields false, never na. If source1 sits exactly on source2 for several bars and then falls below, the crossunder fires on the bar it falls below, once.

In a Pine strategy the condition is typically evaluated once per bar on bar close (calc_on_every_tick=false is the default), so an order placed on a crossunder uses the values of the bar that just completed. That is the behaviour to reproduce in an EA, which is why the example below tests the last closed bar rather than the forming one.

The MQL5 equivalent

Pine: an EMA crossunder that raises an alert.

//@version=6
indicator("EMA crossunder alert", overlay=true)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
down = ta.crossunder(fast, slow)
plot(fast, "Fast")
plot(slow, "Slow")
alertcondition(down, "Crossunder", "Fast EMA crossed under slow EMA")

MQL5, as an Expert Advisor. CopyBuffer fills three values, the arrays are switched to series order so index 0 is the forming bar, and the crossunder is tested on bars 1 and 2, the last two closed bars. The check runs once per bar, on the first tick after a new bar opens.

//+------------------------------------------------------------------+
//| EMA crossunder alert EA: Pine's ta.crossunder(fast, slow) in MQL5 |
//+------------------------------------------------------------------+
#property version "1.00"

input int FastLen = 9;
input int SlowLen = 21;

int      hFast, hSlow;
datetime lastBar = 0;

// ta.crossunder(a, b) on series-indexed arrays (0 = forming bar):
// a is below b on the last closed bar and was not below it on the bar before.
bool CrossunderClosed(const double &a[], const double &b[])
{
   return a[1] < b[1] && a[2] >= b[2];
}

int OnInit()
{
   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;
}

void OnTick()
{
   // Evaluate once per bar, on the first tick of a new bar, like a Pine
   // strategy with calc_on_every_tick=false.
   datetime bar = iTime(_Symbol, _Period, 0);
   if(bar == lastBar) return;
   lastBar = bar;

   double fast[], slow[];
   ArraySetAsSeries(fast, true);
   ArraySetAsSeries(slow, true);
   if(CopyBuffer(hFast, 0, 0, 3, fast) < 3) return;
   if(CopyBuffer(hSlow, 0, 0, 3, slow) < 3) return;
   if(BarsCalculated(hSlow) < SlowLen + 2) return;   // not enough history yet

   if(CrossunderClosed(fast, slow))
      Alert(_Symbol, " ", EnumToString(_Period), ": fast EMA crossed under slow EMA");
}

If you want the signal inside an indicator instead, use the oldest-first form from the ta.crossover page with the inequalities flipped: a[i] < b[i] && a[i - 1] >= b[i - 1].

Where the two differ

TopicPine ScriptMQL5
Which bar is "now"The realtime bar inside an indicator; the just-closed bar in a strategy evaluated on closeYour choice: index rates_total - 1 (oldest-first) or [0] (series) is the forming bar; [1] in series order is the last closed bar
Previous barx[1]x[2] when "now" is x[1] in series order
naGives falseGuard before comparing; CopyBuffer can also return fewer values than asked, which must abort the test
FrequencyOnce per bar (strategy default) or every tickOnTick runs on every tick; gate it with a new-bar check
Alertalertcondition is wired up in the UIAlert(), SendNotification() or an order fire directly from code

What the Stratlate converter emits

ta.crossunder maps to pine_crossunder(a, b, bar) in the runtime, which returns false when any of the four compared values is na and otherwise evaluates a[i] < b[i] && a[i-1] >= b[i-1] on oldest-first arrays. Computed operands go through pine_crossunder_step, which stores both values per bar in call-site state buffers so the previous bar is available. The emitted program evaluates the Pine script bar by bar inside OnCalculate (indicators) or on each bar for strategies, so the "which bar" question is decided by the original script's settings, not by the translation. The mapping is exact.

Pitfalls

  • Forgetting ArraySetAsSeries(arr, true) after CopyBuffer. Symptom: the test reads the wrong two bars because index 0 is then the oldest of the copied values.
  • Testing bars 0 and 1 in an EA. Symptom: the signal appears mid-bar, trades are opened, then the bar closes above the line and the "crossunder" never existed.
  • Not gating OnTick on a new bar. Symptom: the same crossunder is acted on dozens of times within one bar.
  • Ignoring the return value of CopyBuffer. Symptom: random false signals right after the EA starts, when the indicator has not finished calculating.
  • Using <= on the current bar. Symptom: an extra signal on bars where the lines are exactly equal.

FAQ

Why does the EA test bars 1 and 2 instead of 0 and 1?

Bar 0 is still forming and its values change with every tick, so a cross seen there can disappear. Bars 1 and 2 are closed, so the result is final and matches a Pine strategy evaluated on bar close.

Does ta.crossunder fire when the two lines are exactly equal?

Not on the equal bar. The current-bar comparison is strict; it fires on the first bar where source1 is strictly below source2, provided it was greater than or equal one bar earlier.

Can I use the same code for an indicator buffer instead of CopyBuffer?

Yes, but keep the index direction straight. Indicator buffers in OnCalculate are oldest-first by default, so the previous bar is i - 1 there, while the series arrays in the EA above use i + 1.

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