TradingView Pine Script v6 Bollinger BandWidth Squeeze Release: Closed-Bar Volatility Signals

Beginner Trading Tutorial · Complete Pine Script v6 indicator · No lookahead data

Volatility is not the same thing as direction. A market can move steadily without broad swings, or chop violently while going nowhere. Bollinger Bands help illustrate how widely prices disperse around a moving average. Yet the width of the bands is easier to interpret after it is normalized against its own recent history. This tutorial turns that idea into a transparent, fully configurable TradingView indicator.

The indicator separates compression from directional confirmation. First it observes a unusually narrow BandWidth relative to a trailing baseline. Then it waits for that narrow state to end on a completed candle. Finally it requires the closing price to finish outside the current Bollinger Band. This three-stage logic intentionally avoids promising that every squeeze produces a tradable breakout.

A volatility question you can calculate by hand

Start with an ordinary 20-period Bollinger Band: basis is the simple moving average of close; the upper band is basis plus two standard deviations; the lower band is basis minus two standard deviations. The raw width is upper minus lower. Expressing it as a percentage of the absolute basis gives a measure that is easier to compare between a $30 share and a $300 share. That comparison is only sensible where the basis is nonzero and where the chosen price series has a meaningful scale.

BandWidth (%) = 100 × (Upper − Lower) ÷ |Basis|
Normalized width ratio = current BandWidth (%) ÷ average BandWidth (%) of the preceding 50 completed candles

The baseline is deliberately calculated from BandWidth[1], so the candle being evaluated does not inflate or depress its own reference value. A ratio of 1.00 means the width matches its prior average. A ratio of 0.60 means it is 40% below the prior average. The default squeeze threshold is 0.65, which is a research setting rather than a universal volatility boundary.

TradingView Pine Script v6 Bollinger BandWidth Squeeze Release: Closed-Bar Volatility Signals
Figure 1. Hypothetical candlestick sequence with Bollinger upper/lower bands and a separate normalized width line. The previous completed bar is still in squeeze; the final bar closes with a release and price above the current upper band. Not historical data.

Worked example: 0.60 becomes 0.84

Suppose the previous completed candle had a Bollinger basis of 100, upper band of 103, and lower band of 97. Raw BandWidth is 100 × (103 − 97)/100 = 6%. If the preceding 50-candle average BandWidth was 10%, the normalized ratio is 6/10 = 0.60. Since 0.60 ≤ 0.65, that candle qualifies as a squeeze.

On the next candle, suppose the basis is again 100, with bands at 104 and 96, so BandWidth is 8%. If its prior 50-bar BandWidth average is 9.5%, the normalized ratio is 8/9.5 = 0.8421. Since 0.8421 > 0.65, the compression condition has ended. If that candle closes at 104.50, above the upper band at 104, and it closes above its own open, the bullish release becomes eligible. Close at 103.50 instead, and the release exists but there is no bullish directional signal. The identical reasoning reversed below the lower band applies to bearish releases.

PS_TV_Bandwidth_EN_Fig2.png
Figure 2. Numerical pass/fail checkpoints: a prior 0.60 squeeze, a current 0.84 release and a confirmed close above the upper band. A release within the bands deliberately produces no directional alert.

What this indicator deliberately does—and does not do

Condition Interpretation Result
Width ratio ≤ 0.65 Compressed relative to preceding bandwidth observations Squeeze shading only
Previous bar squeezed; current bar > 0.65 One confirmed transition out of compression Release candidate
Release + close above current upper band Upward expansion confirmed at bar close Green UP marker and eligible alert
Release + close below current lower band Downward expansion confirmed at bar close Red DN marker and eligible alert
Release but price closes inside the bands Expansion without directional confirmation No arrow; no directional alert

This is a lower-pane indicator. It plots the width ratio and threshold, using shape markers only for completed directional releases. The chart price and Bollinger levels appear in the Data Window for checking. Unlike a strategy, the indicator does not submit orders, size positions, or produce any backtest profit statistic. It also does not wait for pivots or use future-bar data; its calculations run exclusively on the current chart timeframe.

Complete Pine Script v6 source

Create a new TradingView Pine Editor script, replace its content with the following complete listing, and add it to your chart. The source shown here is identical in the English and Chinese editions; calculations and parameter names are not translated.

//@version=6
// PatternSmart: Bollinger BandWidth squeeze and release
// Closed-bar directional confirmation; no future data requests.
indicator("PS BandWidth Squeeze Release", shorttitle = "PS BW Release", overlay = false, precision = 2)

// All parameters are available in the indicator settings panel.
int bbLength = input.int(20, "Bollinger length", minval = 5)
float deviationMultiplier = input.float(2.0, "Std. deviation multiplier", minval = 0.1, step = 0.1)
int baselineLength = input.int(50, "Prior BandWidth average length", minval = 10)
float squeezeLevel = input.float(0.65, "Squeeze ratio threshold", minval = 0.1, maxval = 2.0, step = 0.05)
bool requireBodyDirection = input.bool(true, "Require confirming candle body")

// Calculate Bollinger Bands on the chart's own timeframe.
float basis = ta.sma(close, bbLength)
float deviation = deviationMultiplier * ta.stdev(close, bbLength)
float upperBand = basis + deviation
float lowerBand = basis - deviation

// BandWidth as a percent of absolute basis: no division by zero.
float bandWidthPct = not na(basis) and math.abs(basis) > 0 ?
     100.0 * (upperBand - lowerBand) / math.abs(basis) : na

// Compare against older observations only. Current width is excluded.
float priorAvgWidth = ta.sma(bandWidthPct[1], baselineLength)
float widthRatio = not na(bandWidthPct) and not na(priorAvgWidth) and priorAvgWidth > 0 ?
     bandWidthPct / priorAvgWidth : na

bool squeeze = not na(widthRatio) and widthRatio <= squeezeLevel
bool release = barstate.isconfirmed and squeeze[1] and not na(widthRatio) and widthRatio > squeezeLevel

// Direction is confirmed only after the chart candle has closed.
bool bullishRelease = release and close > upperBand and
     (not requireBodyDirection or close > open)
bool bearishRelease = release and close < lowerBand and
     (not requireBodyDirection or close < open)

// Lower-pane visual: normalized width, threshold and squeeze shading.
plot(widthRatio, title = "BandWidth / previous average", color = squeeze ? color.blue : color.teal, linewidth = 2)
plot(squeezeLevel, title = "Squeeze threshold", color = color.red, linewidth = 1)
bgcolor(squeeze ? color.new(color.blue, 92) : na, title = "Squeeze background")
plotshape(bullishRelease, title = "Bullish release", style = shape.triangleup,
     location = location.bottom, color = color.lime, size = size.small, text = "UP")
plotshape(bearishRelease, title = "Bearish release", style = shape.triangledown,
     location = location.top, color = color.red, size = size.small, text = "DN")

// Data-window diagnostics: inspect widths and reference values precisely.
plot(bandWidthPct, title = "Raw BandWidth percent", display = display.data_window)
plot(priorAvgWidth, title = "Prior average BandWidth percent", display = display.data_window)
plot(upperBand, title = "Upper Bollinger Band", display = display.data_window)
plot(lowerBand, title = "Lower Bollinger Band", display = display.data_window)

// Create alerts from the TradingView UI; choose Once Per Bar Close.
alertcondition(bullishRelease, title = "PS BW bullish release",
     message = "Confirmed bullish BandWidth release: {{ticker}} / {{interval}}")
alertcondition(bearishRelease, title = "PS BW bearish release",
     message = "Confirmed bearish BandWidth release: {{ticker}} / {{interval}}")

Set it up in TradingView

  1. Open a TradingView chart and the Pine Editor.
  2. Paste the entire v6 script, save it, and choose Add to chart. Compile compatibility must be checked in your own TradingView account; no live compilation is claimed.
  3. Start with Bollinger length 20, standard deviation multiplier 2, prior average length 50, squeeze ratio 0.65, and candle body confirmation enabled.
  4. Observe blue shading while the width ratio is at or below 0.65. A green or red marker is only eligible when a just-closed bar breaks out of the prior squeeze and closes outside the current band.
  5. To receive notifications, create a TradingView alert using this indicator’s bullish or bearish alert condition, and select Once Per Bar Close.

A practical warm-up detail: the 20-period Bollinger calculation needs sufficient history, and the trailing 50-width baseline adds more required bars. On the earliest visible portion of a dataset the ratio may be na; this is expected. It is safer to let the series become fully defined than to substitute fabricated values or silently reduce the lookback length.

Four failure modes worth checking before using a signal

1. A narrow band is not a forecast

Compression sometimes precedes a large directional move and sometimes precedes more sideways movement. A squeeze is a description of current dispersion—not a guaranteed launch signal. Price may leave the compression state without closing outside a band; our indicator explicitly rejects that as a directional release.

2. A release can be a false breakout

A close outside a Bollinger Band can be followed by an immediate reversal, particularly around earnings, economic announcements, low liquidity, or unusually wide spreads. A band is not support, resistance, or a stop-loss by definition. The script deliberately leaves risk management to a separate, tested trading plan.

3. Chart refreshes and open bars behave differently

Before the live candle finishes, the raw width ratio, shading and band values can update with price. That is normal indicator behavior. The directional signal itself is gated by barstate.isconfirmed and requires a completed bar. Historical data corrections, adjusted candles and different symbol feeds can still revise past calculated values. This is not a claim of immutable signals across data vendors.

4. Parameters change the sample

Raising the squeeze threshold from 0.65 to 0.80 makes the squeeze state easier to enter, but a subsequent transition can mean a different form of expansion. A shorter baseline reacts faster and can be noisier; a longer baseline better reflects a broader volatility regime but adapts more slowly. Compare several fixed parameter settings on a held-out sample rather than optimizing against a few attractive chart screenshots.

Simple validation protocol

For at least 30 historical transitions, log the prior ratio, the release ratio, the current upper and lower bands, the candle close, the spread and session context. Count how many releases failed the directional close check. For qualified arrows, measure what happened over the next 1, 3 and 5 completed candles, including adverse excursion and realistic execution costs. Evaluate a mix of trending and ranging periods, and keep a record of false breakouts. Do not invent win rates or profitability claims from this illustration.

For a customized version with optional on-chart band overlays, retest tracking, risk controls or a webhook payload, explore Custom Trading Software Development Services. Interested in the free study and want to adapt it to your own workflow? Contact us to discuss a scoped modification.

Educational material only. No recommendation to buy or sell securities, no guaranteed returns, and no claim of live compilation or backtesting. Verify all functions in your own TradingView Pine Editor before relying on the study.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.