Tutorial

Supertrend in Pine Script: How to Build and Use It

What the Supertrend indicator does, why its ATR-based bands make it popular, and how to build it and a strategy in Pine Script v6.

10 min read

Supertrend is one of the most popular trend-following indicators on TradingView, and its appeal is easy to see the moment you put it on a chart: it draws a single line that sits below price in an uptrend and flips above price in a downtrend, coloring green or red to match. That simplicity hides a genuinely clever piece of design, because the line is not a fixed distance from price but one that breathes with volatility. This guide explains how Supertrend works, why traders use it, and how to build it from scratch in Pine Script v6, first as an indicator and then as a strategy.

This is a coding tutorial, not trading advice. Supertrend is a way to express a volatility-adjusted trailing line in code, and building it yourself is the best way to understand where it excels and where it whipsaws.

How Supertrend works

Supertrend is built on the Average True Range, a measure of how much a market typically moves in a bar. The indicator takes a reference price, usually the midpoint of the high and low, and places a band a multiple of the ATR above and below it. As long as price stays above the lower band, the market is considered to be in an uptrend and the Supertrend line tracks that lower band, ratcheting upward and never loosening. When price closes below the line, the trend flips: the line jumps above price and starts trailing the upper band instead.

The reason it uses ATR rather than a fixed distance is what makes it adaptive. In a calm market the ATR is small, so the line hugs price closely and reacts quickly. In a volatile market the ATR grows, so the line sits further away and gives price more room to breathe before flipping. That single idea, scaling the trailing distance by volatility, is why Supertrend feels responsive without flipping on every small wiggle. If you want the mechanics of the ATR itself, our ATR in Pine Script guide covers it in depth.

Why traders use it

Traders like Supertrend because it turns the fuzzy question "are we trending up or down" into a binary, visible answer with a clear flip point. The line doubles as a natural trailing stop: in a long, you can hold while price stays above the green line and treat a close below it as the exit. That makes it popular both as a standalone signal and as an exit mechanism layered on top of another entry rule.

The honest caveat is that Supertrend is a trend-following tool, and like all of them it pays for its clean trend behavior with poor range behavior. In a sideways market price crosses back and forth over the line repeatedly, flipping the trend and generating a string of false signals. The factor and ATR settings let you trade off responsiveness against that whipsaw, but they cannot eliminate it.

Small factor / short ATRLarge factor / long ATR
ReactionFlips quicklyFlips slowly
SignalsMore, noisierFewer, cleaner
WhipsawsMore frequentRarer
SuitsFast timeframesPosition and swing context

Building the indicator

Pine Script provides Supertrend as a built-in function that returns two values: the line itself and a direction value telling you which side of price it is on. Here is the complete v6 indicator.

pine
//@version=6
indicator("Supertrend", overlay = true)

atrPeriod = input.int(10, "ATR Period")
factor    = input.float(3.0, "Factor")

[supertrend, direction] = ta.supertrend(factor, atrPeriod)

upTrend   = direction < 0 ? supertrend : na
downTrend = direction > 0 ? supertrend : na

plot(upTrend, "Up Trend", color = color.green, style = plot.style_linebr, linewidth = 2)
plot(downTrend, "Down Trend", color = color.red, style = plot.style_linebr, linewidth = 2)

The working line is [supertrend, direction] = ta.supertrend(factor, atrPeriod). The function returns the trailing line and a direction value that is negative when the trend is up and positive when it is down. The two ternary expressions split the single line into an up-trend series and a down-trend series so each can be plotted in its own color, using na for the bars where that direction is not active. The style = plot.style_linebr tells Pine to break the line at those na gaps rather than connecting across them, which is what gives Supertrend its characteristic segmented look. Plotting a value only under a condition, using na the rest of the time, is a pattern worth knowing, and it is the correct alternative to trying to call plot inside an if block, which Pine does not allow, as we explain in cannot use plot in local scope.

Turning it into a strategy

Because the direction value flips cleanly, converting Supertrend into a strategy is short: go long when the direction turns up, close when it turns down.

pine
//@version=6
strategy("Supertrend Strategy", overlay = true, margin_long = 100, margin_short = 100)

atrPeriod = input.int(10, "ATR Period")
factor    = input.float(3.0, "Factor")

[supertrend, direction] = ta.supertrend(factor, atrPeriod)

flippedUp   = ta.crossunder(direction, 0)
flippedDown = ta.crossover(direction, 0)

if flippedUp
    strategy.entry("Long", strategy.long)

if flippedDown
    strategy.close("Long")

Since direction is negative in an uptrend, the moment it flips up is the bar it crosses from positive to negative, which is why the entry uses ta.crossunder(direction, 0). The mirror ta.crossover(direction, 0) catches the flip back to a downtrend. Assigning each crossover to its own variable before the if keeps those functions running on every bar, which they need to track state correctly, and the order calls sit inside if blocks as v6 requires.

Tuning the factor and ATR period

The two settings interact to control how tightly the line follows price. A small factor or a short ATR period keeps the line close, so it reacts fast but flips often, producing more signals and more whipsaws. A large factor or a long ATR period holds the line further out, so it flips rarely and filters more noise, at the cost of giving back more of a move before it exits. The default of a 10-period ATR with a factor of 3 is a reasonable starting balance, not a magic number. As with any indicator, resist the urge to keep nudging the settings until one chart looks perfect, because numbers fit to past data on a single symbol rarely hold up elsewhere.

The honest pitfalls

Supertrend's defining weakness is the range-bound market. Its clean, decisive flips become a liability when price is going nowhere, chopping across the line and triggering trade after trade. Many traders pair it with a separate trend or volatility filter, only acting on Supertrend flips when a broader condition confirms a market worth trend-following in. It is also worth remembering that the flip is confirmed on the bar close, so an intrabar view of the indicator can look different from the confirmed signal, which matters if you intend to automate it.

As always, judge a Supertrend strategy across a meaningful sample of trades over several years and more than one market, rather than a stretch of history where the trend happened to be strong. A tool that flips beautifully in a trending backtest can behave very differently the moment the market goes quiet.

Building it faster

Coding Supertrend by hand, especially the line-break plotting, teaches you how the direction value drives everything else. When you already know the behavior you want, describing it in plain English is faster than assembling the ternaries and crossovers yourself. A tool like PineScripter generates the v6 code and, when it does not compile, reads TradingView's error and fixes it automatically. You can compare that workflow with other options in our roundup of the best AI Pine Script generators, and our moving average crossover guide is a good companion for the trend-following mindset Supertrend fits into.

The takeaway

Supertrend is an ATR-scaled trailing line delivered by one function, ta.supertrend(), with a direction value that makes trend flips easy to act on. Its adaptive, volatility-aware distance is what makes it feel responsive, and its range-bound whipsaws are the price of that responsiveness. Build it, tune the factor and ATR for the timeframe you trade, add a filter for choppy markets, and test the result honestly.


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.