MM Flow
FlowScripts

Perfected FlowScript

Bollinger Band %B

Bollinger Band %B V2 is indexed as 066_bollinger_band_pct_b.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.

This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.

Dialect

flowscript-v2

Compatibility

flowscript-v2-needs-transpile

Position

offchart

Axis

true

Size

12.6 KB

Lines

306

Native Signal Candidates

3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

3/3 guarded

Overbought

line 229:5

Trigger

(showShapes && regimeOverbought && obBars == 1)

Value

obRaw

Deps

obBars:static, regimeOverbought:var, showShapes:input

Oversold

line 239:5

Trigger

(showShapes && regimeOversold && osBars == 1)

Value

osRaw

Deps

osBars:static, regimeOversold:var, showShapes:input

Squeeze

line 251:5

Trigger

(showSqueeze && isSqueeze && squeezeBars == 1)

Value

midRaw

Deps

isSqueeze:var, showSqueeze:input, squeezeBars:static

066_bollinger_band_pct_b.flowscript

source path: kscripts/perfected/066_bollinger_band_pct_b.flowscript · sha256:94b6de9e4c8b43e8621f6d821698a77b7efedc9c411de11ed4ed9c08569a8313

hash verified
//@version=2

// ============================================================================
// Bollinger Band %B V2 — Perfected Edition with Fill, Regime & Dynamic Bands
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #bbpct, #bollingerbands, #trading, #technical, #regime
//
// This indicator normalises price position within Bollinger Bands to a 0-1 (or
// 0-100) scale and adds a full production layer: proper band construction
// (SMA ± 2σ), fill between band boundaries, %B regime colour coding, shape
// markers for statistically extreme readings, and static session tracking for
// squeeze/expansion detection. Academic foundations include Bollinger's
// canonical %B, Leung & Chong's empirical validation, and Poterba & Summers'
// mean-reversion evidence.
//
// Academic foundation (exact papers & formulas):
//  1. Bollinger (2001), "Bollinger on Bollinger Bands", McGraw-Hill.
//     [Formula] %B = (Close − Lower Band) / (Upper Band − Lower Band);
//     0 = lower band, 1 = upper band, 0.5 = middle band.
//     Bands = SMA ± k·σ where k = 2 (default) and σ = rolling standard deviation.
//
//  2. Leung & Chong (2003), "An Empirical Comparison of Moving Average
//     Envelopes and Bollinger Bands", Journal of International Financial
//     Markets, Institutions and Money, 13(4), 355–370.
//     [Formula] At 2 standard deviations, ~95% of price movement is captured.
//     BB superior to fixed MA envelopes at capturing abrupt price fluctuations.
//     DOI: https://doi.org/10.1016/S1042-4431(03)00032-5
//
//  3. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications", Journal of Financial Economics, 22(1), 27–59.
//     Returns are negatively autocorrelated over multi-year periods; temporary
//     deviations from fundamental value suggest mean-reversion opportunities.
//     DOI: https://doi.org/10.1016/0304-405X(88)90021-9
//
//  4. Kaufman (1995), "Smarter Trading", McGraw-Hill. Adaptive moving average
//     concepts (KAMA/ER) inform the volatility squeeze / expansion detection.
//
//  5. Bollinger (2010), "Bollinger Band Width", StockCharts.com. Band width
//     (%B range) contraction precedes directional expansion; the "squeeze"
//     pattern is a well-documented volatility regime transition signal.
// ============================================================================

define(title="Bollinger Band %B V2", position="offchart", axis=true)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Band Construction --
var len = input(name="len", type="number", defaultValue=20, label="MA Length (bands)", constraints={min: 5, max: 100, step: 1}, group="Band Construction")
var mult = input(name="mult", type="number", defaultValue=2.0, label="StdDev Multiplier", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Band Construction")
var useEmaBasis = input(name="useEmaBasis", type="boolean", defaultValue=false, label="Use EMA Basis (off = SMA)", group="Band Construction")

// -- Computation --
var smoothLen = input(name="smoothLen", type="number", defaultValue=1, label="%B Smoothing Length (1 = none)", constraints={min: 1, max: 20, step: 1}, group="Computation")
var useEmaSmooth = input(name="useEmaSmooth", type="boolean", defaultValue=false, label="Smooth with EMA (off = SMA)", group="Computation")
var rescale = input(name="rescale", type="boolean", defaultValue=true, label="Rescale to 0-100", group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Squeeze Detection Window", constraints={min: 20, max: 200, step: 5}, group="Computation")

// -- Display --
var showPctB = input(name="showPctB", type="boolean", defaultValue=true, label="Show %B Line", group="Display")
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show Bollinger Bands", group="Display")
var showBandFill = input(name="showBandFill", type="boolean", defaultValue=true, label="Show Band Fill", group="Display")
var showPctBFill = input(name="showPctBFill", type="boolean", defaultValue=true, label="Show %B Fill vs Midline", group="Display")
var showBars = input(name="showBars", type="boolean", defaultValue=true, label="Show %B Bars", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showSqueeze = input(name="showSqueeze", type="boolean", defaultValue=true, label="Show Squeeze Detection", group="Display")

// -- Colors --
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Upper Zone Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Lower Zone Color", group="Colors")
var midColor = input(name="midColor", type="color", defaultValue="#78909c", label="Midline Color", group="Colors")
var bandColor = input(name="bandColor", type="color", defaultValue="#2962ff", label="Band Line Color", group="Colors")
var squeezeColor = input(name="squeezeColor", type="color", defaultValue="#ffab00", label="Squeeze Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first access
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close

// Guard: halt until price data has loaded to avoid NaN propagation
if (isnan(c[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Bollinger Band construction (canonical SMA ± k·σ) --
// Per Bollinger (2001): basis = SMA(close, len); std = StDev(close, len);
// upper = basis + mult * std; lower = basis - mult * std.
// Guard: stddev could be zero on flat markets; bands collapse to basis.

timeseries basis = useEmaBasis ? ema(c, len) : sma(c, len)
timeseries sd = stdev(c, len)
timeseries upB = basis + mult * sd
timeseries dnB = basis - mult * sd
timeseries rangeB = upB - dnB

// -- 3.2 %B calculation (canonical formula) --
// %B = (close − lower) / (upper − lower). 0 = lower band; 1 = upper band; 0.5 = basis.
// Guard: if rangeB == 0, emit 0.5 (midline) to prevent division-by-zero.
timeseries pctB = (rangeB > 0) ? (c - dnB) / rangeB : 0.5

// -- 3.3 Optional smoothing of %B --
timeseries sm = (smoothLen > 1) ? (useEmaSmooth ? ema(pctB, smoothLen) : sma(pctB, smoothLen)) : pctB

// -- 3.4 Optional rescale to 0-100 --
timeseries out = rescale ? sm * 100.0 : sm

// -- 3.5 Regime detection (overbought / oversold / squeeze / neutral) --
// Thresholds are expressed in raw %B space (0-1) and rescaled if needed.
var obRaw = rescale ? 80 : 0.8
var osRaw = rescale ? 20 : 0.2
var midRaw = rescale ? 50 : 0.5

var regimeOverbought = out > obRaw
var regimeOversold = out < osRaw
var regimeMid = !regimeOverbought && !regimeOversold

// Squeeze detection: band width (%B range) is compressed relative to its
// rolling history. A narrow band width means price is coiling.
timeseries bandWidth = (rangeB > 0) ? (rangeB / basis) : 0
timeseries bwMean = sma(bandWidth, zWindow)
timeseries bwStd = stdev(bandWidth, zWindow)
timeseries bwZ = (bwStd > 0) ? (bandWidth - bwMean) / bwStd : 0
var isSqueeze = bwZ < -1.0 && bandWidth > 0

// -- 3.6 Static session tracking for regime persistence --
// Tracks consecutive bars in each regime and squeeze state for context-aware alerting.
static obBars = 0
static osBars = 0
static squeezeBars = 0
static lastPctB = 0.0

if (regimeOverbought) {
    obBars = obBars + 1
    osBars = 0
} else if (regimeOversold) {
    osBars = osBars + 1
    obBars = 0
} else {
    obBars = 0
    osBars = 0
}

if (isSqueeze) {
    squeezeBars = squeezeBars + 1
} else {
    squeezeBars = 0
}

if (!isnan(out[0])) {
    lastPctB = out[0]
}

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// 4.1 Bollinger Bands on the main price chart (plotLine)
if (showBands) {
    plotLine(
        value=([upB, basis, dnB]),
        width=1,
        colors=[bandColor, midColor, bandColor],
        label=["Upper Band", "Basis", "Lower Band"],
        desc=["Upper Bollinger Band (SMA + " + mult + "σ)", "Basis (SMA/EMA " + len + ")", "Lower Bollinger Band (SMA − " + mult + "σ)"]
    )
}

// 4.2 Band fill (fill between upper and lower bands)
if (showBandFill && showBands) {
    plotLine(
        value=([upB, dnB]),
        width=1,
        colors=[transparency(bandColor, 85), transparency(bandColor, 85)],
        fill=true,
        label=["Band Fill"],
        desc=["Bollinger Band fill area showing ±" + mult + "σ envelope"]
    )
}

// 4.3 %B line with regime colour coding (plotLine)
if (showPctB) {
    timeseries pctBColor = regimeOverbought ? upColor : (regimeOversold ? dnColor : midColor)
    plotLine(
        value=out,
        width=2,
        colors=[pctBColor],
        label=["%B"],
        desc=["Bollinger Band %B: 0 = lower band, 1 = upper band, 0.5 = basis"]
    )
}

// 4.4 %B fill vs midline (plotLine with fill)
if (showPctBFill) {
    timeseries midLine = rescale ? 50 : 0.5
    timeseries fillBull = out > midLine
    plotLine(
        value=([out, midLine]),
        width=1,
        colors=[transparency(upColor, 30), transparency(dnColor, 30)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["%B", "Midline"],
        desc=["Fill between %B and midline; above = bullish zone, below = bearish zone"]
    )
}

// 4.5 %B bars (plotBar) — regime-coloured
timeseries barColorIdx = regimeOverbought ? 0 : (regimeOversold ? 1 : 2)
if (showBars) {
    plotBar(
        value=out,
        colors=[upColor, dnColor, midColor],
        colorIndex=barColorIdx,
        width=1,
        label=["%B Bars"],
        desc=["Bollinger Band %B as bars; colour-coded by overbought/oversold/mid regime"]
    )
}

// 4.6 Extreme %B shapes (plotShape)
if (showShapes && regimeOverbought && obBars == 1) {
    plotShape(
        value=obRaw,
        shape="triangledown",
        colorIndex=upColor,
        width=2,
        label=["Overbought"],
        desc=["Price near upper Bollinger Band; potential exhaustion / mean-reversion zone"]
    )
}
if (showShapes && regimeOversold && osBars == 1) {
    plotShape(
        value=osRaw,
        shape="triangleup",
        colorIndex=dnColor,
        width=2,
        label=["Oversold"],
        desc=["Price near lower Bollinger Band; potential bounce / mean-reversion zone"]
    )
}

// 4.7 Squeeze detection shapes (plotShape)
if (showSqueeze && isSqueeze && squeezeBars == 1) {
    plotShape(
        value=midRaw,
        shape="circle",
        colorIndex=squeezeColor,
        width=2,
        label=["Squeeze"],
        desc=["Bollinger Band width compressed; volatility expansion likely imminent"]
    )
}

// 4.8 Reference lines (hline)
if (rescale) {
    hline(value=100, color="#ffffff30", width=1)
    hline(value=80, color=transparency(upColor, 60), width=1)
    hline(value=50, color="#88888860", width=1)
    hline(value=20, color=transparency(dnColor, 60), width=1)
    hline(value=0, color="#ffffff30", width=1)
} else {
    hline(value=1.0, color="#ffffff30", width=1)
    hline(value=0.8, color=transparency(upColor, 60), width=1)
    hline(value=0.5, color="#88888860", width=1)
    hline(value=0.2, color=transparency(dnColor, 60), width=1)
    hline(value=0.0, color="#ffffff30", width=1)
}

// 4.9 Regime summary table (last bar only)
if (isLastBar) {
    var regimeText = regimeOverbought ? "OVERBOUGHT" : (regimeOversold ? "OVERSOLD" : "NEUTRAL")
    var regimeTextColor = regimeOverbought ? upColor : (regimeOversold ? dnColor : midColor)
    var squeezeText = isSqueeze ? "SQUEEZE" : "EXPANSION"
    var squeezeTextColor = isSqueeze ? squeezeColor : midColor

    plotTable(
        data=[
            ["%B V2 — Regime", regimeText],
            ["%B Value", out[0]],
            ["Band Width Z", bwZ[0]],
            ["Squeeze State", squeezeText],
            ["OB Bars", obBars],
            ["OS Bars", osBars],
            ["Basis", basis[0]]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}