Pine Script SuperTrend (ATR-based)

Master this powerful volatility-adjusted trend indicator in TradingView's Pine Script for dynamic buy/sell signals and stop-loss placement.

Posted: Expertise: Intermediate

What is SuperTrend?

The SuperTrend indicator is a popular trend-following system that plots a line on the price chart, dynamically switching its position relative to the price. It's built upon the concept of Average True Range (ATR), which measures market volatility. This makes SuperTrend adaptive to changing market conditions, providing more reliable signals than indicators with fixed distances from price.

In Pine Script, SuperTrend is a robust tool for identifying trends, generating buy/sell signals, and even for setting dynamic stop-loss levels.

Components and Calculation

SuperTrend primarily consists of two key components:

The indicator calculates an upper and lower basic band, and then switches between them based on price action. The core calculation involves:

  1. Calculating ATR: Measures the average volatility over the specified period.
  2. Basic Upper Band: `(high + low) / 2 + (multiplier * ATR)`
  3. Basic Lower Band: `(high + low) / 2 - (multiplier * ATR)`
  4. Final SuperTrend Line: The line switches based on whether the closing price crosses the basic bands, reflecting the prevailing trend. When price closes above the upper band, SuperTrend flips below price; when price closes below the lower band, it flips above price.

Basic SuperTrend Implementation in Pine Script

Pine Script v5 provides a convenient built-in function `ta.supertrend()` that handles all the calculations for you.

//@version=5
indicator("My SuperTrend Indicator", overlay=true)

// Inputs for SuperTrend parameters
atrPeriod = input(10, title="ATR Length")
factor = input.float(3.0, title="Factor")

// Calculate SuperTrend using the built-in function
[supertrend, direction] = ta.supertrend(factor, atrPeriod)

// Plot the SuperTrend line, coloring it based on its direction
plot(supertrend, title="SuperTrend", color=direction < 0 ? color.green : color.red, linewidth=2)

// Optional: Plot arrows when the trend changes
plotshape(direction == 1 and direction[1] == -1, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)
plotshape(direction == -1 and direction[1] == 1, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
Understanding `direction` Output: The `ta.supertrend()` function returns two values: the `supertrend` line value and a `direction` value. `direction` is `1` for an uptrend (SuperTrend below price) and `-1` for a downtrend (SuperTrend above price).

Practical SuperTrend Strategies

1. Trend Following with SuperTrend

SuperTrend excels at identifying and following trends. When the SuperTrend line is below the price, it indicates an uptrend (often colored green). When it's above the price, it indicates a downtrend (often colored red).

//@version=5
strategy("SuperTrend Trend Following", overlay=true)

// Inputs
atrPeriod = input(10, title="ATR Length")
factor = input.float(3.0, title="Factor")

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

// Entry conditions based on SuperTrend direction change
longCondition = ta.crossover(close, supertrend) // Price crosses above SuperTrend
shortCondition = ta.crossunder(close, supertrend) // Price crosses below SuperTrend

// Strategy entries
if (longCondition)
    strategy.entry("Long", strategy.long)

if (shortCondition)
    strategy.entry("Short", strategy.short)

// Plot SuperTrend
plot(supertrend, title="SuperTrend", color=direction < 0 ? color.green : color.red, linewidth=2)

2. SuperTrend as a Dynamic Stop-Loss

One of SuperTrend's most powerful applications is as a dynamic stop-loss. The indicator's line itself can serve as a trailing stop, adapting to market volatility. When in a long position, the SuperTrend's green line (uptrend) acts as your stop. When in a short position, the red line (downtrend) acts as your stop.

//@version=5
strategy("SuperTrend Dynamic Stop-Loss", overlay=true)

// Inputs
atrPeriod = input(10, title="ATR Length")
factor = input.float(3.0, title="Factor")

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

// Entry conditions (example: simple moving average crossover for entries)
fastMA = ta.ema(close, 20)
slowMA = ta.ema(close, 50)
longEntry = ta.crossover(fastMA, slowMA)
shortEntry = ta.crossunder(fastMA, slowMA)

// Long strategy
if (longEntry)
    strategy.entry("Buy", strategy.long)

// Short strategy
if (shortEntry)
    strategy.entry("Sell", strategy.short)

// Dynamic Stop Loss based on SuperTrend
// If in a long position, close if price crosses below SuperTrend
if (strategy.position_size > 0)
    strategy.exit("Long Exit", from_entry="Buy", stop=supertrend)

// If in a short position, close if price crosses above SuperTrend
if (strategy.position_size < 0)
    strategy.exit("Short Exit", from_entry="Sell", stop=supertrend)

// Plot SuperTrend
plot(supertrend, title="SuperTrend", color=direction < 0 ? color.green : color.red, linewidth=2)

Optimizing SuperTrend Performance

To maximize SuperTrend's effectiveness:

Important: The ATR period and multiplier are crucial. Too small, and you'll get whipsaws; too large, and signals will be too late. Find a balance that suits your trading style and asset.

Common SuperTrend Pitfalls

Conclusion

The SuperTrend indicator is an exceptional tool for traders seeking a dynamic, volatility-adjusted way to identify and follow trends in Pine Script. Its intuitive visual signals and utility as a stop-loss mechanism make it a valuable addition to any TradingView strategy. By understanding its ATR-based calculations and combining it wisely with other analytical tools, you can harness the full power of SuperTrend to navigate market movements more effectively.