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
195 lines of Pine Script v5 from BB Swing Strategy.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.
BB Swing Strategy.pine
//@version=5
//
// Author: benso87
// benso87.com
//
//
strategy("BB Swing", overlay=true, initial_capital=100, default_qty_value=100, default_qty_type=strategy.percent_of_equity, process_orders_on_close=true, backtest_fill_limits_assumption=1, commission_type=strategy.commission.percent, commission_value=0.06)
noColor = color.new(color.white, transp=100)
///////////////////////////////////////////////////////////////////////////////
// Inputs
// Dates
startDate = input.time(timestamp('1 Jan 2022 00:00'), title='Start', group='Dates')
endDate = input.time(timestamp('1 Jan 2100 00:00'), title='End', group='Dates')
// General
src = input.source(close, title='Source', group='General')
useLong = input.bool(true, title='Longs', group='General')
useShort = input.bool(true, title='Shorts', group='General')
testTypeApprox = input.bool(false, title='Use approximate entry?', group='General')
testPercent = input.float(10, title='Test approx %', minval=0, maxval=100, group='General')
frontrun = input.bool(false, title='Front run TP?', group='General')
frontrunPercent = input.float(10, title='Fron run %', minval=0, maxval=100, group='General')
// Moving Average
maLength = input.int(200, title='MA Length', minval=1, group='Moving Average')
maType = input.string( "EMA", title="Type", options=['SMA','EMA'], group="Moving Average")
maLookback = input.int(1, title='Slope Lookback', minval=1, group='Moving Average')
// Bollinger Bands
bbLength = input.int(21, minval=1, group='Bollinger Bands')
bbMult = input.float(2.0, minval=0.001, maxval=50, title="StdDev", group='Bollinger Bands')
useBiasFill = input.bool(true, title='Bias Filling?', group='Bollinger Bands')
defaultFill = input.color(noColor, title='Default', group='Bollinger Bands')
longFill = input.color(color.new(color.green, transp=80), title='Long Bias', group='Bollinger Bands')
shortFill = input.color(color.new(color.red, transp=80), title='Short Bias', group='Bollinger Bands')
// Stoch RSI
smoothK = input.int(3, title='K', minval=1, group='Stochastic RSI')
smoothD = input.int(3, title='D', minval=1, group='Stochastic RSI')
rsiLength = input.int(21, minval=1, title='RSI Length', group='Stochastic RSI')
stochLength = input.int(14, title='Stoch Length', minval=1, group='Stochastic RSI')
srsiHigh = input.float(90, title='High', minval=0, maxval=100, group='Stochastic RSI')
srsiLow = input.float(10, title='Low', minval=0, maxval=100, group='Stochastic RSI')
// ATR
atrLength = input.int(21, title='ATR Length', minval=1, group='Average True Range')
atrMult = input.float(2, title='ATR Multiplier', minval=0, group='Average True Range')
// ADX
useADX = input.bool(true, title='Use ADX for bias?', group='ADX')
length = input.int(14, title='ADX Length', minval=1, group='ADX')
adxLow = input.float(30, title='ADX Low', minval=0, maxval=100, group='ADX')
///////////////////////////////////////////////////////////////////////////////
// Functions
// Moving average type
f_ma(source, length, type) =>
switch type
'SMA' => ta.sma(source, length)
'EMA' => ta.ema(source, length)
'RMA' => ta.rma(source, length)
'WMA' => ta.wma(source, length)
///////////////////////////////////////////////////////////////////////////////
// Calculations
// Moving Average
ma = f_ma(src, maLength, maType)
maSlope = ma - ta.sma(ma, maLookback)
// Bollinger Bands
basis = ta.sma(src, bbLength)
dev = bbMult * ta.stdev(src, bbLength)
upper = basis + dev
lower = basis - dev
bandDiff = upper - lower
upperishTest = upper - (testPercent * bandDiff) / 100
upperishTP = upper - (frontrunPercent * bandDiff) / 100
lowerishTest = lower + (testPercent * bandDiff) / 100
lowerishTP = lower + (frontrunPercent * bandDiff) / 100
bbUpTestApprox = close > basis and close[1] > upperishTest[1] and close <= upperishTest
bbUpTestExact = close > basis and close[1] > upper[1] and close <= upper
bbUpTest = testTypeApprox ? bbUpTestApprox : bbUpTestExact
bbLowTestApprox = close < basis and close[1] < lowerishTest[1] and close >= lowerishTest
bbLowTestExact = close < basis and close[1] < lower[1] and close >= lower
bbLowTest = testTypeApprox ? bbLowTestApprox : bbLowTestExact
// Stoch RSI
rsi = ta.rsi(src, rsiLength)
k = ta.sma(ta.stoch(rsi, rsi, rsi, stochLength), smoothK)
d = ta.sma(k, smoothD)
// ATR
atr = ta.atr(atrLength)
// ADX
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, length)
plus = fixnan(100 * ta.rma(plusDM, length) / trur)
minus = fixnan(100 * ta.rma(minusDM, length) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), length)
// Biases
longBias = maSlope >= 0 and basis >= ma and (not useADX or adx >= adxLow)
shortBias = maSlope <= 0 and close < ma and basis <= ma and (not useADX or adx >= adxLow)
// Stop losses
slLongCurrent = lower - (atrMult * atr)
slShortCurrent = upper + (atrMult * atr)
// Take profits
tpLong = frontrun ? upperishTP : upper
tpShort = frontrun ? lowerishTP : lower
// Fill color
fillColor = useBiasFill and longBias ? longFill : useBiasFill and shortBias ? shortFill : defaultFill
// Entries
longEntry = useLong and time >= startDate and time <= endDate and longBias and bbLowTest and k < srsiHigh
shortEntry = useShort and time >= startDate and time <= endDate and shortBias and bbUpTest and k > srsiLow
// Trade variables
var float entryPrice = na
var float slLong = na
var float slShort = na
var string tradeType = na
if longEntry and strategy.position_size == 0
entryPrice := close
slLong := slLongCurrent
tradeType := 'long'
if shortEntry and strategy.position_size == 0
entryPrice := close
slShort := slShortCurrent
tradeType := 'short'
stopLoss = tradeType == 'long' ? slLong : tradeType == 'short' ? slShort : na
takeProfit = tradeType == 'long' ? tpLong : tradeType == 'short' ? tpShort : na
///////////////////////////////////////////////////////////////////////////////
// Strategy
// Entries
strategy.entry('Long', strategy.long, when=longEntry)
strategy.entry('Short', strategy.short, when=shortEntry)
// Exits
strategy.exit('Long Exit', from_entry='Long', stop=slLong, limit=tpLong)
strategy.exit('Short Exit', from_entry='Short', stop=slShort, limit=tpShort)
///////////////////////////////////////////////////////////////////////////////
// Plots
// Bollinger Bands
plot(basis, title='Basis', color=color.orange, linewidth=1)
p1 = plot(upper, title='Upper', color=color.blue, linewidth=2)
p2 = plot(lower, title='Lower', color=color.blue, linewidth=2)
fill(p1, p2, title='BB Background', color=fillColor)
// SL Bands
plot(slLongCurrent, title='Long SL', color=color.new(color.red, transp=50), linewidth=1)
plot(slShortCurrent, title='Short SL', color=color.new(color.red, transp=50), linewidth=1)
// Moving Average
plot(ma, title='MA', color=color.yellow, linewidth=2)
// Trades
sl = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? stopLoss : na, title='Stop Loss', color=color.red, style=plot.style_linebr)
e = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? entryPrice : na, title='Entry', color=color.yellow, style=plot.style_linebr)
tp = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? takeProfit : na, title='Take Profit', color=color.green, style=plot.style_linebr)
fill(sl, e, color=color.new(color.red, transp=80))
fill(tp, e, color=color.new(color.green, transp=80))
///////////////////////////////////////////////////////////////////////////////
// Testing
plot(maSlope + ma, title='MA slope line', color=color.white)
plotchar(maSlope, title='MA slope', char='.', color=noColor)
Overview
BB Swing evaluates trend bias and momentum conditions to generate long and short swing entries using percent-of-equity sizing. The settings allow traders to adjust moving average lengths and types, Bollinger Band parameters, Stochastic RSI thresholds, and ADX filters, with options for approximate entries and take-profit front-running. Because only the initial script setup is shown, full exit rules and stop-loss logic remain unspecified.
Bollinger Bands with bias filling
Configurable moving average slope filter
Stochastic RSI momentum thresholds
ADX trend bias filter
ATR multiplier and optional take-profit front-running
The inputs you can change from the gear icon on the chart. Defaults are the author's.
Setting
Type
Default
Variable
Start
time
timestamp('1 Jan 2022 00:00')
startDate
End
time
timestamp('1 Jan 2100 00:00')
endDate
Source
source
close
src
Longs
bool
true
useLong
Shorts
bool
true
useShort
Use approximate entry?
bool
false
testTypeApprox
Test approx %
float
10
testPercent
Front run TP?
bool
false
frontrun
Fron run %
float
10
frontrunPercent
MA Length
int
200
maLength
Type
string
EMA
maType
Slope Lookback
int
1
maLookback
Show all 29 settings
Setting
Type
Default
Variable
bbLength
int
21
bbLength
StdDev
float
2.0
bbMult
Bias Filling?
bool
true
useBiasFill
Default
color
noColor
defaultFill
Long Bias
color
color.new(color.green, transp=80)
longFill
Short Bias
color
color.new(color.red, transp=80)
shortFill
K
int
3
smoothK
D
int
3
smoothD
RSI Length
int
21
rsiLength
Stoch Length
int
14
stochLength
High
float
90
srsiHigh
Low
float
10
srsiLow
ATR Length
int
21
atrLength
ATR Multiplier
float
2
atrMult
Use ADX for bias?
bool
true
useADX
ADX Length
int
14
length
ADX Low
float
30
adxLow
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 overlays a trend moving average and Supertrend bands directly on the price chart while calculating Stochastic RSI values internally. Long positions trigger when price exceeds the moving average, Supertrend signals bullish momentum, and the StochR
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
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
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
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
This strategy evaluates market trend and momentum to generate long and short trading signals on price charts. It plots 100-period and 500-period moving averages (EMA or SMA) to establish macro trend direction. Long entries require trend alignment alongside opt