SuperTrend spread largely through TradingView, and Pine has ta.supertrend built
in — so the canonical version is a few lines. See
the explainer for the logic.
What you’ll need
- A TradingView account (free tier is fine)
- The Pine Editor
The source
//@version=5
indicator("AlgoGen SuperTrend", shorttitle="AG ST", overlay=true)
atrLen = input.int(10, "ATR length")
factor = input.float(3.0, "Multiplier")
[supertrend, direction] = ta.supertrend(factor, atrLen)
// direction: -1 = uptrend (line below price), +1 = downtrend (line above).
upColor = color.new(#0ca30c, 0)
dnColor = color.new(#d03b3b, 0)
plot(supertrend, "SuperTrend", color = direction < 0 ? upColor : dnColor,
style=plot.style_linebr, linewidth=2)
flipUp = direction < 0 and direction[1] > 0
flipDn = direction > 0 and direction[1] < 0
plotshape(flipUp, "Flip up", shape.triangleup, location.belowbar, color=upColor, size=size.small)
plotshape(flipDn, "Flip down", shape.triangledown, location.abovebar, color=dnColor, size=size.small)
alertcondition(flipUp or flipDn, "SuperTrend flip", "SuperTrend changed direction")
ta.supertrend(factor, atrLen) returns the line and a direction value. Note
Pine’s convention: direction < 0 is the uptrend (line below price). We colour
the line green/red accordingly and mark the flips — matching the output chart.
From scratch
ta.supertrend does the band-locking for you; if you want to see it, the manual
version mirrors the Python post using ta.atr, hl2, and
var variables to carry the final bands bar to bar. For production, the built-in is
correct and concise.
A filtered strategy
SuperTrend flips too often in ranges, so gating the flips on a higher-timeframe SuperTrend (or a trend filter) is a popular fix:
//@version=5
strategy("AlgoGen SuperTrend System", overlay=true)
[st, dir] = ta.supertrend(3.0, 10)
htfDir = request.security(syminfo.tickerid, "D", ta.supertrend(3.0, 10)[1],
lookahead=barmerge.lookahead_off)
if dir < 0 and dir[1] > 0 and htfDir < 0 // flip up, daily also up
strategy.entry("Long", strategy.long)
if dir > 0 and dir[1] < 0
strategy.close("Long")
Only take the intraday flip when the daily SuperTrend agrees — the multi-timeframe
approach that cuts a lot of the whipsaw. (Keep lookahead_off to avoid future
leakage.)
Gotchas
- Direction sign. Pine’s
ta.supertrendreturnsdirection = -1for up and+1for down — the opposite of what many expect. Colour and signal off that, not your assumption. plot.style_linebr. Using a break style avoids drawing a connecting line across the flip (which would slash through price).- Range whipsaw. Expect frequent flips in sideways markets; gate with a trend filter if it hurts.
Same indicator elsewhere: Python, MQL5, EasyLanguage, NinjaScript. Then test a SuperTrend system in AlgoGen.
This post is educational, not financial advice. Indicators describe the past; they don’t predict the future. Backtest anything before you risk real money on it.
Sources and further reading
- Pine Script built-ins (TradingView)
