Trading StrategyPine Script v5

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.

ComponentDescriptionRole
ATR PeriodLookback for Average True RangeSets the ATR lookback (example default 10)
MultiplierScales ATR distance from the midlineScales the indicator’s ATR distance (example default 3)
Upper / Lower BandsState-dependent indicator bandsDefine when trend state switches
Direction stateBinary bullish vs bearish regime from band logicDrives entries when the state flips

Pine Script v5 Implementation

Pine Script v5
// 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. 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. 2

    Inputs: ATR period and multiplier alter the indicator. The showSignals and highlightState inputs control markers and fills, not order placement.

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

MetricValue
Instrument and dataRecord exchange, ticker, timeframe, and standard candle type
Date windowRecord exact start/end dates and available history
InputsDefault ATR 10 and factor 3; save any changes
Order timingBar-close signal; next available tick fill by default
Sizing and costsReview 100% equity sizing, commission, slippage, and margin
Independent evaluationKeep 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

1

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.

2

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.

3

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.

4

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

No timeframe is demonstrated to be best here. Compare matching date windows, cost assumptions, and enough trades; choosing a timeframe after inspecting its best result can overfit.

The multiplier scales the ATR band distance. Compare a bounded set of values with costs included, then evaluate the selection on an untouched window. No optimum is supplied by this tutorial.

It can be calculated on short chart intervals, but this example has not demonstrated a scalping advantage. Spread, slippage, and the default next-bar fill can materially affect those tests.

This strategy calculates at bar close by default and does not request future data. Intrabar indicator values can change before confirmation; changing inputs, chart type, data history, or calculation settings can change results. Signal timing and order fills still differ.

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.