Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-supertrend

$ 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.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

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.

02

Components and Calculation

SuperTrend primarily consists of two key components:

  • ATR Period: The look-back period for calculating the Average True Range (e.g., 10 periods).
  • Multiplier (Factor): A value that determines the distance of the SuperTrend line from the price (e.g., 3).
  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.
03

Basic SuperTrend Implementation in Pine Script

pine-script@terminal
//@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)
$ ✓ Compiled successfully
04

Understanding `direction` Output

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).

05

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)
shortCondition = ta.crossunder(close, 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.

//@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 (strategy.position_size > 0)
    strategy.exit("Long Exit", from_entry="Buy", stop=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)
06

Optimizing SuperTrend Performance

To maximize SuperTrend's effectiveness:

  • Parameter Tuning: Experiment with `atrPeriod` and `factor` for different timeframes and assets. A shorter ATR period makes it more sensitive; a smaller factor brings the line closer to price.
  • Multi-Timeframe Analysis: Use SuperTrend on a higher timeframe to confirm the overall trend, and on a lower timeframe for entry/exit signals.
  • Combine with Volume: Look for volume confirmation on SuperTrend signals. A trend reversal accompanied by significant volume often provides a stronger signal.
  • Confluence with Support/Resistance: SuperTrend signals that align with key support or resistance levels can be more reliable.
07

Important Parameter Note

Important Parameter Note

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.

08

Common SuperTrend Pitfalls

  • Whipsaws in Ranging Markets: SuperTrend performs best in trending markets. In choppy or sideways markets, it can generate numerous false signals.
  • Lagging Indicator: Like other trend-following indicators, SuperTrend can sometimes lag price action, especially during sharp reversals.
  • Not a Standalone Indicator: Relying solely on SuperTrend without additional confirmation from other indicators or price action can lead to poor results.
  • Over-Optimization: Excessive tuning of parameters to historical data may not translate to future performance.
09

Conclusion

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.

Enhance Your Trading

Get a high-performance Pine Script analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pine Script Strategy