SuperTrend Strategy is a trend-following strategy that plots an ATR-based SuperTrend line on the price chart and optionally fills the background green or red with the trend.
1Copy the scriptPress Copy script above, or the copy button on the code below.
2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.
Source Code
128 lines of Pine Script v4 from supertrend.pinescript, published under MIT. Keep the author's credit and licence lines when you reuse it.
supertrend.pinescript
//@version=4
strategy("SuperTrend Strategy", overlay=true, default_qty_value=5, currency=currency.USD, default_qty_type=strategy.percent_of_equity, initial_capital=10000, max_bars_back=4000)
//===== TIMEFRAME ==========================================================================//
from_month = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
from_day = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
from_year = input(defval = 2019, title = "From Year", minval = 2017)
to_month = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
to_day = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
to_year = input(defval = 9999, title = "To Year", minval = 2017)
start = timestamp(from_year, from_month, from_day, 00, 00)
finish = timestamp(to_year, to_month, to_day, 23, 59)
window() => time >= start and time <= finish ? true : false
//===== INPUTS ==========================================================================//
factor = input(3, title="ATR Factor")
period = input(10, minval = 1, maxval = 100, title="ATR Period")
up = (high + low) / 2 - (factor * atr(period))
down = (high + low) / 2 + (factor * atr(period))
trend_up = 0.0
trend_up := close[1] > trend_up[1] ? max(up, trend_up[1]) : up
trend_down = 0.0
trend_down := close[1] < trend_down[1] ? min(down, trend_down[1]) : down
trend = 0.0
trend := close > trend_down[1] ? 1 : close < trend_up[1] ? -1 : nz(trend[1], 1)
tsl = trend == 1 ? trend_up : trend_down
line_color = trend == 1 ? "green" : "red"
long_signal = trend == 1 and trend[1] == -1
short_signal = trend == -1 and trend[1] == 1
background = input(title = "Background On/Off ?", type = input.bool, defval = true)
use_sl = input(title = "Use Stop Loss ?", type = input.bool, defval = false)
initial_sl_pct = input(defval = 15.0, minval = 0.0, title="Stop Loss %")
//===== PLOTS ==========================================================================//
// Line
line_plot = plot(tsl, color = trend == 1 ? color.green : color.red, linewidth = 2, title = "Trend Line")
// Labels
plotshape(long_signal and window() ? up : na, title = "Buy", text = "Buy", location = location.absolute, style = shape.labelup, size = size.tiny, color = color.green, textcolor = color.white, transp = 0)
plotshape(short_signal and window() ? down : na, title = "Sell", text = "Sell", location = location.absolute, style = shape.labeldown, size = size.tiny, color = color.red, textcolor = color.white, transp = 0)
// Circles
plotshape(long_signal and window() ? up : na, title = "Uptrend starts", location = location.absolute, style = shape.circle, size = size.tiny, color = color.green, transp = 0)
plotshape(short_signal and window() ? down : na, title = "Downtrend starts", location = location.absolute, style = shape.circle, size = size.tiny, color = color.red, transp = 0)
// Background
long_fill = background ? (trend == 1 ? color.green : na) : na
short_fill = background ? (trend == -1 ? color.red : na) : na
candle_plot = plot(ohlc4, title = "Price Line", color = trend == 1 ? long_fill : short_fill, transp = 90, linewidth = 2)
fill(candle_plot, line_plot, title = "Long Background", color = long_fill)
fill(candle_plot, line_plot, title = "Short Background", color = short_fill)
//===== GLOBAL ==========================================================================//
var entry_price = 0.0
var updated_entry_price = 0.0
var sl_price = 0.0
has_open_trade() => strategy.position_size != 0
has_no_open_trade() => strategy.position_size == 0
is_long() => strategy.position_size > 0 ? true : false
is_short() => strategy.position_size < 0 ? true : false
plot(use_sl ? has_no_open_trade() ? close : sl_price : na, color = has_no_open_trade() ? na : color.blue, title = "Stop Loss")
strategy_close() =>
if (is_long())
strategy.close("Long")
if (is_short())
strategy.close("Short")
strategy_long() =>
strategy.entry("Long", strategy.long)
strategy_short() =>
strategy.entry("Short", strategy.short)
sl_pct = initial_sl_pct
if (long_signal or is_long() and not (short_signal or is_short()))
sl_pct := initial_sl_pct * -1
//===== STRATEGY ==========================================================================//
crossed_sl = false
if (is_long() and use_sl)
crossed_sl := close <= sl_price
if (is_short() and use_sl)
crossed_sl := close >= sl_price
terminate_operation = window() and has_open_trade() and crossed_sl
if (terminate_operation and not (long_signal or short_signal)) // Do not close position if trend is flipping anyways.
entry_price := 0.0
updated_entry_price := entry_price
sl_price := 0.0
strategy_close()
start_operation = window() and (long_signal or short_signal)
if (start_operation)
entry_price := close
updated_entry_price := entry_price
sl_price := entry_price + (entry_price * sl_pct) / 100
if (long_signal)
strategy_long()
if (short_signal)
strategy_short()
//===== TRAILING ==========================================================================//
if (is_long() and use_sl)
strategy_pct = (close - updated_entry_price) / updated_entry_price * 100.00
if (strategy_pct > 1)
sl_pct := sl_pct + strategy_pct - 1.0
new_sl_price = updated_entry_price + (updated_entry_price * sl_pct) / 100
sl_price := max(sl_price, new_sl_price)
updated_entry_price := sl_price
if (is_short() and use_sl)
strategy_pct = (close - updated_entry_price) / updated_entry_price * 100.00
if (strategy_pct < -1)
sl_pct := sl_pct + strategy_pct + 1.0
new_sl_price = updated_entry_price + (updated_entry_price * sl_pct) / 100
sl_price := min(sl_price, new_sl_price)
updated_entry_price := sl_price
Overview
SuperTrend Strategy opens a long when the trend flips up and a short when it flips down, only inside a user-defined date window. Position size defaults to five percent of equity. The ATR factor and period change the line distance and sensitivity. An optional percentage stop loss is off by default, and the visible code shows no take-profit rule. Signals use the current close, so they can change before the live bar closes.
The inputs you can change from the gear icon on the chart. Defaults are the author's.
Setting
Type
Default
Variable
From Month
int
1
from_month
From Day
int
1
from_day
From Year
int
2019
from_year
To Month
int
1
to_month
To Day
int
1
to_day
To Year
int
9999
to_year
ATR Factor
int
3
factor
ATR Period
int
10
period
Background On/Off ?
bool
true
background
Use Stop Loss ?
bool
false
use_sl
Stop Loss %
float
15.0
initial_sl_pct
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.
This strategy calculates Bollinger Bands and Aroon oscillator values to identify mean-reversion opportunities. It enters a long position using full equity when the closing price crosses below the lower Bollinger Band while Aroon Up remains above a user-specifi
This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades
STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions
This strategy uses multiple VWAP anchors and a custom Lull indicator to generate buy and sell signals on the Nasdaq price chart. It plots the VWAP trend line and three VWAP anchors with customizable colors and mitigation methods. The Lull indicator produces si
This strategy implements a single-layer perceptron machine learning model built from scratch to generate trading signals directly on the price chart. It calculates predictions based on sample size, threshold settings, and optional volatility or volume filters.
This overlay strategy plots a two-timeframe Ichimoku setup on the price chart, with Tenkan, Kijun, Chikou, and Kumo from a base higher timeframe and an optional highest-timeframe cloud. It allows two entries in the same direction and uses ATR-based trailing st