Skip to content
Home » Scripts » Bollinger Bands Breakout Strategy

Bollinger Bands Breakout Strategy

Are you seeking to master the Bollinger Bands Breakout Strategy? This trading technique, favored by traders worldwide, can help you spot trend changes and breakouts. The strategy uses Bollinger Bands, a tool that John Bollinger developed. It’s an ingenious way to grasp an asset’s volatility and likely price shifts.

Bollinger Bands consist of volatility bands that sit above and below a moving average – often a simple moving average (SMA). These bands draw upon a set number of standard deviations from the moving average to offer insights into possible price movements.

The Bollinger Bands Breakout Strategy focuses on price breakouts above or below these bands. These breakouts can hint at exciting trading opportunities. A price breaking above the upper band might signal a rising trend, while a break below the lower band might suggest a falling trend. Traders can use this info to decide when to enter or exit positions. Many traders combine this with other technical indicators to improve their trading decisions’ accuracy.

In the following code sample, we’ll show you how to put the Bollinger Bands Breakout Strategy into action on the QuantConnect platform using either Python or C#. The comments in the code breakdown the various parts, like initialization, warm-up, and the trading logic based on Bollinger Bands breakouts.

By understanding and applying the Bollinger Bands Breakout Strategy, traders can gain an edge, better forecast market trends, and optimize their trading decisions in volatile markets.

Click on the code to copy it to your clipboard.
Click here for detailed instructions on how to use the scripts in QuantConnect.

Python
from AlgorithmImports import *

# Bollinger Bands Breakout Algorithm
class BollingerBandsBreakout(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2021, 1, 1)
        self.SetEndDate(2021, 12, 31)
        self.SetCash(10000)

        # Add the SPY ETF with daily resolution
        self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol

        # Create Bollinger Bands indicator with a 20-day SMA and 2 standard deviations
        self.bollinger_bands = self.BB(self.symbol, 20, 2, MovingAverageType.Simple, Resolution.Daily)

        # Set a warm-up period to ensure the Bollinger Bands indicator is ready
        self.SetWarmUp(20)

    def OnData(self, data):
        # Skip processing during the warm-up period
        if self.IsWarmingUp:
            return

        # Buy when the price breaks above the upper Bollinger Band
        if not self.Portfolio.Invested and data[self.symbol].Close > self.bollinger_bands.UpperBand.Current.Value:
            self.SetHoldings(self.symbol, 1)
            self.Debug(f"Buy signal at {self.Time}")

        # Sell when the price breaks below the lower Bollinger Band
        elif self.Portfolio.Invested and data[self.symbol].Close < self.bollinger_bands.LowerBand.Current.Value:
            self.Liquidate(self.symbol)
            self.Debug(f"Sell signal at {self.Time}")
C#
using System;
using QuantConnect;
using QuantConnect.Data;
using QuantConnect.Algorithm;
using QuantConnect.Indicators;
namespace Algorithm.CSharp
{
    public class BollingerBandsBreakout : QCAlgorithm
    {
        private Symbol _symbol;
        private BollingerBands _bollingerBands;
        public override void Initialize()
        {
            SetStartDate(2021, 1, 1);
            SetEndDate(2021, 12, 31);
            SetCash(10000);
            // Add the SPY ETF with daily resolution
            _symbol = AddEquity("SPY", Resolution.Daily).Symbol;
            // Create Bollinger Bands indicator with a 20-day SMA and 2 standard deviations
            _bollingerBands = BB(_symbol, 20, 2, MovingAverageType.Simple, Resolution.Daily);
            // Set a warm-up period to ensure the Bollinger Bands indicator is ready
            SetWarmUp(20);
        }
        public override void OnData(Slice data)
        {
            // Skip processing during the warm-up period
            if (IsWarmingUp) return;
            // Buy when the price breaks above the upper Bollinger Band
            if (!Portfolio.Invested && data[_symbol].Close > _bollingerBands.UpperBand.Current.Value)
            {
                SetHoldings(_symbol, 1);
                Debug($"Buy signal at {Time}");
            }
            // Sell when the price breaks below the lower Bollinger Band
            else if (Portfolio.Invested && data[_symbol].Close < _bollingerBands.LowerBand.Current.Value)
            {
                Liquidate(_symbol);
                Debug($"Sell signal at {Time}");
            }
        }
    }
}

 

Learn more about QuantConnect development services at QuantScripts.

Beyond Basic Bollinger Band Breakouts

The standard Bollinger Band breakout strategy triggers when price closes outside the bands. But not all breakouts are equal. A breakout after a period of band contraction (the “squeeze”) is far more significant than one during normal volatility. The bandwidth indicator — (upper band – lower band) / middle band — helps identify these high-probability setups.

Mean reversion traders can flip the strategy: instead of buying breakouts above the upper band, they sell. This works well in ranging markets. The key is identifying the current regime — trending or ranging — before choosing your approach.

Practical Implementation Tips

When coding Bollinger Band strategies, pay attention to the lookback period and standard deviation multiplier. The default 20-period, 2 standard deviation setting captures about 95% of price action. Widening to 2.5 standard deviations reduces false signals but catches fewer moves.

For futures and forex, consider using Bollinger Bands on tick charts or volume charts rather than time-based charts. This normalizes the data across different session periods and can produce cleaner signals, especially during low-liquidity hours.

Combining Bollinger Bands with RSI creates a powerful confirmation system. A buy signal when price touches the lower band AND RSI is below 30 is much more reliable than either signal alone. This dual-confirmation approach is straightforward to code and backtest.

Ready to Automate Your Trading Strategy?

Whether you’re looking to build a new algorithm from scratch or optimize an existing strategy, our team of experienced quant developers can help. Book a free 30-minute consultation to discuss your project and get a custom quote.

Leave a Reply

Your email address will not be published. Required fields are marked *