How to Use Bollinger Bands in Pine Script v6: Volatility Measurement and Breakout Detection
Bollinger Bands are a statistical volatility envelope built from a simple moving average and a rolling standard deviation, giving traders a dynamic price channel that expands during high-volatility regimes and contracts during low-volatility regimes. Understanding the mathematics behind the bands — and the Pine Script v6 constraints that govern their implementation — is essential before writing production-quality indicators. This article walks through the exact formulas, type-system rules, and verified code patterns required to build a correct Bollinger Band indicator in Pine Script v6. 1. Mathematical Foundation Given a source series $x_t$ and a lookback window of $n$ bars, the three Bollinger Band lines are defined as: $$\text{Basis}_t = \frac{1}{n}\sum_{i=0}^{n-1} x_{t-i}$$ $$\text{Upper}_t = \text{Basis}_t + k \cdot \sigma_t$$ $$\text{Lower}_t = \text{Basis}_t - k \cdot \sigma_t$$ where $k$ is the standard-deviation multiplier (co...