Strategy · Pine Script v5 · On the chart

Bollinger Bands Strategy

by zhuzp98· code credited to gsanson66

This strategy plots price and Bollinger Bands on the chart using a 120-bar SMA basis and 2 standard deviation multiplier.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code116
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago17 Jan 2025

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

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

Stg_ex_BB.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gsanson66


//This strategy uses the well-known Bollinger Bands Indicator
//@version=5
strategy("BOLLINGER BANDS STRATEGY", shorttitle="BB STRATEGY", overlay=true, initial_capital=1000, default_qty_type=strategy.cash, default_qty_value=950, commission_type=strategy.commission.percent, commission_value=0.18, slippage=3)


//---------------------------------------TOOL TIPS-----------------------------------------//

t1 = "Bollinger Bands length. Corresponds to the SMA length to which we add/substract the standard deviation to create upper and lower bands."
t2 = "Corresponds to the number of standard deviations to be added/subtracted to obtain the two bands. This number can be decimal."
t3 = "The length of the SMA sending the output signals."
t4 = "The maximum percentage of the trade value we can lose. Default is 6%"
t5 = "Each gain or losse (relative to the previous reference) in an amount equal to this fixed ratio will change quantity of orders."
t6 = "The amount of money to be added to or subtracted from orders once the fixed ratio has been reached."


//----------------------------------------FUNCTIONS---------------------------------------//

//@function Displays text passed to `txt` when called.
debugLabel(txt, color) =>
    label.new(bar_index, high, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)

//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)


//---------------------------------------USER INPUTS--------------------------------------//

//Technical parameters
bbLength = input.int(defval=120, minval=1, title="BB Length", group="Technical Parameters", tooltip=t1)
mult = input.float(defval=2, minval=0.1, title="Standard Deviation Multipler", group="Technical Parameters", tooltip=t2)
smaLength = input.int(defval=110, minval=1, title="SMA Exit Signal Length", group="Technical Parameters", tooltip=t3)
slMax = input.float(6, minval=0, title="Max Risk per trade (in %)", group="Risk Management", tooltip=t4)
//Money Management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management", tooltip=t5)
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management", tooltip=t6)
//Backtesting period
startDate = input.time(title="Start Date", defval=timestamp("1 Jan 2017 00:00:00"), group="Backtesting Period")
endDate = input.time(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")


//----------------------------------VARIABLES INITIALISATION-----------------------------//

//Exit
smaExit = ta.sma(close, smaLength)
//BB Calculation
basis = ta.sma(close, bbLength)
dev = mult * ta.stdev(close, bbLength)
upperBB = basis + dev
lowerBB = basis - dev
//Money management
equity = math.abs(strategy.equity - strategy.openprofit)
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95
//Backtesting period
bool inRange = na


//------------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION-------------------------------//

//Checking if the date belong to the range
inRange := inBacktestPeriod(startDate, endDate)

//Checking performances of the strategy
if equity > capital_ref + fixedRatio
    spread = (equity - capital_ref)/fixedRatio
    nb_level = int(spread)
    increasingOrder = nb_level * increasingOrderAmount
    cashOrder := cashOrder + increasingOrder
    capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
    spread = (capital_ref - equity)/fixedRatio
    nb_level = int(spread)
    decreasingOrder = nb_level * increasingOrderAmount
    cashOrder := cashOrder - decreasingOrder
    capital_ref := capital_ref - nb_level*fixedRatio

//Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
    strategy.close_all()
    debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116))


//-----------------------------------EXIT SIGNAL------------------------------//

//SMA Exit Signal
if strategy.position_size > 0 and close < smaExit
    strategy.close("Long")
if strategy.position_size < 0 and close > smaExit
    strategy.close("Short")


//----------------------------------LONG/SHORT CONDITION---------------------------//

//Long Condition
if close > upperBB and strategy.position_size==0 and inRange
    qty = cashOrder/close
    strategy.entry("Long", strategy.long, qty)
    strategy.exit("Exit Long", "Long", stop=close*(1-slMax/100))

//Short Condition
if close < lowerBB and strategy.position_size==0 and inRange
    qty = cashOrder/close
    strategy.entry("Short", strategy.short, qty)
    strategy.exit("Exit Short", "Short", stop=close*(1+slMax/100))


//---------------------------------PLOTTING ELEMENT----------------------------------//

plot(smaExit, color=color.orange)
upperBBPlot = plot(upperBB, color=color.blue)
lowerBBPlot = plot(lowerBB, color=color.blue)
fill(upperBBPlot, lowerBBPlot, title = "Background", color=strategy.position_size>0 ? color.rgb(0, 255, 0, 90) : strategy.position_size<0 ? color.rgb(255, 0, 0, 90) : color.rgb(33, 150, 243, 95))

Overview

Bollinger Bands Strategy generates signals from band touches and an exit SMA of 110 bars. Risk management limits losses to 6 percent of trade value. Money management scales position size by a fixed ratio of 400 and adds 200 per increment. It operates in a backtest window from 2017 to 2024.

Details

Published by

zhuzp98 on GitHub

Code credit

gsanson66, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Moving averages, Volatility & bands

Markets

Crypto

Timeframes

Any timeframe

Risk Notes

  • The strategy can add several entries in the same direction

Settings

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

SettingTypeDefaultVariable
BB Lengthint120bbLength
Standard Deviation Multiplerfloat2mult
SMA Exit Signal Lengthint110smaLength
Max Risk per trade (in %)float6slMax
Fixed Ratio Value ($)int400fixedRatio
Increasing Order Amount ($)int200increasingOrderAmount
Start Datetimetimestamp("1 Jan 2017 00:00:00")startDate
End Datetimetimestamp("1 July 2024 00:00:00")endDate
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

This overlay strategy offers two selectable entry modes: a Bollinger squeeze on typical price and a simple moving-average cross. It filters trades by weekday, session, date range, and an optional news window, and can restrict direction or invert the side. Risk

Strategy v5 Volatility & bandsMoving averages
Updated today · None stated GitHub repository of Boilerplate Configurable Strategy [Yosiet]
257 stars

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

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
219 stars

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

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce
218 stars

The Mean Reversion Strategy Template calculates a baseline mean using SMA, EMA, or VWAP alongside upper and lower deviation bands based on standard deviation, ATR, or percentage offsets. It generates long and short entries when price touches, bounces from, or

Strategy v6 Mean reversionMoving averages
Updated 3 months ago · None stated GitHub repository of Mean Reversion Strategy Template

Bollinger Breakout

by hackingthemarkets
189 stars

This price-chart strategy plots a simple moving average and upper and lower bands built from the standard deviation of close, scaled by separate offset inputs. It enters a fixed quantity long when close crosses above the upper band and a fixed quantity short w

Strategy v4 Volatility & bandsBreakout
Updated 3 years ago · None stated GitHub repository of Bollinger Breakout

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