Strategy · Pine Script v5 · On the chart

Supertrend

by g-moe· code credited to goodgains

This strategy calculates trend direction using a multi-timeframe Supertrend formula based on ATR and median price, paired with RSI and Bollinger Band indicators.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code132
Settings15inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago27 May 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 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

132 lines of Pine Script v5 from Tradingview/supertrend-v2.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

supertrend-v2.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © goodgains


//@version=5
strategy("Supertrend", overlay=true)

// @keywords: mtf-supertrend-strategy, atr-band-trend, thirty-minute-security, year-filter-close, direction-flip-entries, stepline-trend-plots, body-middle-fill, long-short-strategy, supertrend-cross-close, lookahead-security, hl2-atr-calc, trend-direction-plot, green-red-fill, strategy-year-exit, factor-atr-settings, overlay-supertrend, flip-entry-signals, v2-supertrend-rules, band-trailing-trend, strategy-entry-close


//
//SUPERTREND
//
atrPeriod = input(10, "ATR Length", group = "Supertrend Settings")
factor = input.float(3.0, "Factor", step = 0.01, group = "Supertrend Settings")
timeframe = input.timeframe('30', title = 'Timeframe', group = "Supertrend Settings")

pine_supertrend(factor, atrPeriod, timeframe) =>
    src = request.security(syminfo.tickerid, timeframe, hl2[1], lookahead = barmerge.lookahead_on)
    close_src = request.security(syminfo.tickerid, timeframe, close[1], lookahead = barmerge.lookahead_on)
    close_src2 = request.security(syminfo.tickerid, timeframe, close[2], lookahead = barmerge.lookahead_on)
    atr = request.security(syminfo.tickerid, timeframe, ta.atr(atrPeriod)[1], lookahead = barmerge.lookahead_on)
    upperBand = src + factor * atr
    lowerBand = src - factor * atr
    prevLowerBand = nz(lowerBand[1])
    prevUpperBand = nz(upperBand[1])

    lowerBand := lowerBand > prevLowerBand or close_src2 < prevLowerBand ? lowerBand : prevLowerBand
    upperBand := upperBand < prevUpperBand or close_src2 > prevUpperBand ? upperBand : prevUpperBand
    int direction = na
    float superTrend = na
    prevSuperTrend = superTrend[1]
    if na(atr[1])
        direction := 1
    else if prevSuperTrend == prevUpperBand
        direction := close_src > upperBand ? -1 : 1
    else
        direction := close_src < lowerBand ? 1 : -1
    superTrend := direction == -1 ? lowerBand : upperBand
    [superTrend, direction]

[supertrend, direction] = pine_supertrend(factor, atrPeriod, timeframe)


st_long = direction < 0
st_short = direction >= 0 
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(st_long ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(st_short ? supertrend : na, "Down Trend", color = color.red, style=plot.style_linebr)

fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)


//
//RSI_BB
//

ma(source, length, type) => 
    return_value = switch type
        "SMA" => ta.sma(source, length)
        "Bollinger Bands" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)
    return_value
    
f_bb(src, basis, length, mult) =>
    float dev = mult * ta.stdev(src, length)
    [basis, basis + dev, basis - dev]

rsiLengthInput = input.int(50, minval=1, title="RSI Length", group="RSI/MA Settings")
rsiSourceInput = input.source(hlc3, "Source", group="RSI/MA Settings")
maTypeInput = input.string("EMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="RSI/MA Settings")
maLengthInput = input.int(100, title="MA Length", group="RSI/MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="RSI/MA Settings")

rsi = ta.rsi(rsiSourceInput,rsiLengthInput)
rsi_ma = ma(rsi, maLengthInput, maTypeInput)
[pineMiddle, pineUpper, pineLower] = f_bb(rsi, rsi_ma, maLengthInput, bbMultInput)

// plot(rsi_value, color = color.new(#7e57c2,0))
// plot(pineMiddle, color = color.yellow)
// plot(pineUpper)
// plot(pineLower)

rsi_long = ta.crossover(rsi, pineLower)
rsi_short = ta.crossunder(rsi, pineUpper)


//
//MA EXIT
//
ma_exit_length = input.int(26, title = 'MA Length', group = 'MA Exit Settings')
ma_exit_type = input.string("EMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Exit Settings")

ma_exit = ma(close, ma_exit_length, ma_exit_type)
ma_long_exit = ta.crossunder(close, ma_exit)
ma_short_exit = ta.crossover(close, ma_exit)


//
//STRATEGY
//
strategy_start = input.time(timestamp("01 January 2020 00:00:00 UTC-5"), "Start Date", group = " Strategy Settings", inline = '1', tooltip = "This can be used as a start date for backteseting if you only wanted to backtest the last 3 months, last year, etc. There
     is a pinescript limitation for how far you can go back.")
use_trading_hours = input.bool(false, title = " ", group = " Strategy Settings", inline = '2')
trading_time = input.session("0930-1600", title = "Trading Time", tooltip = "This can be used if you only want to trade during certain hours of the day. This uses Eastern Time Zone or U.S. NY Market Hours.", group = " Strategy Settings", inline = '2')
trading_hours_cond = not use_trading_hours or time("",trading_time, "America/New_York")

long_trades = input.bool(true, title = "Long Trades", tooltip = "Do we want to take long trades?" , group = " Strategy Settings", inline = '3')
short_trades = input.bool(true, title = "Short Trades", tooltip = "Do we want to take short trades?" , group = " Strategy Settings", inline = '4')

long_entry = long_trades and trading_hours_cond and st_long and rsi_long
long_exit = long_trades and trading_hours_cond and ma_long_exit

short_entry = short_trades and trading_hours_cond and st_short and rsi_short
short_exit = short_trades and trading_hours_cond and ma_short_exit

past_strategy_start_date = time >= strategy_start ? true : false

if past_strategy_start_date
    //ORDERS
    strategy.close("LE", when = long_exit, comment = "LX")
    strategy.close("SS_E", when = short_exit, comment = "SS_X")
    
    strategy.entry("LE", direction = strategy.long, when = long_entry) 
    strategy.entry("SS_E", direction = strategy.short, when = short_entry) 


    strategy.close_all(when = not trading_hours_cond, comment = 'TX')

Overview

Supertrend enters positions when the Supertrend flips direction, plotting uptrend and downtrend bands with colored cloud fills directly on the price chart. Main settings allow customization of the ATR length, multiplier factor, target timeframe, trading hours, and trade direction filters. By default, it operates without an explicit stop loss.

Details

Published by

g-moe on GitHub

Code credit

goodgains, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

M15-H1

Risk Notes

  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
ATR Lengthint10atrPeriod
Factorfloat3.0factor
Timeframetimeframe30timeframe
RSI Lengthint50rsiLengthInput
Sourcesourcehlc3rsiSourceInput
MA TypestringEMAmaTypeInput
MA Lengthint100maLengthInput
BB StdDevfloat2.0bbMultInput
MA Lengthint26ma_exit_length
MA TypestringEMAma_exit_type
Start Datetimetimestamp("01 January 2020 00:00:00 UTC-5")strategy_start
boolfalseuse_trading_hours
Show all 15 settings
SettingTypeDefaultVariable
Trading Timesession0930-1600trading_time
Long Tradesbooltruelong_trades
Short Tradesbooltrueshort_trades
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.

Similar Pine Scripts

106 stars

This trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

Momentum Rider DAILY FINAL

by greenpeas007
58 stars

This strategy combines exponential moving averages (EMA 9, 21, 50), RSI, MACD, and Supertrend indicators to enter long positions. It triggers trades using six dynamic setups based on momentum breakouts, EMA crossovers, and pullbacks. Position sizing is compute

Strategy v6 TrendOscillators & momentum Repaints
Updated 4 months ago · Custom licence GitHub repository of Momentum Rider DAILY FINAL

CombinedBinHAndClucV6

by viktors1982
36 stars

CombinedBinHAndClucV6 is a trading strategy based on the popular BinHV45 and ClucMay72018 algorithms. It calculates dual Bollinger Bands, Exponential Moving Averages, Relative Strength Index, Average True Range, and volume metrics across primary and one-hour h

Strategy v4 Volatility & bandsOscillators & momentum Repaints
Updated 2 years ago · None stated GitHub repository of CombinedBinHAndClucV6

BB Swing

by benso87
24 stars

This strategy calculates Bollinger Bands, a configurable moving average slope, Stochastic RSI, ATR, and ADX directly on the price chart. It evaluates trend bias and momentum conditions to generate long and short swing entries using percent-of-equity sizing. Th

Strategy v5 Volatility & bandsOscillators & momentum
Updated 4 years ago · MPL-2.0 GitHub repository of BB Swing

This strategy trades long and short on the price chart using a multi-timeframe TradingLatino setup. It requires EMA 10 to cross or sit above or below EMA 55 on the one-hour, four-hour, and daily charts, together with a positive ADX slope, a directional monitor

Strategy v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ruckard ABCBitcoin TradingLatino A010

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers