Strategy · Pine Script v5 · On the chart

Bollinger Bands

by Web3Degenerate

This Pine Script converts a Bollinger Band Breakout indicator into a strategy.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code95
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 2024

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

95 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/13.Bollinger-Bands-Strategy-Example.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

13.Bollinger-Bands-Strategy-Example.pine
//Demonstrates how to convert the 5.Indicators/15.Bollinger-Bands-Breakouts.pin "Bollinger Band Breakout Indicator" into a strategy script, and explains some of the limitations of the TradingView Strategy Tester when it comes to robust portfolio testing.

///The Strategy Tester is a great tool and can be used to create backtesting scripts extremely quickly and efficiently especially for limited market strategies such as forex and commodities and small stock portfolios, but the price we pay for that convenience is the lack of powerful features that the Strategy Tester has to offer.

////Hopefully in the future the TradingView developers will expand on the tester and make multiple market testing possible. But for now just be aware that if you're developing a strategy to be traded across dozens or hundreds of markets (such as a universe of stocks in the S&P500 for example), testing it properly can be difficult to achieve with Pine.

//For advanced system testing and trading, other languages such as AFL (https://www.amibroker.com/guide/AFL.html) or Python might be more suitable if you want to build complex strategies and/or perform advanced backtesting such as automatic optimizations and Monte Carlo simulations etc. Pine Script is much better suited for creating trading tools to assist in your trading, rather than advanced fully-automated trading systems that trade hundreds or thousands of markets.

//Update 20th June 2023: The security function call changed to reflect the latest 'best practice' for non-repainting code as mentioned in the TradingView documentation. Also removed 'when=' parameters from the strategy functions where they were mentioned as that parameter is now deprecated and unnecessary. (https://www.tradingview.com/pine-script-docs/en/v5/concepts/Repainting.html#repainting-request-security-calls)


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

// @version=5
strategy("Bollinger Bands", overlay=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=20)

// Get user input
var g_bb        = "Bollinger Band Settings"
upperBandSD     = input.float(title="Upper Band Std Dev", defval=3.0, tooltip="Upper band's standard deviation multiplier", group=g_bb)
lowerBandSD     = input.float(title="Lower Band Std Dev", defval=1.0, tooltip="Lower band's standard deviation multiplier", group=g_bb)
maPeriod        = input.int(title="Middle Band MA Length", defval=100, tooltip="Middle band's SMA period length", group=g_bb)
var g_tester    = "Backtester Settings"
drawTester      = input.bool(title="Draw Backtester", defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")
var g_rf        = "Regime Filter Settings"
useRegime       = input.bool(title="Use Regime Filter", defval=true, group=g_rf)
res             = input.timeframe(title="Timeframe", defval="D", group=g_rf)
len             = input.int(title="EMA Length", defval=20, group=g_rf)
market          = input.symbol(title="Market", defval="BATS:SPY", group=g_rf)

// Define custom security function
f_sec(_market, _res, _exp) => request.security(_market, _res, _exp[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]

// Get EMA value
ema = ta.ema(close, len)
emaValue = f_sec(market, res, ema)

// Check if price is above or below EMA filter
marketPrice = f_sec(market, res, close)
regimeFilter = not useRegime or marketPrice > emaValue

// Change background color
plotshape(useRegime, style=shape.square, size=size.normal, location=location.bottom, color=regimeFilter ? color.green : color.red, title="Regime Filter")

// Get Bollinger Bands
[bbIgnore1, bbHigh, bbIgnore2] = ta.bb(close, maPeriod, upperBandSD)
[bbMid, bbIgnore3, bbLow]      = ta.bb(close, maPeriod, lowerBandSD)

// Prepare trade persistent variables
drawEntry   = false
drawExit    = false

// Detect bollinger breakout
if close > bbHigh and barstate.isconfirmed and strategy.position_size == 0 and regimeFilter
    drawEntry := true
    strategy.entry(id="Trade", direction=strategy.long)
    alert("Bollinger Breakout Detected for " + syminfo.ticker, alert.freq_once_per_bar_close)

// Detect bollinger sell signal
if close < bbLow and barstate.isconfirmed and strategy.position_size != 0
    drawExit := true
    strategy.close(id="Trade")
    alert("Bollinger Exit detected for " + syminfo.ticker, alert.freq_once_per_bar_close)

// Draw bollinger bands
plot(bbMid, color=color.blue, title="Middle SMA")
plot(bbHigh, color=color.green, title="Upper Band")
plot(bbLow, color=color.red, title="Lower Band")

// Draw signals
plotshape(drawEntry, style=shape.triangleup, color=color.green, location=location.belowbar, size=size.normal, title="Buy Signal")
plotshape(drawExit, style=shape.xcross, color=color.red, location=location.belowbar, size=size.normal, title="Sell Signal")

// =============================================================================
// START BACKTEST CODE
// =============================================================================

// Prepare stats table
var table testTable = table.new(position.top_right, 2, 2, border_width=1)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
    _cellText = _title + "\n" + _value
    table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)

// Draw stats table
var bgcolor = color.black
if barstate.islastconfirmedhistory
    if drawTester
        dollarReturn = strategy.equity - strategy.initial_capital
        f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
        f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(strategy.wintrades / strategy.closedtrades * 100, "##.##") + "%", bgcolor, color.white)
        f_fillCell(testTable, 1, 0, "Equity:", "$" + str.tostring(strategy.equity, "###,###.##"), bgcolor, color.white)
        f_fillCell(testTable, 1, 1, "Return:", str.tostring((strategy.netprofit / strategy.initial_capital) * 100, "##.##") + "%", dollarReturn > 0 ? color.green : color.red, color.white)

// =============================================================================
// END BACKTEST CODE
// =============================================================================

Overview

Bollinger Bands plots Bollinger Bands on the price chart using a 100-period SMA as the middle band with upper deviation of 3 and lower deviation of 1. Signals trigger on price crossing the bands after filtering by a regime indicator based on a 20-period EMA. The strategy overlays on the chart and uses percent of equity position sizing. Main settings allow adjustment of band deviations, middle band length, backtester display, regime filter enablement, timeframe, EMA length, and market symbol. The script notes limitations of the TradingView Strategy Tester for multi-market portfolio testing.

Details

Published by

Web3Degenerate on GitHub

Draws

On the price chart

Markets

Stocks

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
Upper Band Std Devfloat3.0upperBandSD
Lower Band Std Devfloat1.0lowerBandSD
Middle Band MA Lengthint100maPeriod
Draw BacktesterbooltruedrawTester
Use Regime FilterbooltrueuseRegime
TimeframetimeframeDres
EMA Lengthint20len
MarketsymbolBATS:SPYmarket
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

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
106 stars

This strategy runs on the price chart and enters long when a fast simple moving average crosses above a slow one, and short on the opposite cross, while closing the other side. Entries also need ATR above a filter, a pullback check, a minimum candle-body chang

Strategy v5 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 9:22 5 MIN 15 MIN BANKNIFTY

均线突破交易系统

by tangly1024
76 stars

This strategy trades long breakouts of a fast and a slow moving average on the price chart. It opens a long position when price crosses above either average, using a percentage of equity as size. It reduces the position by a set share when the high reaches the

Strategy v5 TrendMoving averages
Updated 5 months ago · None stated GitHub repository of 均线突破交易系统

Bollinger bands examples

by tradingstrategy-ai
53 stars

This strategy plots exponential-moving-average Bollinger bands on the price chart and calculates RSI. It opens a long position when close crosses above the upper band while RSI is at or above a threshold, the date filter allows trading, and no position is open

Strategy v5 Volatility & bandsOscillators & momentum
Updated 3 years ago · None stated GitHub repository of Bollinger bands examples

Keltner Channels Strategy

by TWODS-CAPITAL
37 stars

This strategy builds Keltner-style bands around an exponential or simple moving average of the chosen source. Band width uses average true range, raw true range, or a smoothed high-low range, scaled by a multiplier. When the source crosses above the upper band

Strategy v5 Volatility & bandsBreakout
Updated 3 years ago · MIT GitHub repository of Keltner Channels Strategy
16 stars

This strategy plots Donchian channels, trailing stops, and profit targets directly on the price chart. It enters breakout trades using a 55-bar Donchian channel and sizes positions according to an ATR-based risk percentage per unit. The system adds units as pr

Strategy v6 TrendBreakout
Updated 12 months ago · None stated GitHub repository of Seykota Alt 10: Profit Targets

More Volatility & bands scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers