Skip to content
GetProfitable
Search
Volatility

Bollinger Bands

A 20 period basis with bands a number of standard deviations either side, the envelope shaded, and the band width as a percentage of the basis carried in the data window so the squeeze and expansion are measurable.

indicator
//@version=6
indicator("Bollinger Bands", "BB", overlay = true)

length = input.int(20, "Basis length", minval = 2, group = "Settings")
mult = input.float(2.0, "Standard deviations", minval = 0.1, step = 0.1, group = "Settings")
bandCol = input.color(#787B86, "Bands", group = "Style")
aboveCol = input.color(#26A69A, "Closed above", group = "Style")
belowCol = input.color(#EF5350, "Closed below", group = "Style")

[basis, upper, lower] = ta.bb(close, length, mult)
width = basis != 0 ? (upper - lower) / basis * 100 : 0

pUpper = plot(upper, "Upper", color = bandCol)
pLower = plot(lower, "Lower", color = bandCol)
plot(basis, "Basis", color = color.new(bandCol, 25))
fill(pUpper, pLower, color = color.new(bandCol, 94), title = "Envelope")
plot(width, "Band width percent", color = bandCol, display = display.data_window)

closedAbove = ta.crossover(close, upper)
closedBelow = ta.crossunder(close, lower)
plotshape(closedAbove, "Closed above", location = location.abovebar, style = shape.triangleup, color = aboveCol, size = size.tiny)
plotshape(closedBelow, "Closed below", location = location.belowbar, style = shape.triangledown, color = belowCol, size = size.tiny)
alertcondition(closedAbove, "Closed above the upper band", "Price closed above the upper Bollinger band")
alertcondition(closedBelow, "Closed below the lower band", "Price closed below the lower Bollinger band")
This runs in TradingView, not here
Pine Script only executes inside TradingView. Paste the source into the Pine Editor and add it to a chart to see it plotted.

What it will not do

  • Standard deviation assumes returns are well behaved. They are not, so closes outside the bands happen far more often than the arithmetic suggests.
  • A close outside a band is not a reversal signal. In a trend price walks the band for long stretches.
  • The bands widen after volatility has already arrived, because the deviation is measured over past bars.
  • Band width is comparable over time on one instrument, not between instruments on different scales.

Written from this description

Plot Bollinger bands with a configurable length and standard deviation multiple, shade between the bands, expose the band width as a percentage of the basis, and mark closes outside either band.

Educational only, not financial advice. The maths is simple arithmetic on the numbers you enter; it knows nothing about your broker, fees, slippage or the market. Something wrong with it? Say so in Site Feedback.