Strategy · Pine Script v5 · On the chart

Bollinger Band Trend Follow Strategy

by imzeeshan

This trend-following strategy calculates asymmetric Bollinger Bands and overlays them on the price chart alongside a central moving average.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code68
Settings10inputs
LicenceMIT
Last update2 years ago8 Jul 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

68 lines of Pine Script v5 from strategies/trend-follow/BollingerBandTrendFollow/scripts/BollingerBandTrendFollowStrategy.pinescript, published under MIT. Keep the author's credit and licence lines when you reuse it.

BollingerBandTrendFollowStrategy.pinescript
//@version=5
//@Author: @GeorgeFreelanceDeveloper, @LucyFreelanceDeveloper
strategy("Boillinger Band Trend Follow strategy", overlay=true, margin_long = 10, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// ********************************
// User defined inputs
// ********************************
var G_BASIC_SETTINGS = "Basic settings"
var G_FILTER_SETTINGS = "Filter settings"
var G_TIME = "Time settings"

length = input.int(defval = 20, title = "Length", group = G_BASIC_SETTINGS)
multiplierUpper = input.int(defval = 1, title = "Upper", step = 1, group = G_BASIC_SETTINGS)
multiplierLower = input.float(defval = 0.5, title = "Lower", step = 1, group = G_BASIC_SETTINGS)

riskPercentage = input.float(defval = 1.00, title = "Risk per trade", step = 0.01, group = G_BASIC_SETTINGS)
atrMultiplier = input.int(defval = 2, title = "ATR multiplier", group = G_BASIC_SETTINGS)
atrLength = input.int(defval = 20, title = "ATR length", group = G_BASIC_SETTINGS)

enableFilter = input.bool(defval = false, title = "Use filter", tooltip = "Filter is close price is above 200 day simple moving average of benchmark", group=G_FILTER_SETTINGS)
benchmarkSymbol = input.symbol(defval = "SPX", title = "Benchmark symbol", group=G_FILTER_SETTINGS)

fromDateTime = input.time(defval = timestamp("1900-01-01T01:01+0000"), title = "From Date and time", group = G_TIME) 
toDateTime = input.time(defval = timestamp("9999-01-01T01:01+0000"), title = "To Date and time", group = G_TIME)


// ********************************
// Functions
// ********************************
tradeDateIsAllowed() => time >= fromDateTime and time <= toDateTime

// **********************************
// Perform calculations and analysis
// **********************************

// Boillinger Bands
centralMA = ta.sma(close, length)
upperBand = ta.sma(close, length) + multiplierUpper * ta.stdev(close, length)
lowerBand = ta.sma(close, length) - multiplierLower * ta.stdev(close, length)

// Filters
benchmarkSymbolClose = request.security(benchmarkSymbol,"1D", close)
filter = enableFilter ? benchmarkSymbolClose[1] >= ta.sma(source = benchmarkSymbolClose, length = 200) : true

// Trade amount
qty = ((riskPercentage/100)*strategy.equity) / (atrMultiplier * ta.atr(atrLength))

buyCondition = ta.crossover(close, upperBand) and tradeDateIsAllowed() and filter
sellCondition = ta.crossunder(close, lowerBand) and tradeDateIsAllowed()

// ********************************
// Draw outputs
// ********************************
plot(centralMA, color = color.blue, linewidth = 2, title = "Central Moving Average")
plot(upperBand, color = color.red, linewidth = 2, title = "Upper Bollinger Band")
plot(lowerBand, color = color.green, linewidth = 2, title = "Lower Bollinger Band")

// ********************************
// Manage trade
// ********************************

// Entry
if (buyCondition) 
    strategy.entry("Long", strategy.long, qty = qty)

// Exit
if (sellCondition)
    strategy.close("Long")

Overview

Bollinger Band Trend Follow Strategy enters long positions when the price crosses above the upper band, provided an optional benchmark trend filter (checking if a symbol like SPX is above its 200-day moving average) is active. Position sizes are calculated dynamically using an ATR-based risk allocation formula. Long positions are closed when the price crosses below the lower band. The strategy lacks a strict stop-loss order, relying solely on band crossovers for exits.

Details

Published by

imzeeshan on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Volatility & bands, Moving averages

Markets

Stocks, Indices

Timeframes

M15-H1, H4 and above

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
Lengthint20length
Upperint1multiplierUpper
Lowerfloat0.5multiplierLower
Risk per tradefloat1.00riskPercentage
ATR multiplierint2atrMultiplier
ATR lengthint20atrLength
Use filterboolfalseenableFilter
Benchmark symbolsymbolSPXbenchmarkSymbol
From Date and timetimetimestamp("1900-01-01T01:01+0000")fromDateTime
To Date and timetimetimestamp("9999-01-01T01:01+0000")toDateTime
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 mean-reversion strategy plots Bollinger Bands and a long-term moving average directly on the price chart. It enters trades when price candles penetrate the outer Bollinger Bands beyond a user-defined body percentage, anticipating a price reversal. Entries

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner PRO [Alorse]
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
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

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 overlay strategy combines a Chandelier Exit with a zero-lag least squares moving average. Although the header mentions Heikin Ashi candles, the calculations use ordinary closes. An ATR trailing stop sets long and short levels, and direction flips when pri

Strategy v5 TrendMoving averages
Updated 3 years ago · MIT GitHub repository of Chandelier Exit & ZLSMA 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