Indicator · Pine Script v6 · On the chart

Bollinger Band Squeeze (BBS)

by mihakralj

This overlay indicator calculates Bollinger Bands from a rolling mean and standard deviation and Keltner Channels from a simple moving average plus ATR-smoothed true range.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code151
Settings7inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

151 lines of Pine Script v6 from lib/oscillators/bbs/bbs.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

bbs.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Bollinger Band Squeeze (BBS)", "BBS", overlay=true)

//@function Calculates Bollinger Bands for squeeze detection
//@param source Series to calculate from
//@param period Lookback period
//@returns tuple with [middle, deviation] values
bbands_calc(series float source, simple int period) =>
    var int p = math.max(1, period)
    var int head = 0
    var int count = 0
    var array<float> buffer = array.new_float(p, na)
    var float sum = 0.0
    var float sumSq = 0.0
    
    float oldest = array.get(buffer, head)
    float current_val = nz(source)
    
    if not na(oldest)
        sum -= oldest
        sumSq -= oldest * oldest
    else
        count := math.min(count + 1, p)
    
    sum += current_val
    sumSq += current_val * current_val
    array.set(buffer, head, current_val)
    head := (head + 1) % p
    
    int n = math.max(1, count)
    float basis = sum / n
    float variance = n > 1 ? math.max(0.0, (sumSq / n) - (basis * basis)) : 0.0
    float dev = math.sqrt(variance)
    
    [basis, dev]

//@function Calculates Average True Range for Keltner Channels
//@param period Lookback period for ATR calculation
//@returns ATR value with proper warmup
atr_calc(simple int period) =>
    if period <= 0
        runtime.error("Period must be greater than 0")
    
    float tr = math.max(high - low, math.max(math.abs(high - nz(close[1])), math.abs(low - nz(close[1]))))
    float alpha = 2.0 / (period + 1)
    float beta = 1.0 - alpha
    
    var bool warmup = true
    var float e = 1.0
    var float atr = 0.0
    
    atr := alpha * tr + beta * atr
    
    float result = tr
    if warmup
        e *= beta
        float c = 1.0 / (1.0 - e)
        result := c * atr
        warmup := e > 1e-10
    else
        result := atr
    
    result

//@function Calculates Keltner Channels using SMA and ATR
//@param source Series to calculate from
//@param period Lookback period
//@param atr_mult ATR multiplier for channel width
//@param atr_val Pre-calculated ATR value
//@returns tuple with [middle, upper, lower] channel values
keltner_calc(series float source, simple int period, simple float atr_mult, series float atr_val) =>
    var int p = math.max(1, period)
    var int head = 0
    var int count = 0
    var array<float> buffer = array.new_float(p, na)
    var float sum = 0.0
    
    float oldest = array.get(buffer, head)
    float current_val = nz(source)
    
    if not na(oldest)
        sum -= oldest
    else
        count := math.min(count + 1, p)
    
    sum += current_val
    array.set(buffer, head, current_val)
    head := (head + 1) % p
    
    int n = math.max(1, count)
    float middle = sum / n
    float offset = atr_mult * atr_val
    
    [middle, middle + offset, middle - offset]

//@function Detects Bollinger Band Squeeze condition
//@param source Series to analyze
//@param bb_period Bollinger Band period
//@param bb_mult Bollinger Band standard deviation multiplier
//@param kc_period Keltner Channel period
//@param kc_mult Keltner Channel ATR multiplier
//@returns tuple with [squeeze_on, bandwidth, bands and channels]
bbs(series float source, simple int bb_period, simple float bb_mult, simple int kc_period, simple float kc_mult) =>
    if bb_period <= 0 or kc_period <= 0
        runtime.error("Periods must be greater than 0")
    if bb_mult <= 0.0 or kc_mult <= 0.0
        runtime.error("Multipliers must be greater than 0")
    
    [bb_middle, bb_dev] = bbands_calc(source, bb_period)
    float bb_upper = bb_middle + (bb_mult * bb_dev)
    float bb_lower = bb_middle - (bb_mult * bb_dev)
    
    float atr_val = atr_calc(kc_period)
    [kc_middle, kc_upper, kc_lower] = keltner_calc(source, kc_period, kc_mult, atr_val)
    
    bool squeeze_on = bb_upper < kc_upper and bb_lower > kc_lower
    float bandwidth = bb_middle == 0 ? 0 : ((bb_upper - bb_lower) / bb_middle) * 100
    
    [squeeze_on, bandwidth, bb_middle, bb_upper, bb_lower, kc_middle, kc_upper, kc_lower]

// ---------- Main loop ----------

// Inputs
i_bb_period = input.int(20, "Bollinger Band Period", minval=1, maxval=500)
i_bb_mult = input.float(2.0, "BB StdDev Multiplier", minval=0.1, maxval=5.0, step=0.1)
i_kc_period = input.int(20, "Keltner Channel Period", minval=1, maxval=500)
i_kc_mult = input.float(1.5, "KC ATR Multiplier", minval=0.1, maxval=5.0, step=0.1)
i_source = input.source(close, "Source")
i_show_bands = input.bool(true, "Show Bands", group="Display Options")
i_show_channels = input.bool(true, "Show Channels", group="Display Options")

// Calculation
[squeeze_on, bandwidth, bb_middle, bb_upper, bb_lower, kc_middle, kc_upper, kc_lower] = bbs(i_source, i_bb_period, i_bb_mult, i_kc_period, i_kc_mult)

// Plot squeeze dots
plotshape(squeeze_on, "Squeeze ON", shape.circle, location.bottom, color=color.red, size=size.tiny)
plotshape(not squeeze_on, "Squeeze OFF", shape.circle, location.bottom, color=color.green, size=size.tiny)

// Optional: Plot bands and channels
plot(i_show_bands ? bb_upper : na, "BB Upper", color=color.new(color.blue, 50), linewidth=1)
plot(i_show_bands ? bb_middle : na, "BB Middle", color=color.new(color.blue, 50), linewidth=1)
plot(i_show_bands ? bb_lower : na, "BB Lower", color=color.new(color.blue, 50), linewidth=1)

plot(i_show_channels ? kc_upper : na, "KC Upper", color=color.new(color.orange, 50), linewidth=1)
plot(i_show_channels ? kc_middle : na, "KC Middle", color=color.new(color.orange, 50), linewidth=1)
plot(i_show_channels ? kc_lower : na, "KC Lower", color=color.new(color.orange, 50), linewidth=1)

// Background color during squeeze
bgcolor(squeeze_on ? color.new(color.red, 95) : na, title="Squeeze Background")

Overview

A dedicated function returns whether a squeeze is on, the bandwidth, and the band and channel values. Periods, standard-deviation and ATR multipliers, and the price source are adjustable, and bands or channels can be hidden. It draws on the price chart and does not define entries, exits, or a stop loss.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Volatility & bands

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

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

SettingTypeDefaultVariable
Bollinger Band Periodint20i_bb_period
BB StdDev Multiplierfloat2.0i_bb_mult
Keltner Channel Periodint20i_kc_period
KC ATR Multiplierfloat1.5i_kc_mult
Sourcesourceclosei_source
Show Bandsbooltruei_show_bands
Show Channelsbooltruei_show_channels
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

Chandelier Exit

by everget
948 stars

This indicator plots an ATR-based Chandelier Exit trailing stop on the price chart. It tracks a long stop under recent highs and a short stop above recent lows, then switches direction when price crosses the opposite stop. Buy and sell labels mark those flips.

Indicator v6 Volatility & bandsTrend Repaints
Updated 10 days ago · GPL-3.0 GitHub repository of Chandelier Exit

ICT Liquidity Void Fill

by ArunKBhaskar
575 stars

This overlay indicator marks ICT liquidity void fills on the price chart and can show long and short signals. It places a Fibonacci level inside a displacement candle, defaulting to the midpoint, and draws lines in a chosen style. Optional filters limit the fi

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Liquidity Void Fill

This indicator plots trade entry and exit signals on the price chart by combining Bollinger Bands with optional filter conditions. It calculates standard Bollinger Bands along with RSI, Aroon, and moving average filters. Reversal signals trigger when price bre

Indicator v4 Volatility & bandsOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner IND [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of NVDA Trend Ribbon

Algo AVT

by ricardosantos79
261 stars

This indicator calculates an outlier-filtered moving average based on statistical filtering concepts. It stores close prices in a rolling array over a user-defined length, calculates the mean and standard deviation, and excludes values falling within a specifi

Indicator v4 Moving averagesVolatility & bands
Updated 4 years ago · None stated GitHub repository of Algo AVT

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers