Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-bollinger-bands

$ Pine Script Bollinger Bands

Master these dynamic volatility envelopes in TradingView's Pine Script for identifying overbought/oversold conditions, potential trend reversals, and market volatility shifts.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

What are Bollinger Bands?

Bollinger Bands (BB) are a widely popular and versatile technical analysis indicator developed by John Bollinger. They consist of three lines:

  1. A Middle Band: Typically a 20-period Simple Moving Average (SMA) of the price.
  2. An Upper Band: Plotted a certain number of standard deviations (typically 2) above the Middle Band.
  3. A Lower Band: Plotted the same number of standard deviations below the Middle Band.
02

Components and Calculation

The calculation of Bollinger Bands involves a Simple Moving Average (SMA) and Standard Deviation (StdDev) of price:

  1. Middle Band: A Simple Moving Average of the `close` price over a specified `length` (e.g., 20 periods).
    Middle Band = SMA(close, length)
  2. Standard Deviation: Calculate the standard deviation of the `close` price over the same `length`.
    StdDev = ta.stdev(close, length)
  3. Upper Band: Add a multiple of the standard deviation to the Middle Band. The `multiplier` is typically 2.
    Upper Band = Middle Band + (StdDev * multiplier)
  4. Lower Band: Subtract the same multiple of the standard deviation from the Middle Band.
    Lower Band = Middle Band - (StdDev * multiplier)
03

Basic Bollinger Bands Implementation in Pine Script

pine-script@terminal
//@version=5
indicator("My Bollinger Bands", overlay=true)

// Inputs for Bollinger Bands parameters
length = input.int(20, title="BB Length", minval=1)
stdDevMultiplier = input.float(2.0, title="StdDev Multiplier", minval=0.1, step=0.1)

// Calculate Bollinger Bands using the built-in function
[middleBand, upperBand, lowerBand] = ta.bb(close, length, stdDevMultiplier)

// Plot the Middle Band
plot(middleBand, title="Middle Band", color=color.blue, linewidth=2)

// Plot the Upper and Lower Bands
plot(upperBand, title="Upper Band", color=color.red, linewidth=1)
plot(lowerBand, title="Lower Band", color=color.green, linewidth=1)

// Fill the area between the bands for visual appeal
fill(upperBand, lowerBand, color=color.new(color.blue, 90), title="BB Background")
$ ✓ Compiled successfully
04

Dynamic Channels

Dynamic Channels

Unlike fixed channels, Bollinger Bands adapt to current volatility, providing a more context-aware view of price extremes.

05

Practical Bollinger Bands Trading Strategies

1. Bollinger Band Squeeze (Volatility Contraction)

A "squeeze" occurs when the bands contract significantly, indicating a period of low volatility and consolidation that often precedes a strong price breakout.

  • Signal: Bands narrow considerably, often becoming the tightest they've been in a while.
  • Trade Action: Wait for price to break out of the consolidation phase. A close above the Upper Band after a squeeze suggests a bullish breakout; a close below the Lower Band suggests a bearish breakout.
//@version=5
strategy("Bollinger Band Squeeze Breakout", overlay=true)

length = input.int(20, title="BB Length", minval=1)
stdDevMultiplier = input.float(2.0, title="StdDev Multiplier", minval=0.1, step=0.1)

[middleBand, upperBand, lowerBand] = ta.bb(close, length, stdDevMultiplier)

plot(middleBand, "Middle Band", color.blue)
plot(upperBand, "Upper Band", color.red)
plot(lowerBand, "Lower Band", color.green)
fill(upperBand, lowerBand, color.new(color.blue, 90))

bandWidth = (upperBand - lowerBand) / middleBand * 100
squeezeThreshold = input.float(5.0, title="Squeeze Percentage Threshold", minval=0.1, step=0.1)
isSqueezing = bandWidth < squeezeThreshold

longBreakout = isSqueezing[1] and close > upperBand and close[1] <= upperBand[1]
shortBreakout = isSqueezing[1] and close < lowerBand and close[1] >= lowerBand[1]

if (longBreakout)
    strategy.entry("Long Breakout", strategy.long)

if (shortBreakout)
    strategy.entry("Short Breakout", strategy.short)

strategy.exit("Long Exit", from_entry="Long Breakout", stop=lowerBand)
strategy.exit("Short Exit", from_entry="Short Breakout", stop=upperBand)

2. Band Walks (Trend Following)

In strong trends, price can "walk" along the Upper or Lower Band without touching the Middle Band for extended periods, indicating strong directional momentum.

  • Bullish Walk: Price consistently touches or rides the Upper Band, and the Middle Band is sloping upwards.
  • Bearish Walk: Price consistently touches or rides the Lower Band, and the Middle Band is sloping downwards.
//@version=5
strategy("Bollinger Band Walk Strategy", overlay=true)

length = input.int(20, title="BB Length", minval=1)
stdDevMultiplier = input.float(2.0, title="StdDev Multiplier", minval=0.1, step=0.1)

[middleBand, upperBand, lowerBand] = ta.bb(close, length, stdDevMultiplier)

plot(middleBand, "Middle Band", color.blue)
plot(upperBand, "Upper Band", color.red)
plot(lowerBand, "Lower Band", color.green)
fill(upperBand, lowerBand, color.new(color.blue, 90))

isBullishWalk = close > middleBand and close > close[1] and close[1] > middleBand[1] and middleBand > middleBand[1] and close >= upperBand
isBearishWalk = close < middleBand and close < close[1] and close[1] < middleBand[1] and middleBand < middleBand[1] and close <= lowerBand

if (isBullishWalk)
    strategy.entry("Riding Bull", strategy.long)

if (isBearishWalk)
    strategy.entry("Riding Bear", strategy.short)

strategy.close("Riding Bull", when=close < middleBand or close[1] < middleBand[1])
strategy.close("Riding Bear", when=close > middleBand or close[1] > middleBand[1])

3. Mean Reversion (Band Bounces)

In sideways or consolidating markets, price often reverts to the Middle Band after touching one of the outer bands.

  • Buy Signal: Price touches or penetrates the Lower Band, and then closes back inside the band.
  • Sell Signal: Price touches or penetrates the Upper Band, and then closes back inside the band.
//@version=5
strategy("Bollinger Band Mean Reversion", overlay=true)

length = input.int(20, title="BB Length", minval=1)
stdDevMultiplier = input.float(2.0, title="StdDev Multiplier", minval=0.1, step=0.1)

[middleBand, upperBand, lowerBand] = ta.bb(close, length, stdDevMultiplier)

plot(middleBand, "Middle Band", color.blue)
plot(upperBand, "Upper Band", color.red)
plot(lowerBand, "Lower Band", color.green)
fill(upperBand, lowerBand, color.new(color.blue, 90))

isRanging = (upperBand - lowerBand) / middleBand * 100 > 1.0 and (upperBand - lowerBand) / middleBand * 100 < 5.0

longReversion = isRanging and close > lowerBand and close[1] <= lowerBand[1]
shortReversion = isRanging and close < upperBand and close[1] >= upperBand[1]

if (longReversion)
    strategy.entry("Buy Reversion", strategy.long)

if (shortReversion)
    strategy.entry("Sell Reversion", strategy.short)

strategy.close("Buy Reversion", when=close > middleBand or close < lowerBand)
strategy.close("Sell Reversion", when=close < middleBand or close > upperBand)
06

Optimizing Bollinger Bands Performance

To get the most from Bollinger Bands in Pine Script:

  • Parameter Tuning: The standard 20 length and 2.0 multiplier are suitable for intermediate-term analysis. Shorter lengths make bands more reactive; longer lengths make them smoother.
  • Combine with Other Indicators: Use momentum oscillators (RSI, Stochastic, MACD) to confirm overbought/oversold conditions, volume indicators to confirm breakouts, and trend-following indicators to confirm the underlying trend.
  • Adapt to Market Conditions: Mean-reversion works best in ranging markets; trend-following works best when volatility is increasing.
  • Look for W-Bottoms and M-Tops: These are classic Bollinger Band patterns where price makes a new low/high outside the bands signaling a reversal.
07

Not Just About Price Outside Bands

Not Just About Price Outside Bands

Price touching or slightly exceeding the bands is not always a direct buy/sell signal. It indicates relative overextension. The subsequent price action is what provides the signal.

08

Common Bollinger Bands Pitfalls

  • False Signals in Strong Trends: In a strong uptrend, price can consistently "walk" along the Upper Band. Treating every touch as a sell signal leads to premature exits.
  • Whipsaws in Choppy Markets: In very choppy or non-directional markets, the bands can still generate false reversal signals.
  • Lag: Bollinger Bands are lagging indicators reflecting past price action and volatility.
  • Over-Reliance on Single Signals: Relying solely on price touching a band without confirmation can be detrimental.
  • Not a Standalone Indicator: Bollinger Bands perform best as part of a comprehensive trading system.
09

Conclusion

Conclusion

Bollinger Bands are an exceptionally powerful and dynamic technical analysis tool in Pine Script for TradingView. By creating a visual representation of price volatility around a central moving average, they provide traders with invaluable insights into relative overbought/oversold conditions, potential trend reversals, and shifts in market volatility. Whether you are looking to capitalize on volatility squeezes, ride strong trends, or execute mean-reversion strategies, understanding and effectively applying Bollinger Bands, ideally in conjunction with other indicators and robust risk management, can significantly enhance your trading strategies and overall performance.

Enhance Your Trading

Get a high-performance Pine Script analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pine Script Strategy