Strategy · Pine Script v5 · On the chart

Bridge 04 - Bollinger Squeeze

by broomva

This strategy calculates Bollinger Bands and monitors band width relative to a historical moving average to identify low-volatility squeeze regimes.

View on GitHub

GitHub stars5on the repository
Pine versionv5runs as is
Lines of code72
Settings7inputs
LicenceMIT
Last updatetoday28 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

72 lines of Pine Script v5 from skills/finance/investment-management/services/tradingview-bridge/strategies/pine/04-bollinger-squeeze.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

04-bollinger-squeeze.pine
//@version=5
// Bollinger band squeeze + directional breakout. Fires when:
// - BB width is below its N-period mean (squeeze regime)
// - Price closes outside the band (squeeze release)
// Best for volatility-compression regimes (consolidating markets that
// then break out with momentum). Default tuned for FX timeframes.
//
// Schema target: TVAlert (services/tradingview-bridge/src/tradingview_bridge/schemas.py)

strategy(
     title="bridge/04 - Bollinger squeeze",
     shorttitle="04-BB",
     overlay=true,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=10,
     initial_capital=10000,
     commission_type=strategy.commission.percent,
     commission_value=0.02)

// === Inputs ===
length       = input.int(20,  "BB length",        minval=2)
mult         = input.float(2.0, "BB stdev",       minval=0.5, step=0.1)
squeeze_lookback = input.int(50, "Squeeze lookback", minval=10)
squeeze_pct      = input.float(0.7, "Squeeze threshold (width pct)", minval=0.1, maxval=1.0,
     tooltip="Squeeze fires when current BB width < this fraction of the mean width over lookback")

ASSET_CLASS   = input.string("fx", "Asset class",
     options=["stock", "etf", "bond", "fx", "crypto", "prediction"])
STRATEGY_NAME = input.string("bollinger-squeeze-20", "Strategy name (for journal)")
SECRET        = input.string("REPLACE_WITH_YOUR_TVBRIDGE_TV_WEBHOOK_SECRET", "Webhook shared secret")

// === Bands ===
basis = ta.sma(close, length)
dev   = mult * ta.stdev(close, length)
upper = basis + dev
lower = basis - dev
width = upper - lower

plot(basis, "Basis", color=color.new(color.gray,   60))
plot(upper, "Upper", color=color.new(color.red,    30))
plot(lower, "Lower", color=color.new(color.green,  30))

// === Squeeze regime ===
mean_width = ta.sma(width, squeeze_lookback)
in_squeeze = width < (mean_width * squeeze_pct)
bgcolor(in_squeeze ? color.new(color.yellow, 85) : na)

// === Signals — squeeze release ===
long_signal  = in_squeeze[1] and close > upper
short_signal = in_squeeze[1] and close < lower

// === Alert message ===
build_alert(action) =>
    '{' +
      '"alert_id":"' + STRATEGY_NAME + '-' + str.tostring(time, "yyyyMMdd-HHmm") + '-' + action + '",' +
      '"secret":"'        + SECRET        + '",' +
      '"strategy_name":"' + STRATEGY_NAME + '",' +
      '"asset_class":"'   + ASSET_CLASS   + '",' +
      '"symbol":"{{ticker}}",' +
      '"action":"'        + action        + '",' +
      '"size":"{{strategy.position_size}}",' +
      '"size_type":"units",' +
      '"price_hint":"{{close}}",' +
      '"order_type":"market",' +
      '"time":"{{time}}",' +
      '"metadata":{"bb_width":"' + str.tostring(width, "#.####") + '","mean_width":"' + str.tostring(mean_width, "#.####") + '"}' +
    '}'

if long_signal
    strategy.entry("L", strategy.long,  alert_message=build_alert("buy"))
if short_signal
    strategy.entry("S", strategy.short, alert_message=build_alert("sell"))

Overview

Bridge 04 - Bollinger Squeeze draws upper, lower, and basis bands directly on the price chart while shading squeeze periods in yellow. A long position is triggered when price breaks above the upper band out of a squeeze, and a short position is opened on a breakout below the lower band. Settings allow customization of band length, deviation multiplier, squeeze threshold, and webhook alert payloads. The strategy lacks stop-loss or take-profit rules, exiting only upon opposite entry signals.

Details

Published by

broomva on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Breakout, Trend

Markets

Forex, Crypto, Stocks

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Topics

agent-skillsai-agentsclaude-codemcpremotionskillsskills-shbstack-researchagentskillsanthropic

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
BB lengthint20length
BB stdevfloat2.0mult
Squeeze lookbackint50squeeze_lookback
Squeeze threshold (width pct)float0.7squeeze_pct
Asset classstringfxASSET_CLASS
Strategy name (for journal)stringbollinger-squeeze-20STRATEGY_NAME
Webhook shared secretstringREPLACE_WITH_YOUR_TVBRIDGE_TV_WEBHOOK_SECRETSECRET
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

This strategy plots VWMA-based Bollinger bands on the 1-minute ES futures price chart for volatility analysis and potential breakout identification. It calculates dynamic long and short stop loss and take profit levels using percentage inputs relative to entry

Strategy v6 Volatility & bandsSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of V1.6 ES - Futures 1M No Repaint
106 stars

This strategy runs on the price chart and enters long when a fast simple moving average crosses above a slow one, and short on the opposite cross, while closing the other side. Entries also need ATR above a filter, a pullback check, a minimum candle-body chang

Strategy v5 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 9:22 5 MIN 15 MIN BANKNIFTY

均线突破交易系统

by tangly1024
76 stars

This strategy trades long breakouts of a fast and a slow moving average on the price chart. It opens a long position when price crosses above either average, using a percentage of equity as size. It reduces the position by a set share when the high reaches the

Strategy v5 TrendMoving averages
Updated 4 months ago · None stated GitHub repository of 均线突破交易系统
16 stars

This trend-following strategy adapts classic Donchian breakout channels according to market volatility regimes. It calculates an ATR percentile rank across a rolling lookback period, shifting dynamically between tighter breakout channels with smaller stops dur

Strategy v6 TrendBreakout
Updated 11 months ago · None stated GitHub repository of Seykota Alt 1: Adaptive Volatility

This strategy executes breakout trades using two Donchian Channels alongside an optional 200-period EMA trend filter. Entries trigger when the price sets a new highest high or lowest low over the primary Donchian Channel period. Exits are managed via a shorter

Strategy v5 BreakoutTrend
Updated 1 year ago · None stated GitHub repository of Ruckard Walcrypto DoubleDonchian B002

Breakout Strategy

by JoelPasapera
11 stars

This strategy implements a channel breakout system directly on the main price chart. It calculates highest highs and lowest lows over configurable entry and exit periods using historical candles. A long entry triggers when the close breaks above the entry chan

Strategy v6 BreakoutTrend
Updated 5 months ago · Apache-2.0 GitHub repository of Breakout Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers