Strategy · Pine Script v5 · On the chart

Bollinger Band Strategy

by might-tree

The Bollinger Band Strategy is a mean-reversion trading strategy designed to trade bounces off Bollinger Bands.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code88
Settings4inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago2 Aug 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

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

Bollinger_Band_Strategy.pine
//Run the following Script on PINE EDITOR or any platform supporting Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © might-tree

//@version=5
strategy("Bollinger Band Strategy", overlay=true, margin_long=100, margin_short=100)

start_time = input.time(timestamp("20 Jul 2020 00:00 +0300"), "Strategy Start Date")
exit_time = input.time(timestamp("20 Jul 2023 00:00 +0300"), "Strategy Exit Date")

in_period = time>=timestamp("20 Jul 2022 00:00 +0300") and time<=timestamp("20 Jul 2023 00:00 +0300")


bb_length = input.int(20)
bb_mult = input.int(2)

[middle, upper, lower] = ta.bb(close,bb_length, bb_mult)
plot(middle, color=color.rgb(228, 231, 75))
plot(upper, color=color.rgb(0, 255, 34))
plot(lower, color=color.rgb(255, 0, 85))
long_cond = ta.crossover(close,lower)
short_cond = ta.crossunder(close,upper)

var saved_ph = 0.0
if strategy.opentrades>0 and strategy.opentrades[1]==0 and strategy.position_size > 0
    saved_ph := upper[1]
var saved_pl = 0.0
if strategy.opentrades>0 and strategy.opentrades[1]==0 and strategy.position_size < 0
    saved_pl := lower[1]

avg = strategy.position_avg_price

long_diff = saved_ph-avg
short_diff = saved_pl-avg

long_stoploss = avg - 1*long_diff
short_stoploss = avg - 1*short_diff

long_avgdown = avg - 0.5*long_diff
short_avgup = avg - 0.5*short_diff

long_profit_price = avg + 0.5*long_diff
short_profit_price = avg + 0.5*short_diff

var label _label = na
if in_period
    if long_cond and strategy.opentrades==0
        strategy.entry("Long",strategy.long)
    if long_cond and strategy.opentrades >0 and (close[1]<long_avgdown or close[2]<long_avgdown)
        strategy.entry("Long",strategy.long)

    if short_cond and strategy.opentrades==0
        strategy.entry("Short", strategy.short)
    if short_cond and strategy.opentrades>0 and (close[1]>short_avgup or close[2]>short_avgup)
        strategy.entry("Short",strategy.short)

plot(avg, style=plot.style_linebr)


plot(strategy.position_size > 0? long_profit_price: na,color=color.green, style=plot.style_linebr)
plot(strategy.position_size > 0? long_avgdown: na,color=color.rgb(177, 255, 59), style=plot.style_linebr)
plot(strategy.position_size > 0? long_stoploss: na,color=color.rgb(82, 255, 192), style=plot.style_linebr)

plot(strategy.position_size < 0? short_profit_price: na,color=color.rgb(243, 255, 74), style=plot.style_linebr)
plot(strategy.position_size < 0? short_avgup: na,color=color.rgb(248, 190, 97), style=plot.style_linebr)
plot(strategy.position_size < 0? short_stoploss: na,color=color.rgb(255, 0, 0), style=plot.style_linebr)

var co = false
if strategy.position_size > 0 and ta.crossover(close, middle)
    co := true
var cu = false
if strategy.position_size < 0 and ta.crossunder(close, middle)
    cu := true
if strategy.opentrades == 0
    co := false
    cu := false

if strategy.position_size > 0
    if co
        strategy.exit("Long Exit", "Long", limit=long_profit_price, stop=middle)
    else
        strategy.exit("Long Exit", "Long", limit=long_profit_price, stop=long_stoploss)
if strategy.position_size < 0
    if cu
        strategy.exit("Short Exit", "Short", limit=short_profit_price, stop=middle)
    else
        strategy.exit("Short Exit", "Short", limit=short_profit_price, stop=short_stoploss)

Overview

Bollinger Band Strategy enters long positions when the closing price crosses above the lower band and short positions when it crosses below the upper band. Upon entry, the script sets dynamic take-profit, stop-loss, and position-averaging levels based on band width. Once price crosses the middle band, stop losses adjust to lock in risk management. Inputs allow users to adjust Bollinger Band length, standard deviation multiplier, and backtesting date ranges.

Details

Published by

might-tree on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Mean reversion

Markets

Any symbol

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
Strategy Start Datetimetimestamp("20 Jul 2020 00:00 +0300")start_time
Strategy Exit Datetimetimestamp("20 Jul 2023 00:00 +0300")exit_time
bb_lengthint20bb_length
bb_multint2bb_mult
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

330 stars

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [Alorse]
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
106 stars

This strategy backtests a long Bollinger Band deal on the price chart for 3Commas-style bots. It plots short and long simple moving averages, offset bands, and the average entry price of the open deal. A long starts when price crosses the lower band inside a c

Strategy v4 Volatility & bandsMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 3Commas Bollinger Strategy

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy
104 stars

This strategy combines Bollinger Bands with a short RSI to fade moves that leave the bands and then return. A long requires the prior bar below the lower band and oversold, then a close back inside the band while RSI is between 30 and 50. Shorts mirror that at

Strategy v5 Oscillators & momentumVolatility & bands
Updated 3 years ago · MIT GitHub repository of Bollinger Bands and RSI Strategy
37 stars

This strategy plots Bollinger Bands on the price chart using a simple moving average and a multiple of standard deviation. It places a long stop entry when close crosses above the lower band and a short stop entry when close crosses below the upper band. Pendi

Strategy v5 Volatility & bandsMean reversion
Updated 3 years ago · MIT GitHub repository of Bollinger Bands Strategy directed

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