PipLedger
Today's forex newsNFP, CPI, FOMC and other high-impact eventsEconomic calendarCalendar →

Bollinger Bands strategy: trading the squeeze, with a free Pine Script

Bollinger Bands widen when the market is busy and narrow when it goes quiet. The squeeze, when they narrow more than they have for a long time, often comes before a big move. This guide explains how the bands are built, why touching a band isn't a signal on its own, rules for trading the breakout from a squeeze, a worked GBPUSD example and a free TradingView script.

By M. A. Horaira. Updated 10 October 2026. 10 minute read.

The rules at a glance

  • Bands: 20-period simple moving average with bands 2 standard deviations above and below
  • Squeeze: the band width (upper minus lower, divided by the middle band) is at its lowest in 100 candles
  • Entry: within 5 candles of a squeeze, a close above the upper band (long) or below the lower band (short) after a close inside the bands
  • Stop loss: the middle band at the time of entry, or the opposite band
  • Target: twice the risk (2R); one trade at a time, with an optional 200 EMA filter

How Bollinger Bands work

John Bollinger developed the bands in the 1980s. There are three lines: a 20-period simple moving average in the middle, and two bands set 2 standard deviations above and below it. The standard deviation measures how spread out recent closes are, so the bands widen when prices swing a lot and narrow when they don't.

Most closes fall inside the bands, which is why beginners often sell at the upper band and buy at the lower one. Bollinger himself stressed that a touch of a band isn't a buy or sell signal on its own. In a strong trend, the price can ride along the upper band for a long time. The bands are better at telling you how volatile the market is than which way it will go.

The squeeze

Volatility comes in cycles: quiet periods tend to be followed by busy ones, and the other way round. When the bands pinch together more than they have for a long time, the market is unusually quiet, and a big move often follows. Bollinger called this the squeeze. He measured it with band width: the distance between the bands divided by the middle band. He described a squeeze as band width falling to its lowest level in about six months. This script uses 100 candles, which on the 1-hour chart is only about four trading days, a much looser test than Bollinger's six months; try a longer lookback to see how many fewer squeezes it finds.

The squeeze tells you a move may be coming, not which way. That's why the strategy waits for the price to break out of the bands before choosing a side. Bollinger also warned about the head fake: a first move out of the squeeze that reverses and becomes the real move the other way. The stop at the middle band is there for that.

The rules, step by step

1. Find the squeeze

The script works out the band width on every candle. When it's the lowest of the last 100 candles, that's a squeeze, and the background is shaded.

2. Wait for the first close outside a band

Within 5 candles of a squeeze, go long on a close above the upper band, or short on a close below the lower band, when the candle before closed inside the bands. If a first breakout fails and the price closes back outside again within the window, the script can take a second trade.

3. Stop at the middle band

The stop goes at the middle band (the 20 SMA) as it is when you enter. If the price falls back to the average, the breakout has failed. The other choice is the opposite band, which gives more room and a smaller position.

4. Target twice the risk

The target is 2R. The trend filter is off by default, because a squeeze can break either way; switch it on to take only breakouts in the direction of the 200 EMA.

Worked example: GBPUSD, 1-hour chart

Target 1.3248Entry 1.3210Stop 1.3191SqueezeClose above the band2R

Upper and lower bands Middle band (20 SMA)

Illustrative chart drawn for this guide to show the rules. It isn't a real day's prices. GBPUSD, 1-hour candles.

After a choppy week, GBPUSD goes quiet around 1.3190. The band width falls to 0.23% of the price, the lowest in 100 candles (it had been as wide as 0.87%). Two candles after the squeeze, a strong candle closes at 1.3210, above the upper band at 1.3209. That's the long signal, with the stop at the middle band, 1.3191.

GBPUSD long
Entry1.3210
Stop loss (middle band)1.3191, 19 pips away
Target (2R)1.3248, 38 pips away
Account and risk$10,000, risking 1% = $100
Lot size$100 ÷ (19 pips × $10) = 0.52 lots
Loss if the stop is hit$98.80
Profit at the target$197.60

The bands open up as the move gets going, and the target is reached 8 hours after the entry. The quiet stretch is what made the stop small: the middle band was only 19 pips below the breakout close. After a busy period the same setup would need a much wider stop.

Other ways traders use Bollinger Bands

ApproachIdeaWatch out for
Squeeze breakout (this page)Trade the first close outside the bands after they pinchHead fakes
Mean reversionFade closes outside the bands back towards the middleStrong trends that ride a band
Walking the bandsIn a strong trend the price keeps tagging one band; buy pullbacks to the middle bandTrend changes
Band with RSICombine a band touch with an RSI readingTwo filters can still both be wrong

For momentum without the bands, see the RSI 60/40 strategy; for a trend filter with moving averages, the 9 and 21 EMA crossover.

Risk management

Common mistakes

  1. Selling every touch of the upper band. In a trend that means fighting the move.
  2. Guessing the direction before the break. The squeeze doesn't tell you which way.
  3. Calling any narrow stretch a squeeze. The point is that it's the narrowest in a long time; compare it with the last 100 candles, not the last 10.
  4. Changing the settings to fit one chart. 20 and 2 are the standard. Test changes on many dates.

Backtest it yourself on TradingView

This page doesn't quote a win rate or a profit figure, and you should be wary of anyone who does without showing the test. Results change with the market, the dates, the data feed and the costs you put in. The honest way is to run the test yourself, and the free script below does the work in a couple of minutes.

  1. Open the chart. On TradingView, open GBPUSD on the 1-hour chart.
  2. Add the script. Open the Pine Editor from the Pine icon in the panel on the right of the chart (older layouts have it as a tab under the chart), delete the code that's already there, paste this strategy's code and click "Add to chart".
  3. Put in your costs. Open the strategy's settings and go to Properties. Enter your broker's commission and a little slippage. A test without costs flatters every strategy, and short-term ones most of all.
  4. Read the Strategy Tester. The panel under the chart shows the net profit, the maximum drawdown, the profit factor, the number of trades and a list of every trade. Click a few trades and check on the chart that each one follows the rules. Trade sizes are shown in units rather than lots: 100,000 units is one lot of a forex pair, and 100 ounces is one lot of gold.
  5. Change one setting at a time. Compare the middle-band stop with the opposite-band stop, the squeeze lookback (50, 100, 150 candles), the 5-candle window, and the 200 EMA filter on and off. Then try EURUSD, XAUUSD and the 15-minute chart.

As a rough guide, don't trust a result with fewer than 100 trades, a profit factor under 1 once costs are in, or a drawdown you couldn't sit through with real money. Settings tuned to look good on one stretch of history often fail on the next, so check the same settings on dates you didn't tune them on, then demo trade the strategy for a few weeks. How much history you can test depends on your TradingView plan: the free plan loads 5,000 candles, which is a few months of 15-minute candles but years of daily ones.

The script sizes each trade from the stop loss and your risk percentage, starts with $10,000 and assumes 1:100 leverage (a 1% margin setting), so the tester doesn't flag margin calls on normal forex trade sizes. Change these under Properties to match your account. By default TradingView fills orders at the open of the candle after the signal, so the fill can differ a little from the signal candle's close.

Download the free Pine Script and PDF

The script is written in Pine Script version 6 for this guide and follows the rules above. It can't read the economic calendar, so skipping news days is up to you. It's free to use, change and share. The PDF is a one-page cheat sheet with the rules, a worked example, the lot size maths and a checklist, to keep next to your chart.

Show the code (Pine Script v6, 61 lines)
//@version=6
// Bollinger Bands squeeze strategy by PipLedger (https://pipledgerfx.com/bollinger-bands-strategy)
// Waits for the bands to squeeze to their narrowest in 100 candles, then trades the first close outside a band.
// Free to use and change. For education and backtesting only; not financial advice.
strategy("PipLedger: Bollinger Bands Squeeze", shorttitle="BB Squeeze", overlay=true, initial_capital=10000, pyramiding=0, default_qty_type=strategy.fixed, default_qty_value=1, margin_long=1, margin_short=1, currency=currency.USD)

// ---------- Inputs
bbLen     = input.int(20, "Bollinger length", minval=2)
bbMult    = input.float(2.0, "Standard deviations", minval=0.5, step=0.1)
sqLook    = input.int(100, "Squeeze: band width at its lowest in (candles)", minval=10)
sqRecent  = input.int(5, "Breakout must come within (candles) of the squeeze", minval=1)
stopMode  = input.string("Middle band", "Stop loss at", options=["Middle band", "Opposite band"])
rr        = input.float(2.0, "Target (R multiple)", minval=0.5, step=0.25)
useTrend  = input.bool(false, "Only trade in the direction of the 200 EMA")
riskPct   = input.float(1.0, "Risk per trade (% of equity)", minval=0.1, maxval=5.0, step=0.1)

// ---------- Helpers
fx = strategy.convert_to_account(1.0)  // one unit of the chart's quote currency in account currency (1 on USD-quoted charts)
calcQty(float entry, float stop) =>
    float dist = math.abs(entry - stop)
    dist > 0 and not na(fx) ? strategy.equity * riskPct / 100 / (dist * syminfo.pointvalue * fx) : 0.0

basis  = ta.sma(close, bbLen)
dev    = bbMult * ta.stdev(close, bbLen)
upper  = basis + dev
lower  = basis - dev
bw     = (upper - lower) / basis          // band width as a share of the middle band
ema200 = ta.ema(close, 200)

squeeze  = bw <= ta.lowest(bw, sqLook)
sinceSq  = ta.barssince(squeeze)
recentSq = not na(sinceSq) and sinceSq <= sqRecent

// ---------- Signals: the first close outside a band soon after a squeeze
flat     = strategy.position_size == 0
longSig  = flat and recentSq and close > upper and close[1] <= upper[1] and (not useTrend or close > ema200)
shortSig = flat and recentSq and close < lower and close[1] >= lower[1] and (not useTrend or close < ema200)

if longSig
    float sl = stopMode == "Middle band" ? basis : lower
    float q  = calcQty(close, sl)
    if q > 0 and sl < close
        strategy.entry("Long", strategy.long, qty=q)
        strategy.exit("Long exit", "Long", stop=sl, limit=close + (close - sl) * rr)

if shortSig
    float sl = stopMode == "Middle band" ? basis : upper
    float q  = calcQty(close, sl)
    if q > 0 and sl > close
        strategy.entry("Short", strategy.short, qty=q)
        strategy.exit("Short exit", "Short", stop=sl, limit=close - (sl - close) * rr)

// ---------- Chart
pU = plot(upper, "Upper band", color=color.new(color.teal, 20))
plot(basis, "Middle band (20 SMA)", color=color.new(color.orange, 0))
pL = plot(lower, "Lower band", color=color.new(color.teal, 20))
fill(pU, pL, color=color.new(color.teal, 92), title="Bands")
bgcolor(squeeze ? color.new(color.orange, 85) : na, title="Squeeze")
plot(useTrend ? ema200 : na, "200 EMA", color=color.new(color.gray, 0))
plotshape(longSig, "Breakout up", shape.triangleup, location.belowbar, color.teal, size=size.small)
plotshape(shortSig, "Breakout down", shape.triangledown, location.abovebar, color.red, size=size.small)

Trading this from India

Residents can trade EURUSD, GBPUSD and USDJPY futures and options on NSE and BSE through a SEBI-registered broker. The contracts are quoted the same way as the spot pair, one lot is 1,000 units of the base currency, and they're cash-settled in rupees. They trade only from 9 a.m. to 7:30 p.m. IST, volumes are thin and not every broker offers them, so check the hours and the spread first. Trading forex or CFDs with offshore online platforms isn't allowed for residents under FEMA, even if the app is easy to download. Details are in is forex trading legal in India.

Related strategies: 9 and 21 EMA crossover, RSI 60/40, MACD and 200 EMA, VWAP pullback, XAUUSD scalping. All 34 strategies are compared on one page in forex trading strategies.

Quick answers

What is the Bollinger Bands squeeze?

It's when the bands narrow to their tightest in a long time, because the market has gone unusually quiet. John Bollinger measured it with band width. A squeeze often comes before a bigger move, but it doesn't tell you the direction.

What are the best Bollinger Bands settings?

The standard settings are a 20-period moving average and bands 2 standard deviations away, and that's what most traders and this script use. Other settings can be tested, but there's no setting that's best for every market.

Is touching the upper Bollinger Band a sell signal?

Not on its own. Bollinger stressed that a touch of a band isn't a signal; in a strong uptrend the price can ride the upper band for a long time.

What is band width?

The distance between the upper and lower bands divided by the middle band. It measures how volatile the market is: low band width means a quiet market, high band width a busy one.

What is a head fake in Bollinger Bands?

It's Bollinger's term for a first move out of a squeeze that reverses and turns into the real move the other way. A stop at the middle band limits the damage.

Can I use Bollinger Bands for scalping?

The bands work on any timeframe, including the 1- and 5-minute charts. On those, costs are a bigger share of each trade, so backtest with your real spread and commission.

More guides

All 75 guides →

हिंदी में पढ़ें: Lot size kaise nikale?, Prop firm challenge kaise pass kare?, Gold trading kaise kare?, Forex trading kya hai, और India में यह legal है या नहीं?

Trading psychology

The habits that decide whether a good strategy makes money.

All 14 trading psychology guides

8 popular prop firms

Well-known firms for forex, gold and index traders that were still operating in 2026. Compare their rules before you buy a challenge.

If a link in this list is a referral link, PipLedger may earn a commission if you sign up, at no extra cost to you. This list is not a recommendation. Programs, prices and rules change often, so check each firm's own site, including its margin and drawdown rules, before you buy a challenge.