Pine gives you two clean ways to draw Heikin-Ashi: pull the pre-built HA series with
ticker.heikinashi, or compute the candles yourself and draw them with plotcandle.
Both are short. See the explainer.
What you’ll need
- A TradingView account (free tier is fine)
- The Pine Editor
The built-in way
//@version=5
indicator("AlgoGen Heikin-Ashi", overlay=true)
haTicker = ticker.heikinashi(syminfo.tickerid)
haO = request.security(haTicker, timeframe.period, open)
haH = request.security(haTicker, timeframe.period, high)
haL = request.security(haTicker, timeframe.period, low)
haC = request.security(haTicker, timeframe.period, close)
col = haC >= haO ? #0ca30c : #d03b3b
plotcandle(haO, haH, haL, haC, "HA", color=col, wickcolor=col, bordercolor=col)
ticker.heikinashi transforms the current symbol into its Heikin-Ashi form, and
request.security pulls the transformed OHLC. plotcandle draws them — the smoothed
candles from the output chart.
From scratch
If you want the math explicit (and no request.security):
//@version=5
indicator("AlgoGen Heikin-Ashi (manual)", overlay=true)
haClose = (open + high + low + close) / 4
var float haOpen = na
haOpen := na(haOpen[1]) ? (open + close) / 2 : (haOpen[1] + haClose[1]) / 2
haHigh = math.max(high, math.max(haOpen, haClose))
haLow = math.min(low, math.min(haOpen, haClose))
col = haClose >= haOpen ? #0ca30c : #d03b3b
plotcandle(haOpen, haHigh, haLow, haClose, color=col, wickcolor=col, bordercolor=col)
The var float haOpen plus the haOpen[1] self-reference is how Pine expresses the
recursive open: on the first bar (na(haOpen[1])) it seeds with (open + close) / 2,
and thereafter it averages its own previous value with the previous haClose.
Which to use
The built-in ticker.heikinashi is the safest — it’s the exact series TradingView shows
when you switch chart type to Heikin-Ashi, so it’ll match perfectly. The manual version
is for when you want to compute on HA values (e.g. an HA-based moving average) inside
one script without repeated request.security calls.
Gotchas
var+[1]for the open. That’s Pine’s recursive-series idiom; a plainhaOpen[1]withoutvarwon’t carry correctly on the first bar.- Seed with
(open + close) / 2. Guarded byna(haOpen[1])for bar 0. request.securitycan repaint on lower timeframes if misused; for same-timeframe HA it’s fine, but prefer the manual version if you’re nesting timeframes.- HA prices are averages — don’t wire them into
strategy.entrylimit prices as if they were real levels.
Same candles elsewhere: Python, MQL5, EasyLanguage, NinjaScript. Then test a Heikin-Ashi rule 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)
