ta.supertrend in MQL5: bands, ATR and the direction sign
Short answer
MetaTrader 5 has no SuperTrend, so write it by hand: hl2 plus or minus factor times Wilder's ATR, with bands that ratchet and need their own buffers. Direction is -1 in an uptrend and +1 in a downtrend.
ta.supertrend(factor, atrPeriod) returns a tuple [supertrend, direction]: a trailing line built from hl2 plus or minus factor times the ATR, and a direction flag. The sign convention catches almost everyone: direction is -1 in an uptrend (the line is below price) and +1 in a downtrend. MetaTrader 5 has no built-in SuperTrend, so the MQL5 equivalent is written by hand. It is about forty lines, and because the bands depend on their own previous values, each one needs a buffer.
What ta.supertrend computes
With atr = ta.atr(atrPeriod) (Wilder's average of the true range, seeded with the SMA of the first atrPeriod values) and src = hl2:
upper = src + factor * atr,lower = src - factor * atr- The lower band only rises: it keeps
lower[1]unless the new value is higher or the previous close fell belowlower[1]. The upper band only falls, by the mirror rule. A missing previous band counts as 0 (nz). - Direction: 1 if
atr[1]isna; otherwise, if the previous SuperTrend was the upper band, -1 whenclosebreaks above the upper band, else 1; if it was the lower band, 1 whenclosebreaks below the lower band, else -1. supertrend = direction == -1 ? lower : upper
The line is na until the ATR has a value, at bar atrPeriod - 1. The direction test uses the current close, so on the realtime bar the trend can flip and flip back before the bar closes.
The MQL5 equivalent
Pine first: two plots split by direction, the usual way to colour the line.
//@version=6
indicator("Supertrend ref", overlay=true)
[st, dir] = ta.supertrend(3.0, 10)
plot(dir < 0 ? st : na, "Up", color=color.green, style=plot.style_linebr)
plot(dir > 0 ? st : na, "Down", color=color.red, style=plot.style_linebr)In MQL5 a single DRAW_COLOR_LINE with a colour-index buffer does the same job. The ATR, both bands and the direction live in calculation buffers so the forming bar is recomputed from the previous bar on every tick. DirBuf keeps Pine's sign, so code ported from the script (dir < 0 means long) reads the same.
//+------------------------------------------------------------------+
//| SuperTrend matching [st, dir] = ta.supertrend(factor, atrPeriod) |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 7
#property indicator_plots 1
#property indicator_label1 "SuperTrend"
#property indicator_type1 DRAW_COLOR_LINE
#property indicator_color1 clrGreen, clrRed
#property indicator_width1 2
input double InpFactor = 3.0; // Factor
input int InpAtr = 10; // ATR period
double StBuf[], StColor[], DirBuf[], UpBuf[], LoBuf[], AtrBuf[], TrBuf[];
int OnInit()
{
SetIndexBuffer(0, StBuf, INDICATOR_DATA);
SetIndexBuffer(1, StColor, INDICATOR_COLOR_INDEX);
SetIndexBuffer(2, DirBuf, INDICATOR_CALCULATIONS); // -1 up, +1 down (Pine's sign)
SetIndexBuffer(3, UpBuf, INDICATOR_CALCULATIONS);
SetIndexBuffer(4, LoBuf, INDICATOR_CALCULATIONS);
SetIndexBuffer(5, AtrBuf, INDICATOR_CALCULATIONS);
SetIndexBuffer(6, TrBuf, INDICATOR_CALCULATIONS);
PlotIndexSetDouble(0, 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[])
{
const int n = InpAtr;
int start = prev_calculated > 1 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
// ta.atr: true range (high - low on bar 0), Wilder average seeded with an SMA
TrBuf[i] = i == 0 ? high[i] - low[i]
: MathMax(high[i] - low[i], MathMax(MathAbs(high[i] - close[i - 1]),
MathAbs(low[i] - close[i - 1])));
if(i < n - 1) AtrBuf[i] = EMPTY_VALUE;
else if(i == n - 1)
{
double s = 0.0;
for(int k = 0; k < n; k++) s += TrBuf[i - k];
AtrBuf[i] = s / n;
}
else AtrBuf[i] = (AtrBuf[i - 1] * (n - 1) + TrBuf[i]) / n;
if(AtrBuf[i] == EMPTY_VALUE) // no ATR yet: bands and SuperTrend are na
{
UpBuf[i] = EMPTY_VALUE; LoBuf[i] = EMPTY_VALUE;
StBuf[i] = EMPTY_VALUE; DirBuf[i] = 1.0; StColor[i] = 1;
continue;
}
const double mid = (high[i] + low[i]) / 2.0; // hl2
double up = mid + InpFactor * AtrBuf[i];
double lo = mid - InpFactor * AtrBuf[i];
const double prevUp = UpBuf[i - 1] == EMPTY_VALUE ? 0.0 : UpBuf[i - 1]; // nz(upper[1])
const double prevLo = LoBuf[i - 1] == EMPTY_VALUE ? 0.0 : LoBuf[i - 1];
// a band only ratchets toward price, unless the previous close broke it
lo = (lo > prevLo || close[i - 1] < prevLo) ? lo : prevLo;
up = (up < prevUp || close[i - 1] > prevUp) ? up : prevUp;
UpBuf[i] = up; LoBuf[i] = lo;
double dir;
if(AtrBuf[i - 1] == EMPTY_VALUE) dir = 1.0; // na(atr[1])
else if(StBuf[i - 1] == prevUp) dir = close[i] > up ? -1.0 : 1.0;
else dir = close[i] < lo ? 1.0 : -1.0;
DirBuf[i] = dir;
StBuf[i] = dir < 0 ? lo : up; // -1: uptrend, line below price
StColor[i] = dir < 0 ? 0 : 1; // 0 = green, 1 = red
}
return rates_total;
}The colour line connects the last up bar and the first down bar with a segment in the new colour. If you want gaps at the flips, as Pine's plot.style_linebr plots draw them, use two DRAW_LINE plots and write EMPTY_VALUE into the one that is not active.
Where the two differ
| Aspect | Pine ta.supertrend | MQL5 |
|---|---|---|
| Built-in | Yes, returns a tuple | None; several buffers by hand |
| Direction sign | -1 uptrend, +1 downtrend | Whatever you choose; keep Pine's to avoid inverting signals |
| ATR | ta.atr, Wilder smoothing | iATR is a simple average of the true range, not Wilder; compute it yourself |
| Source | Fixed hl2 | (high + low) / 2 |
| Missing previous band | nz() gives 0 | Must be handled explicitly |
| Colouring | Two plots or a colour expression | DRAW_COLOR_LINE plus a colour-index buffer |
The ATR row decides whether the lines match. Building the bands on iATR gives the right shape but different band distances after volatility changes, and band breaks, therefore trend flips, move by a bar or more. Wilder's ATR with an SMA seed, as in the code above, reproduces ta.atr from its first value.
What the Stratlate converter emits
The lowering pass rewrites [st, dir] = ta.supertrend(f, n) into two runtime calls that share one state id: pine_supertrend(...) for the line and pine_supertrend_dir(...) for the direction. Both fill the same per-bar buffers (ATR state, true range, upper band, lower band, line, direction) and the fill is idempotent, so reading the value and the direction on the same bar is safe. The ATR comes from pine_atr_hlc, Wilder's average of the true range, and the band and direction rules are transcribed from Pine's reference definition, including the nz of the previous band and Pine's sign convention. The mapping is reported as exact; the test script above converts CLEAN. Compile the output and backtest it before trading on it. For a full walk-through of the indicator on both platforms see the SuperTrend indicator page.
Pitfalls
- Reading
dir == 1as "up". In Pine it means down. An EA that buys ondir == 1trades every trend backwards. - Using
iATR. The bands sit at different distances and flips come on different bars than on TradingView. - Ratcheting the bands with the current close instead of the previous one. The line flips a bar early and the rules contradict each other on gap bars.
- Comparing the previous SuperTrend with the previous upper band using a tolerance or after rounding. The rule relies on exact equality of the stored values; keep them in
doublebuffers and compare directly. - Storing bands in
static doublevariables. On the forming bar each tick ratchets the band again from its own updated value and the line creeps toward price. - Trading the flip on the forming bar. It can reverse before the close; read the last closed bar in an EA unless the Pine strategy used
calc_on_every_tick.
FAQ
What does direction -1 mean in ta.supertrend?
An uptrend. When direction is -1 the SuperTrend line is the lower band, below price; when it is +1 the line is the upper band, above price. The sign is the opposite of what most people expect, so keep it unchanged when porting conditions.
Is there a SuperTrend indicator built into MetaTrader 5?
No. MetaTrader 5 has no SuperTrend function or standard indicator. Write it as on this page, or load a custom one with iCustom after checking that its ATR uses Wilder smoothing and its bands ratchet the same way.
Why do my SuperTrend flips differ from TradingView by a bar?
The usual cause is the ATR: MetaTrader's iATR averages the true range with a simple moving average, while ta.atr uses Wilder smoothing. Different band distances move the breakout bar. Check also that both charts start far enough back for the ATR to converge.
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