Tutorial

Bollinger Squeeze Pine Script: Detect and Backtest It

Build a Bollinger squeeze in Pine Script v6: rank band width with ta.percentrank, detect the release, and test a breakout strategy with exits.

•11 min read

You open a chart of a coin that has been going nowhere for two weeks. The candles are tiny, the Bollinger Bands have pinched together until they look like a single thick line, and you know from experience that this quiet never lasts. What you do not know is how to tell your script that "tight" means tight. A fixed number like 0.04 works on one market and means nothing on the next, and the moment you move to a different timeframe the whole idea falls apart.

This guide builds the Bollinger squeeze in Pine Script v6 in a way that survives a change of symbol or timeframe. We measure band width, rank it against its own recent history instead of a hard-coded threshold, detect the moment the squeeze releases, and then turn that into a strategy with explicit exits that you can run through TradingView's Strategy Tester. Along the way we cover the traps that make squeeze scripts look better than they are.

What a squeeze actually measures

Bollinger Bands are a moving average with a band above and below it, placed a multiple of the standard deviation of price away. When price is quiet, the standard deviation shrinks and the bands move closer together. When price is volatile, they spread. If you want the full construction of the bands themselves, our Bollinger Bands guide covers it, and the free Bollinger Bands calculator lets you check a single value by hand.

A squeeze is simply a period when the bands are unusually narrow compared with how narrow they usually are for that market. The key word is "usually". A calm large-cap pair and a thin altcoin have very different normal widths, so a squeeze cannot be defined with one absolute number. It has to be defined relative to the instrument's own history.

The idea behind trading it is that volatility tends to alternate between low and high. A squeeze tells you the market has been quiet; it does not tell you which way price will go when the quiet ends, or whether it will go anywhere at all. That distinction shapes every design decision below. The script detects a condition and reports it. It does not forecast anything.

Band width, the number to track

The standard way to turn the bands into one number is band width: the distance between the upper and lower band, divided by the middle band. Dividing by the middle band matters, because it makes the value a fraction of price. Without it, a coin trading at 60,000 and a coin trading at 0.5 could never be compared, and even the same coin would read as wider simply because its price rose.

In Pine this is a few lines. The middle band is a simple moving average of close, the offset is a multiple of the population standard deviation from ta.stdev, and the width falls out directly. If you have wondered which standard deviation Pine uses, the ta.stdev breakdown explains the sample versus population question, and it is the same one the built-in ta.bb uses.

One practical note: the formula divides by the basis, so a basis of zero would give na. On real price data that does not happen, but if you apply the script to a synthetic series that touches zero, expect gaps. Pine propagates na silently, which is worth understanding before you debug an empty plot, and we have a separate piece on how Pine Script handles na.

Defining "tight" with percentrank instead of a magic number

The most common mistake in squeeze scripts is a constant such as bbw < 0.05. It will look fine on the chart you tuned it on and misfire everywhere else. The fix is to ask a different question: where does today's width sit among the last N widths?

Pine has a built-in for exactly this. ta.percentrank(source, length) returns the percentage of previous values in the lookback that are less than or equal to the current one, on a scale from 0 to 100. A reading of 10 means the current width is among the narrowest 10 percent of the last N bars. That reading means the same thing on a four-hour chart and a daily chart, on one market and another. We go deeper on the function in the ta.percentrank article.

Two inputs then define your squeeze: the lookback (how much history counts as normal) and the percentile threshold (how narrow counts as tight). A lookback of 120 bars and a threshold of 15 is a sensible place to start, not a recommendation. Short lookbacks adapt quickly but forget what a real squeeze looks like after a long quiet stretch. Long lookbacks stay anchored but react slowly to a market that has genuinely changed regime. You should treat both as parameters to test, not settings to trust.

The detector, a complete indicator

Here is the full indicator. It plots the width rank in its own pane, shades squeeze bars, and exposes an alert for the moment a squeeze ends. Every ta.* call sits at global scope, which avoids the inconsistent-history problem that appears when these functions are called inside conditionals.

pine
//@version=6
indicator("Bollinger Squeeze Detector", overlay = false)

length   = input.int(20, "BB length", minval = 2)
mult     = input.float(2.0, "StdDev multiplier", minval = 0.1, step = 0.1)
lookback = input.int(120, "Rank lookback", minval = 10)
pct      = input.float(15.0, "Squeeze percentile", minval = 1.0, maxval = 50.0)

basis = ta.sma(close, length)
dev   = mult * ta.stdev(close, length)
upper = basis + dev
lower = basis - dev
bbw   = (upper - lower) / basis
rank  = ta.percentrank(bbw, lookback)

inSqueeze   = rank <= pct
squeezeEnds = inSqueeze[1] and not inSqueeze

plot(rank, "Width rank", color = color.new(color.blue, 0))
hline(pct, "Squeeze threshold", color = color.gray, linestyle = hline.style_dashed)
bgcolor(inSqueeze ? color.new(color.orange, 80) : na)
plotshape(squeezeEnds, "Squeeze ends", shape.triangleup, location.bottom, color.orange, size = size.tiny)

alertcondition(squeezeEnds, "Squeeze ended", "Bollinger squeeze ended on {{ticker}} {{interval}}")

Read the output carefully. The blue line is the rank of the current width, the dashed line is your threshold, and the shaded background marks bars that qualify as a squeeze. The triangle marks the first bar after a squeeze stops. It says "the bands stopped being unusually narrow". It does not say price will rise or fall, and nothing in the script claims it.

Because squeezeEnds compares the current bar to the previous one, it is confirmed only when the bar closes. If you attach an alert to it, set the alert to fire once per bar close, otherwise a real-time bar can flicker in and out of a squeeze and fire an alert you then cannot find on the chart. The article on alerts firing on the wrong bar explains this failure in detail.

Watching it before you trade it

Before turning any detector into a strategy, look at where it fires. Scroll through a few markets and several timeframes. Ask whether the shaded regions are what you would have called a squeeze by eye, and whether the triangle sits on the bar where the bands begin to widen. If shading appears for hundreds of bars at a time, your lookback is too long or your percentile too generous. If it almost never appears, do the opposite.

PineScripter's replay is useful here: it steps a chart run one bar at a time so you can see exactly when the script reacts, and you can ask the AI about any bar. That is a check on behavior, not a test of whether the idea earns anything. For that, you use TradingView's Strategy Tester, which comes next.

Turning the squeeze into a strategy

A squeeze alone has no direction, so a strategy needs an extra rule to choose one. The simplest honest rule is the one the bands themselves provide: after a squeeze, if the close breaks above the upper band, go long; if it breaks below the lower band, go short. This is a hypothesis to test, not a claim. Plenty of squeezes end with a brief poke through one band that reverses immediately, and that is precisely what a backtest on your own market will show you.

A few design choices are worth explaining before the code.

First, "after a squeeze" is defined as a squeeze having been active within the last few bars, not necessarily on the previous one. The bands are often already widening on the breakout bar itself, so requiring the squeeze to still be active at that moment would filter out nearly every real breakout. We use ta.barssince(inSqueeze) with a small window, called at global scope.

Second, every entry has an exit plan written into the script. A volatility stop based on ATR sits a set distance from the average entry price, and a position also closes when price falls back to the middle band, meaning the breakout has failed to hold. Our trailing stop guide and ATR guide go further into both ideas.

Third, costs are modelled from the start. A strategy that fires only a few times a month can look fine with zero commission and fall apart with realistic fees. The strategy below sets percent commission and slippage in the declaration. Test them at values you would actually pay, and read the commission and slippage settings article to see how TradingView applies them.

pine
//@version=6
strategy("Bollinger Squeeze Breakout", overlay = true, initial_capital = 10000,
     default_qty_type = strategy.percent_of_equity, default_qty_value = 10,
     commission_type = strategy.commission.percent, commission_value = 0.1,
     slippage = 2)

length    = input.int(20, "BB length", minval = 2)
mult      = input.float(2.0, "StdDev multiplier", minval = 0.1, step = 0.1)
lookback  = input.int(120, "Rank lookback", minval = 10)
pct       = input.float(15.0, "Squeeze percentile", minval = 1.0, maxval = 50.0)
window    = input.int(3, "Bars after squeeze to allow entry", minval = 0)
atrLen    = input.int(14, "ATR length", minval = 1)
atrStop   = input.float(2.0, "ATR stop multiple", minval = 0.5, step = 0.1)

basis = ta.sma(close, length)
dev   = mult * ta.stdev(close, length)
upper = basis + dev
lower = basis - dev
bbw   = (upper - lower) / basis
rank  = ta.percentrank(bbw, lookback)
atr   = ta.atr(atrLen)

inSqueeze     = rank <= pct
recentSqueeze = ta.barssince(inSqueeze) <= window

longBreak  = recentSqueeze and close > upper
shortBreak = recentSqueeze and close < lower

if longBreak and strategy.position_size <= 0
    strategy.entry("Long", strategy.long)
if shortBreak and strategy.position_size >= 0
    strategy.entry("Short", strategy.short)

if strategy.position_size > 0
    strategy.exit("Long exit", "Long", stop = strategy.position_avg_price - atrStop * atr)
    if close < basis
        strategy.close("Long", comment = "Back to basis")

if strategy.position_size < 0
    strategy.exit("Short exit", "Short", stop = strategy.position_avg_price + atrStop * atr)
    if close > basis
        strategy.close("Short", comment = "Back to basis")

plot(basis, "Basis", color = color.gray)
plot(upper, "Upper", color = color.new(color.teal, 0))
plot(lower, "Lower", color = color.new(color.teal, 0))
bgcolor(inSqueeze ? color.new(color.orange, 85) : na)

Notice the stop is evaluated against the average entry price, not against the current close. That keeps the stop fixed in place as the trade develops. If you want it to move with price, that is a trailing stop and a different design, which we cover in the trailing stop piece linked above. The entry logic is also reversed when the opposite signal appears, because strategy.entry on the other side closes the open position and opens the new one.

Pitfalls that flatter a squeeze backtest

The first trap is parameter fitting. With a lookback, a percentile, a window, an ATR length, and a stop multiple, you have five dials. Turn them enough and some combination will look excellent on any history. The question to ask of any result is whether it survives small changes. If a percentile of 15 works and 12 and 18 do not, you have found a coincidence, not a pattern.

The second is trade count. A squeeze strategy is selective by design, so a test over a short window may produce a handful of trades. A handful of trades cannot support any conclusion. Test across multiple markets and long ranges, and treat anything with only a few dozen trades as weak evidence at best. Our guides to Strategy Tester metrics and to why backtests differ from live trading are worth reading before you trust a number.

The third is lookahead in anything you add. If you build a higher-timeframe filter, such as requiring a daily squeeze while trading on the one-hour chart, use request.security carefully. A wrong setting leaks future values into past bars and produces a strategy that cannot possibly be traded. The lookahead explainer shows exactly how that happens.

The fourth is the band-walk. In a strong move, price can sit outside the upper band for many bars. A script that re-enters on every close beyond the band will stack up entries it did not intend. The guard strategy.position_size <= 0 in the code above prevents that, and it is easy to forget when adapting the script.

Variations worth testing

Once the base version runs, there are a few natural extensions. A volume filter requires the breakout bar to trade above its own recent average, which screens out some thin pokes through a band. A Keltner version, in the style popularised as the TTM squeeze, calls it a squeeze only when the Bollinger Bands sit inside the Keltner Channels, which compares two different volatility measures; our Keltner Channels guide gives you the second half of that build. A trend filter allows long entries only when price is above a longer moving average, and shorts only below it, which reduces trades but changes what the strategy is saying.

Each of those is a small edit to a working script, and each should be tested one at a time. Change one thing, rerun, and compare against the previous version. When you change three things at once you can no longer tell which one helped.

Making those edits without breaking the script

This is where hand-editing gets tedious. You want to add a volume condition to the entry, move the ATR multiple into a tuned input, and add an alert that carries the entry direction, all without disturbing the parts that already work. With a general chatbot, the usual outcome is a rewrite of the whole file, and the part you did not ask about quietly changes.

PineScripter is built around that loop. You describe the change in plain English, it checks the new code for compile errors the way TradingView does and fixes them itself, and it edits only the lines that change, with a Code Changes view showing exactly what moved. You can run the result on real market data in the chart, step through it bar by bar in replay, and measure how its triggers behaved on past data in Indicator Analysis. PineScripter does not backtest or simulate trades, so the final performance check still belongs in TradingView's Strategy Tester. The code is yours to copy out at any time. See the pricing page for plans, and the indicator to strategy guide for the general workflow.

Disclaimer

PineScripter is a coding tool, not a financial advisor, broker, or signal service. The code in this article is educational and describes a volatility condition, not a prediction about price. Nothing here is a recommendation to buy or sell, and no result is promised or implied. Past behavior of any script on historical data does not indicate future behavior. Test everything yourself and make your own decisions.

Back to Blog

Frequently asked questions

What is a Bollinger squeeze in Pine Script?

It is a period when the Bollinger Bands are unusually narrow compared with their own recent history. In Pine Script you measure band width as (upper - lower) / basis, then use ta.percentrank to check whether the current width sits among the narrowest readings of the last N bars.

Why use ta.percentrank instead of a fixed width threshold?

A fixed number such as 0.05 only fits the market and timeframe you tuned it on. A percentile rank describes the width relative to that instrument own history, so the same setting means the same thing across symbols and timeframes.

Does a squeeze tell me which direction price will move?

No. A squeeze only says volatility has been low. Direction needs a separate rule, such as a close beyond the upper or lower band, and that rule is a hypothesis you test, not a prediction.

Can PineScripter backtest this strategy?

No. PineScripter checks the code, runs it on real market data in its chart, and lets you step through replay bar by bar, but it does not simulate trades. Use TradingView Strategy Tester for the backtest.

Why is my squeeze alert firing on bars I cannot find?

Real-time bars can enter and leave a squeeze before they close. Set the alert to fire once per bar close so it matches what the chart shows afterwards.

Describe your indicator in plain English and get Pine Script that compiles →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.