Strategy · Pine Script v5 · On the chart

12-BB

by sam30606

This overlay strategy combines a Bollinger-style band with separate ATR upper and lower envelopes and optional ADX, Volume Flow Indicator, and RSI filters.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code321
Settings40inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago30 Mar 2023

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

321 lines of Pine Script v5 from BB.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

BB.pinescript
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sam30606

//@version=5
// # ========================================================================= #
// #                   |   STRATEGY  |
// # ========================================================================= #
strategy("12-BB", shorttitle="12-BB", overlay=true , default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000)

// # ========================================================================= #
// #                   |   STRATEGY  |
// # ========================================================================= #

// # ========================================================================= #
// #                   |   Average Directional Index  |
// # ========================================================================= #
var groupADX = "Average Directional Index Settings"

enableADX = input.bool(1, title = "Enable ADX?", group = groupADX) 
timeADX = input.timeframe('5', "Timeframe", group=groupADX)
lenADX = input(10, title="ADX Smoothing", group=groupADX)
lenDI = input(10, title="DI Length", group=groupADX)
lowestADX = input.float(30, title='ADX Lowest', step = 0.1, group=groupADX)

dirmov(_len) =>
    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)
    truerange = ta.rma(ta.tr, _len)
    plus = fixnan(100 * ta.rma(plusDM, _len) / truerange)
    minus = fixnan(100 * ta.rma(minusDM, _len) / truerange)
    [plus, minus]
adx(lenDI, lenADX) =>
    [plus, minus] = dirmov(lenDI)
    sum = plus + minus
    adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lenADX)
sig = request.security(syminfo.tickerid, timeADX, adx(lenDI, lenADX))
// # ========================================================================= #
// #                   |   Average Directional Index  |
// # ========================================================================= #

// # ========================================================================= #
// #                   |   Volume Flow Indicator [LazyBear]  |
// # ========================================================================= #
// @author LazyBear
var groupVFI = "Volume Flow Indicator Settings"

enableVFI = input.bool(1, title = "Enable VFI?", group = groupVFI) 
lengthVFI = input(130, title='VFI length', group = groupVFI)
coef = input(1, group = groupVFI)
vcoef = input(3.4, title='Max. vol. cutoff', group = groupVFI)
smoothVFI = input(false, group = groupVFI)

VFIma(x, y) =>
    sma_1 = ta.sma(x, y)
    smoothVFI ? sma_1 : x

typical = hlc3
inter = math.log(typical) - math.log(typical[1])
vinter = ta.stdev(inter, 30)
cutoff = coef * vinter * close
vave = ta.sma(volume, lengthVFI)[1]
vmax = vave * vcoef
vc = volume < vmax ? volume : vmax  //min( volume, vmax )
mf = typical - typical[1]
iff_1 = mf < -cutoff ? -vc : 0
vcp = mf > cutoff ? vc : iff_1

vfi = VFIma(math.sum(vcp, lengthVFI) / vave, 3)

//plot(vfi, title='vfi', color=color.new(color.green, 0), linewidth=2)
// # ========================================================================= #
// #                   |   Volume Flow Indicator [LazyBear]  |
// # ========================================================================= #
// # ========================================================================= #
// #                   |   RSI  |
// # ========================================================================= #

var groupRSI = "RSI Settings"
enableRSI = input.bool(1, title = "Enable RSI?", group = groupRSI) 
rsiMa(source, length, type) =>
    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)

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

up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
//rsiMA = rsiMa(rsi, maLengthInput, maTypeInput)
//isBB = maTypeInput == "Bollinger Bands"

//plot(rsi, "RSI", color=#7E57C2)
//plot(rsiMA, "RSI-based MA", color=color.yellow)
//rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
//hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
//rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
//fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
//bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green)
//bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green)
//fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill")

// # ========================================================================= #
// #                   |   RSI  |
// # ========================================================================= #
// # ========================================================================= #
// #                   |   ATR Bands  |
// # ========================================================================= #
var groupATR = "ATR Bands Settings"

// Inputs
atrPeriod = input.int(title='ATR Period', defval=14, minval=1, group = groupATR)
srcUpper = input(title='Source Upper', defval=close, inline = "ATRSource", group = groupATR)
srcLower = input(title='Source Lower', defval=close, inline = "ATRSource",group = groupATR)
atrMultiplierUpper = input.float(title='ATR Multiplier Upper', defval=3, inline = "ATRMult",group = groupATR)
atrMultiplierLower = input.float(title='ATR Multiplier Lower', defval=3, inline = "ATRMult",group = groupATR)

// ATR
atr = ta.atr(atrPeriod)


// # ========================================================================= #
// #                   |   ATR Bands  |
// # ========================================================================= #

// # ========================================================================= #
// #                   |   BB  |
// # ========================================================================= #
var groupBB = "BB Settings"

source = input(defval=high, title="Source", group = groupBB)
length = input.int(20, minval=1, group = groupBB)
mult = input.float(2.0, minval=0.001, maxval=50, group = groupBB)
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
upper = basis + dev
lower = basis - dev



buyBB = ta.crossover(source, upper)
sellBB = ta.crossunder(source, lower)
// # ========================================================================= #
// #                   |   BB  |
// # ========================================================================= #


var entryPrice = 0.0
var priceLimit = 0.0
var priceStop = 0.0
var tradeDay = false
var groupBackTest ="Back Test Settings"
var time_now = 0
var orderQty = 0.0
fromYear = input.int(defval=2000, title='From Year', minval=2000, inline = "BTFrom", group=groupBackTest)
fromMomth = input.int(defval=1, title='From Month', minval=1, maxval=12, inline = "BTFrom", group=groupBackTest)
fromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, inline = "BTFrom", group=groupBackTest)
toYear = input.int(defval=2300, title='To Year', minval=2020, inline = "BTTo", group=groupBackTest)
toMomth = input.int(defval=1, title='To Month', minval=1, maxval=12, inline = "BTTo", group=groupBackTest)
toDay = input.int(defval=1, title='To Day', minval=1, maxval=31, inline = "BTTo", group=groupBackTest)
timeStart = timestamp(fromYear, fromMomth, fromDay, 00, 00)
timeFinish = timestamp(toYear, toMomth, toDay, 23, 59)
window()=>time>=timeStart and time <= timeFinish ? true : false

var groupTrade = "Trade Settings"

buySLMeth = input.session(defval = "%", title = "Buy Stop Loss Method", options = ["%", "ATR", "tick"], inline = "BuySL", group = groupTrade) 
sellSLMeth = input.session(defval = "%", title = "Sell Stop Loss Method", options = ["%", "ATR", "tick"], inline = "SellSL", group = groupTrade)
buyTPMeth = input.session(defval = "R/R", title = "Buy Take Profit Method", options = ["%", "ATR", "tick", "R/R"], inline = "BuyTP", group = groupTrade) 
sellTPMeth = input.session(defval = "R/R", title = "Sell Take Profit Method", options = ["%", "ATR", "tick", "R/R"], inline = "SellTP", group = groupTrade)

buySLPer = input.float(defval = 0.01 , title = "Buy Stop Loss %", minval = 0 , step = 0.01 , inline = "BuySL", group = groupTrade)
sellSLPer = input.float(defval = 0.01 , title = "Sell Stop Loss %", minval = 0 , step = 0.01 , inline = "SellSL", group = groupTrade)
buyTPPer = input.float(defval = 0.01 , title = "Buy Take Progit %", minval = 0 , step = 0.01 , inline = "BuyTP", group = groupTrade)
sellTPPer = input.float(defval = 0.01 , title = "Sell Take Progit %", minval = 0 , step = 0.01 , inline = "SellTP", group = groupTrade)

ratioRR = input.float(3, title='R/R Ratio', step = 0.1, group=groupTrade)

leverage = input.float(200, title='Leverage', step = 0.1, group=groupTrade)
orderPerc = input.float(10, title='Order%', step = 0.1, group=groupTrade)/100

buyTrade = input.bool(defval = true, title = "BuyTrade",  group = groupTrade) 
sellTrade = input.bool(defval = true, title = "SellTrade",  group = groupTrade) 

dd1 = input.bool(0, title='Sun',inline = "tradeDay", group=groupTrade)
dd2 = input.bool(1, title='Mon', inline = "tradeDay", group=groupTrade)
dd3 = input.bool(1, title='Tues', inline = "tradeDay", group=groupTrade)
dd4 = input.bool(1, title='Wed', inline = "tradeDay", group=groupTrade)
dd5 = input.bool(1, title='Thur', inline = "tradeDay", group=groupTrade)
dd6 = input.bool(1, title='Fri', inline = "tradeDay", group=groupTrade)
dd7 = input.bool(0, title='Sat', inline = "tradeDay", group=groupTrade)

dayweek = dayofweek(time = time, timezone = 'America/New_York' )

tradeDay := switch dayweek
    1 => dd1
    2 => dd2
    3 => dd3
    4 => dd4
    5 => dd5
    6 => dd6
    7 => dd7
    => false



passADX = enableADX ? sig > lowestADX : true

buyVFI = enableVFI ? vfi > 0 : true
sellVFI = enableVFI ? vfi   < 0 : true

buyRSI = enableRSI ? rsi > 75 : true
sellRSI = enableRSI ? rsi < 25  : true
//buyRSI = enableRSI ? rsi > 75 ? rsi[1] > 75 : false : true
//sellRSI = enableRSI ? rsi < 25 ? rsi[1] < 25 : false : true

buyfilters = passADX and buyVFI and buyRSI and tradeDay and buyTrade
sellfilters = passADX and sellVFI and sellRSI and tradeDay and sellTrade

// you can set your own logic here

buyCondition = buyfilters and strategy.position_size == 0 and buyBB
sellCondition = sellfilters and strategy.position_size == 0 and sellBB

if (strategy.position_size == 0)
    entryPrice := 0.0
    priceLimit := 0.0
    priceStop := 0.0
    time_now := 0
    orderQty:=0
// you can set your own logic here
if(window())
    if (buyCondition)

        entryPrice := close
        time_now := timenow
        orderQty:=strategy.equity/entryPrice*leverage*orderPerc

        priceStop := switch buySLMeth
            "%" => entryPrice * (1 - buySLPer / 100)
            "ATR" => srcLower - atr * atrMultiplierLower
            "tick" => entryPrice - (syminfo.mintick * buySLPer)
        priceStop := math.round_to_mintick(priceStop)
        
        priceLimit := switch buyTPMeth
            "%" => entryPrice * (1 + buyTPPer / 100)
            "ATR" => srcUpper + atr * atrMultiplierUpper
            "tick" => entryPrice + (syminfo.mintick * buyTPPer)
            "R/R" => entryPrice + (entryPrice - priceStop) * ratioRR 
        priceLimit := math.round_to_mintick(priceLimit)
        
        strategy.entry('Buy', strategy.long, qty = orderQty, alert_message = "buy")
        strategy.exit("Buy", limit=priceLimit, stop=priceStop, comment_profit="Buy_profit", comment_loss="Buy_loss", alert_message = "close")
    if (sellCondition)

        entryPrice := close
        time_now := timenow
        orderQty:=strategy.equity/entryPrice*leverage*orderPerc

        priceStop := switch sellSLMeth
            "%" => entryPrice * (1 + sellSLPer / 100)
            "ATR" => srcUpper + atr * atrMultiplierUpper
            "tick" => entryPrice + (syminfo.mintick * sellSLPer)
        priceStop := math.round_to_mintick(priceStop)

        priceLimit := switch sellTPMeth
            "%" => entryPrice * (1 - sellTPPer / 100)
            "ATR" => srcLower - atr * atrMultiplierLower
            "tick" => entryPrice - (syminfo.mintick * sellTPPer)
            "R/R" => entryPrice - (priceStop - entryPrice) * ratioRR
        priceLimit := math.round_to_mintick(priceLimit)

        strategy.entry('Sell', strategy.short, qty = orderQty, alert_message = "sell")
        strategy.exit("Sell",limit=priceLimit, stop=priceStop, comment_profit="Sell_profit", comment_loss="Sell_loss", alert_message = "close")
        

// # ========================================================================= #
// #                   |   Print  |
// # ========================================================================= #

plotchar(entryPrice, "entryPrice", "", location = location.top)
plotchar(priceLimit, "priceLimit", "", location = location.top)
plotchar(priceStop, "priceStop", "", location = location.top)
plotchar(leverage, "leverage", "", location = location.top)
plotchar(orderPerc, "orderPerc", "", location = location.top)
plotchar(time_now, "timenow", "", location = location.top)

plotchar(buyCondition, "buyCondition", "", location = location.top)
plotchar(sellCondition, "sellCondition", "", location = location.top)


plotchar(buyBB, "buyBB", "", location = location.top)
plotchar(sellBB, "sellBB", "", location = location.top)
plotchar(passADX, "passADX", "", location = location.top)
plotchar(buyVFI, "buyVFI", "", location = location.top)
plotchar(sellVFI, "sellVFI", "", location = location.top)
plotchar(buyRSI, "buyRSI", "", location = location.top)
plotchar(sellRSI, "sellRSI", "", location = location.top)
plotchar(buyfilters, "buyfilters", "", location = location.top)
plotchar(sellfilters, "sellfilters", "", location = location.top)
plotchar(tradeDay, "tradeDay", "", location = location.top)
plotchar(dayofweek(time = time, timezone = 'America/New_York' ) , "dayofweek(time = dayofweek, timezone = 'America/New_York' ) ", "", location = location.top)
plotchar(syminfo.mintick, "mintick", "", location = location.top)

// Plotting
plot(srcUpper + atr * atrMultiplierUpper, color=color.new(color.green, 0))
plot(srcLower - atr * atrMultiplierLower, color=color.new(color.red, 0))

p1 = plot(upper, "Upper", color=#2962FF)
p2 = plot(lower, "Lower", color=#2962FF)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))

Overview

12-BB sizes positions as a percentage of equity. Settings change band length and multiplier, ATR periods and multipliers, ADX timeframe and minimum level, VFI length and volume cutoff, RSI length and source, and the backtest date window. Stop and take-profit inputs default to a percentage method and a risk-reward method. The excerpt does not show the order conditions.

Details

Published by

sam30606 on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Oscillators & momentum, Volatility & bands, Volume

Markets

Any symbol

Timeframes

Any timeframe

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
Enable ADX?bool1enableADX
Timeframetimeframe5timeADX
ADX Smoothingint10lenADX
DI Lengthint10lenDI
ADX Lowestfloat30lowestADX
Enable VFI?bool1enableVFI
VFI lengthint130lengthVFI
coefint1coef
Max. vol. cutofffloat3.4vcoef
smoothVFIboolfalsesmoothVFI
Enable RSI?bool1enableRSI
RSI Lengthint14rsiLengthInput
Show all 40 settings
SettingTypeDefaultVariable
SourcesourceclosersiSourceInput
ATR Periodint14atrPeriod
Source UppersourceclosesrcUpper
Source LowersourceclosesrcLower
ATR Multiplier Upperfloat3atrMultiplierUpper
ATR Multiplier Lowerfloat3atrMultiplierLower
Sourcesourcehighsource
lengthint20length
multfloat2.0mult
From Yearint2000fromYear
From Monthint1fromMomth
From Dayint1fromDay
To Yearint2300toYear
To Monthint1toMomth
To Dayint1toDay
Buy Stop Loss Methodsession%buySLMeth
Sell Stop Loss Methodsession%sellSLMeth
Buy Take Profit MethodsessionR/RbuyTPMeth
Sell Take Profit MethodsessionR/RsellTPMeth
Buy Stop Loss %float0.01buySLPer
Sell Stop Loss %float0.01sellSLPer
Buy Take Progit %float0.01buyTPPer
Sell Take Progit %float0.01sellTPPer
R/R Ratiofloat3ratioRR
Leveragefloat200leverage
Order%float10orderPerc
BuyTradebooltruebuyTrade
SellTradebooltruesellTrade
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

6 stars

Capital41 Fusion Core Strategy is an overlay trading strategy that combines an exponential moving average trend filter, RSI, Williams %R, and volume/ATR expansion into a composite momentum oscillator. It executes long trades when the smoothed oscillator crosse

Strategy v6 TrendOscillators & momentum
Updated 8 weeks ago · MIT GitHub repository of Capital41 Fusion Core Strategy

This strategy executes trades on gold based on a confluence of Supertrend, RSI, MACD, Bollinger Bands, and volume spikes. It enters long or short positions when trend direction aligns with momentum and price positioning relative to volatility bands, filtered b

Strategy v6 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of XAUUSD High Probability Strategy

Parabolic SAR

by g-moe
3 stars

This strategy overlays a smoothed moving average on price and combines it with Aroon, Chaikin Money Flow and a Chaikin oscillator to define long and short conditions. Relative Vigor Index and Parabolic SAR values are calculated for exits. Entries can be limite

Strategy v5 TrendOscillators & momentum
Updated 5 months ago · None stated GitHub repository of Parabolic SAR
2 stars

This strategy calculates MACD, ADX trend strength, ATR, and a rolling VWAP resetting at fixed bar intervals. It plots the VWAP line, stop loss levels, and profit targets directly on the price chart. Long positions enter when MACD crosses above its signal line

Strategy v5 TrendOscillators & momentum Repaints
Updated 8 months ago · MIT GitHub repository of MACD & VWAP Strategy with ATR SL/Targets

This strategy generates trade entries by combining up to five normalized 0-100 technical indicators: Relative Strength Index (RSI with divergence detection), Stochastic RSI, Money Flow Index (MFI), Relative Volatility Index (RVI), and Average Directional Index

Strategy v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of TLC 0TO100 Five Indicators Strategy

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