Strategy · Pine Script v5 · On the chart

BB Swing

by benso87

This strategy calculates Bollinger Bands, a configurable moving average slope, Stochastic RSI, ATR, and ADX directly on the price chart.

View on GitHub

GitHub stars24on the repository
Pine versionv5runs as is
Lines of code195
Settings29inputs
LicenceMPL-2.0
Last update4 years ago5 Oct 2022

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

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.

Details

Published by

benso87 on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Oscillators & momentum, Moving averages, Trend

Markets

Any symbol

Timeframes

H4 and above

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

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

SettingTypeDefaultVariable
Starttimetimestamp('1 Jan 2022 00:00')startDate
Endtimetimestamp('1 Jan 2100 00:00')endDate
Sourcesourceclosesrc
LongsbooltrueuseLong
ShortsbooltrueuseShort
Use approximate entry?boolfalsetestTypeApprox
Test approx %float10testPercent
Front run TP?boolfalsefrontrun
Fron run %float10frontrunPercent
MA Lengthint200maLength
TypestringEMAmaType
Slope Lookbackint1maLookback
Show all 29 settings
SettingTypeDefaultVariable
bbLengthint21bbLength
StdDevfloat2.0bbMult
Bias Filling?booltrueuseBiasFill
DefaultcolornoColordefaultFill
Long Biascolorcolor.new(color.green, transp=80)longFill
Short Biascolorcolor.new(color.red, transp=80)shortFill
Kint3smoothK
Dint3smoothD
RSI Lengthint21rsiLength
Stoch Lengthint14stochLength
Highfloat90srsiHigh
Lowfloat10srsiLow
ATR Lengthint21atrLength
ATR Multiplierfloat2atrMult
Use ADX for bias?booltrueuseADX
ADX Lengthint14length
ADX Lowfloat30adxLow
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

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 strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers