Bollinger Bands in Pine Script
A 20-bar moving average with bands 2 standard deviations either side, so their width tracks volatility and price at a band is a relative extreme, not a fixed one.
Definition
Bollinger Bands are a moving average with an upper and a lower band drawn a chosen number of standard deviations away from it. The standard setting is a 20-bar simple moving average with bands at 2 standard deviations. They belong to the bands and channels family, but unlike a fixed envelope the width is set by the market: the bands widen when recent closes are dispersed and tighten when they are clustered. That makes a band touch a relative statement, price is high or low compared with its own recent behaviour, rather than a fixed distance from an average.
Standard deviation measures how far closes have spread around their average over the window. A close outside a 2-deviation band is unusual by the standard of the last 20 bars, and that is all it says. Price is not normally distributed and trends persist, so an outside close is not a reversal signal by itself. In a range it marks a stretch that tends to snap back toward the basis. In a trend it marks strength, and price can walk along the band for many bars. The bands report the extreme; the context decides what to do with it.
John Bollinger developed the bands in the 1980s and later added two derived readings: %B, which places the close on a 0 to 1 scale between the bands, and bandwidth, the distance between the bands as a share of the basis. He also linked the multiplier to the length, about 1.9 at 10 bars and 2.1 at 50, so the bands contain a similar share of closes. The defaults on most platforms are 20 and 2. The library script adds a squeeze tint, amber while the bands sit inside a Keltner channel of the same length.
On the chart the bands hold most closes, and the interesting bars are the ones outside. After a quiet stretch the bands pinch together, which is the squeeze, and a burst of range then pushes one band away sharply. During a strong move price rides the outside of a band, closing on or beyond it bar after bar, while the opposite band turns and follows. When a move ends, the first close back inside the band is the mechanical event the library script marks: a close back above the lower band is a long, a close back below the upper band a short.
Reading the chart
Read the width first, then the position of price, then the slope of the basis, because each changes what a band touch means.
- Look at the width. Contracting bands, tinted amber in the library script while they sit inside the Keltner channel, mean a quiet market that is due to expand; wide and widening bands mean a move in progress.
- Locate the close relative to the bands. Outside the upper band is a 2-deviation high, outside the lower band a 2-deviation low; %B above 1 or below 0 says the same in one number.
- Read the basis. A rising 20-bar average is a bullish bias and a falling one bearish, and reversion trades are taken toward the basis, never through it.
- Check for a walk. Several closes in a row on or outside one band, with the opposite band turning to follow, is a trend, and fading it is the classic losing trade.
- Wait for the return inside. The library's trigger is the close crossing back inside from outside: back above the lower band for a long, back below the upper band for a short, on a confirmed bar.
- Confirm with something independent. A momentum divergence, a volume climax or a level from another concept at the band raises the odds of the snap back.
The maths
The basis is a simple moving average and the bands are that average plus and minus a multiple of the standard deviation of the same window.
The deviation is the population form, dividing by n. The sample form, dividing by n − 1, gives slightly wider bands and is what some spreadsheets return by default.
The deviation is measured around the same simple average that forms the basis, over the same window, so the two always move together.
Change the multiplier with the length: about 1.9 at 10 bars, 2 at 20 and 2.1 at 50 keeps the share of closes inside the bands roughly constant.
The squeeze in the library script is defined against a Keltner channel of the same length, an EMA with lines 1.5 ATR away. When both bands sit inside that channel the fill turns amber.
Inputs that matter
| Input | Typical | What changing it does |
|---|---|---|
| Length | 20 | Shorter bands hug price and give frequent touches; longer bands smooth the basis and make a touch rarer and more meaningful. |
| StdDev multiplier | 2 | Lower brings the bands in so price leaves them often; higher makes an outside close a rarer, stronger extreme. |
| Squeeze Keltner multiplier | 1.5 | Lower makes the squeeze condition stricter and the amber tint rare; higher tints more bars as compressed. |
In practice
- As a mean-reversion rule in a range: the close back inside a band is the entry and the basis the first target, which is the rule the library strategy trades with a 2 ATR stop.
- As a trend read: a walk along the upper band with the lower band turning up is strength, and pullbacks to the basis are long entries, while the band is not a short.
- As a volatility gauge: bandwidth at a multi-month low flags a squeeze, and the expansion that follows tends to start a directional move that other tools then time.
- As a target: in reversion trades the basis is the first target, in trend trades the opposite band, which moves with the trend and keeps the target realistic as the move develops.
- As a normalised position: %B lets you compare where price sits in its bands across instruments, and %B divergence against price at a second touch is a common reversal read.
- As a breakout filter: a close outside a band as the bands expand from a squeeze is a breakout with volatility behind it, the opposite trade from a reversion.
Where it goes wrong
- Shorting every touch of the upper band. In a trend the band is where price lives; check the basis slope and the opposite band before fading.
- Treating the bands as support and resistance. They are statistical distances that move with price, not levels where orders sit; combine them with fixed references.
- Assuming 95 percent of closes fall inside. That figure belongs to a normal distribution; real markets keep 85 to 90 percent inside and trend outside for long stretches.
- Changing the multiplier without changing the length. A 2-deviation band on 10 bars is much tighter in practice than on 50; adjust the pair together.
Compared with
Keltner Channels. Keltner channels use an EMA and a multiple of ATR, so the width changes slowly with average range. Bollinger widths jump with the dispersion of closes, which is why the two are compared to define a squeeze.
Moving Average Envelopes. Envelopes sit a fixed percentage from the average and do not know about volatility. Bollinger Bands set the distance from recent dispersion, so the same setting fits a quiet stock and a volatile one without recalibration.
Donchian Channels. Donchian channels are the highest high and lowest low of the window, a breakout tool by construction. Bollinger Bands are built from the average and its deviation, and read as extremes and volatility, not as range edges.
Volatility Squeeze. The squeeze is a regime defined by Bollinger Bands sitting inside a Keltner channel. The bands are the general tool; the squeeze is one specific reading of them, with a momentum histogram to pick direction.
Build it in Quant
Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.
Questions
Does a close above the upper band mean the market is overbought?
It means the close is more than 2 standard deviations above the 20-bar average, which is rare by the standard of recent behaviour. In a range that stretch tends to revert. In a trend it is a sign of strength, and price can close above the band for many bars. Read the basis slope and the opposite band before calling it overbought.
What are %B and bandwidth?
%B places the close between the bands on a 0 to 1 scale: 1 at the upper band, 0 at the lower, 0.5 at the basis, above 1 or below 0 when outside. Bandwidth is the distance between the bands divided by the basis, a volatility number you can compare across time. Both were added by Bollinger to make the bands quantitative.
What length and multiplier should I use?
Start with 20 and 2, the setting most traders and platforms share. If you shorten the length, lower the multiplier slightly, about 1.9 at 10 bars; if you lengthen it, raise it, about 2.1 at 50. The aim is a similar share of closes inside the bands, so a touch keeps the same meaning.
What is a Bollinger squeeze?
A squeeze is a stretch where the bands narrow to a low width compared with their own history, showing a quiet market. Bollinger read it from bandwidth at a 6-month low; the library script reads it as the bands sitting inside a Keltner channel and tints the fill amber. Quiet tends to be followed by a directional expansion, whose side the squeeze does not predict.
Why do the bands stay wide long after a big move?
Because the standard deviation keeps the big bars in its window for the full length. A single wide bar raises the deviation for 20 bars, so the bands stay wide even while price calms, then narrow sharply when the bar drops out. Read the width as a 20-bar memory, not as the volatility of the last few bars.
How does the library strategy trade the bands?
It enters long when the close crosses back above the lower band and short when it crosses back below the upper band, exits when the close crosses the basis, and protects each trade with a stop of 2 ATR. Longs and shorts can be switched off separately. It is a range strategy, so it needs a filter, or it stands down during a squeeze.