SuperTrend Strategy on TradingView: Pine Script and Test Assumptions
This tutorial uses TradingView’s ta.supertrend() to create simulated long and short reversal orders. It explains the ATR inputs, signal timing, and testing limits. No performance result is established here: the settings are teaching defaults, and the script does not include a separate protective stop or trading costs.
How the SuperTrend Example Works
SuperTrend combines the midpoint of high and low with an ATR-scaled distance. The built-in function carries forward final bands according to prior bands and closing prices; the active band changes when the trend state reverses.
Construction
- ATR measures recent trading range, including gaps. It is not a prediction of the next range.
- Basic bands start at (high + low) / 2 plus or minus factor × ATR.
- Final bands depend on prior state and reset conditions. They are plotted indicator levels, not stop orders in this script.
Orders and timing
The strategy evaluates at bar close under its default settings. A direction change creates a market order; the broker emulator normally fills it at the next bar’s open. A signal does not identify an exact market turning point. Sideways markets can produce repeated reversals.
See TradingView’s Supertrend calculation and strategy execution documentation.
| Component | Description | Role |
|---|---|---|
| ATR Period | Lookback for Average True Range | Sets the ATR lookback (example default 10) |
| Multiplier | Scales ATR distance from the midline | Scales the indicator’s ATR distance (example default 3) |
| Upper / Lower Bands | State-dependent indicator bands | Define when trend state switches |
| Direction state | Binary bullish vs bearish regime from band logic | Drives entries when the state flips |
Pine Script v5 Implementation
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify_Expert
//@version=5
strategy("SuperTrend Reversal Tutorial", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// --- Inputs ---
atrPeriod = input.int(10, "ATR Period", minval=1)
multiplier = input.float(3.0, "ATR Multiplier", minval=0.1, step=0.1)
showSignals = input.bool(true, "Show Buy/Sell Signals")
highlightState = input.bool(true, "Highlight Trend State")
// --- SuperTrend Calculation ---
[supertrend, direction] = ta.supertrend(multiplier, atrPeriod)
// --- Visuals ---
bodyMiddle = plot((open + close) / 2, "Body Midpoint", display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color=color.green, style=plot.style_linebr)
downTrend = plot(direction > 0 ? supertrend : na, "Down Trend", color=color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, highlightState ? color.new(color.green, 90) : na, "Up Trend Fill")
fill(bodyMiddle, downTrend, highlightState ? color.new(color.red, 90) : na, "Down Trend Fill")
plotshape(showSignals and direction < 0 and direction[1] > 0 ? supertrend : na, title="Buy Signal", style=shape.labelup, location=location.absolute, color=color.green, textcolor=color.white, text="BUY", size=size.small)
plotshape(showSignals and direction > 0 and direction[1] < 0 ? supertrend : na, title="Sell Signal", style=shape.labeldown, location=location.absolute, color=color.red, textcolor=color.white, text="SELL", size=size.small)
// --- Strategy Logic ---
if (direction < 0 and direction[1] > 0)
strategy.entry("Long", strategy.long)
if (direction > 0 and direction[1] < 0)
strategy.entry("Short", strategy.short)
// --- Risk Management (Optional) ---
// You can add hard stop losses or take profits here to further refine the strategy.Code Breakdown
- 1
Strategy properties: initial capital is 10,000 and entry size is 100% of simulated equity. These are teaching defaults, not position-sizing recommendations. Commission and slippage default to zero unless changed in Properties.
- 2
Inputs: ATR period and multiplier alter the indicator. The showSignals and highlightState inputs control markers and fills, not order placement.
- 3
ta.supertrend(): negative direction indicates the bullish state and positive direction the bearish state. The example enters only on a change between those states.
- 4
Orders: strategy.entry() reverses the existing simulated position when an opposite entry fills. With default execution, the bar-close signal normally fills at the next bar open, not at the plotted signal level.
- 5
Risk controls: no strategy.exit() stop or target is present. The plotted SuperTrend line is not an executable protective stop, and an order is not a live brokerage instruction.
Backtest Assumptions and Metrics
No dated trade export, exchange feed, or reproducible test artifact supports a performance result for this example. The table is a checklist of assumptions to record in your own run; it is not a reported BTC/USDT result or a typical-return claim.
| Metric | Value |
|---|---|
| Instrument and data | Record exchange, ticker, timeframe, and standard candle type |
| Date window | Record exact start/end dates and available history |
| Inputs | Default ATR 10 and factor 3; save any changes |
| Order timing | Bar-close signal; next available tick fill by default |
| Sizing and costs | Review 100% equity sizing, commission, slippage, and margin |
| Independent evaluation | Keep an untouched validation window and save the trade export |
Compare net results after realistic costs, the size and duration of drawdowns, and dependence on a few trades. Win rate alone does not establish profitability, a Sharpe ratio does not prove an edge, and an average trade does not guarantee enough margin for every execution cost. Changing filters after seeing results can overfit the history.
Review the Exported Trade History
Pineify’s Backtest Report analyzes an exported TradingView trade list. It does not rerun the Pine strategy or establish that a rule will work out of sample.
Use the report to inspect the uploaded history and available summary calculations, then return to TradingView to change script inputs and run a new test. Record costs and dates with each export. Check current access requirements on the product page; this tutorial does not promise a free trial or automatic validation.
Strategy Optimization Suggestions
MTF Filtering
Test a separately confirmed higher-timeframe condition against the unfiltered baseline. Do not use future higher-timeframe values; fewer trades need not improve results.
Volume Confirmation
A volume threshold is an optional hypothesis, absent from this script. Specify the baseline and feed coverage, then compare costs and rejected trades.
Regime-Adaptive Multipliers
A changing multiplier requires additional logic and can increase fitting choices. Test it on untouched data; the current example uses a fixed input and has no stop order.
ADX Strength Filter
An ADX threshold is an optional condition to test, not a proven improvement. It is not included in the example and does not identify price direction.
Frequently Asked Questions
Review the Script and Its Test Assumptions
Use the Coding Agent to draft changes, review the final logic, and rerun the strategy in TradingView. A CSV report can help inspect the resulting trades; it does not certify a strategy or execute live orders.
Disclaimer: Trading involves significant risk. The strategies and code provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.
Related Strategy Tutorials
MACD Crossover Strategy Tutorial
Read MACD crossover definitions, Pine Script examples and backtest interpretation on TradingView.
Bollinger Bands Breakout Strategy Tutorial
Master the Bollinger Bands Squeeze and Breakout strategy on TradingView. Learn the Pine Script v5 code and professional analysis with Pineify.
Breakout and Retest Strategy Tutorial
Study a Pine Script v6 breakout-and-retest strategy with confirmed pivots, volume filters and simulated ATR-based exits; test its assumptions in TradingView.
VWAP Strategy Tutorial
Build a daily-anchored VWAP reversion example in Pine Script v6. Review rolling price-deviation bands, independent stop and target controls, and fill-timing limits.