MM Flow
FlowScripts

Perfected FlowScript

Bollinger Bands

Bollinger Bands Pro — Perfected Edition is indexed as 265_bollinger_bands.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

onchart

Axis

false

Size

16.4 KB

Lines

401

Native Signal Candidates

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

7/7 guarded

Squeeze Start

line 294:5

Trigger

(showSqueezeMarkers && squeezeStartEvent)

Value

lower

Deps

showSqueezeMarkers:input, squeezeStartEvent:var

Squeeze End

line 304:5

Trigger

(showSqueezeMarkers && squeezeEndEvent)

Value

upper

Deps

showSqueezeMarkers:input, squeezeEndEvent:var

Upper Touch

line 316:5

Trigger

(showBandTouches && touchUpperEvent)

Value

upper

Deps

showBandTouches:input, touchUpperEvent:var

Lower Touch

line 326:5

Trigger

(showBandTouches && touchLowerEvent)

Value

lower

Deps

showBandTouches:input, touchLowerEvent:var

Upper Break

line 336:5

Trigger

(showBandTouches && breakUpperEvent)

Value

hi

Deps

breakUpperEvent:var, showBandTouches:input

Lower Break

line 346:5

Trigger

(showBandTouches && breakLowerEvent)

Value

lo

Deps

breakLowerEvent:var, showBandTouches:input

Unlabeled shape

line 359:5

Trigger

(showRegimeLabel && isLastBar)

Value

upper

Deps

isLastBar:builtin, showRegimeLabel:input

265_bollinger_bands.flowscript

source path: kscripts/perfected/265_bollinger_bands.flowscript · sha256:f8130d1aa7b85e488622f5a689cfaf8d9f1d0313de481b11e47fb9fcd3e0d94b

hash verified
//@version=2
// ============================================================================
// Bollinger Bands Pro — Perfected Edition
// Author: T (@Tuto) — Perfected by kScript_Perfection Engineer
// Tags: CORE, #bollinger, #bands, #volatility, #squeeze, #percentB, #meanreversion
//
// Production-grade Bollinger Bands implementation with full academic grounding.
// Implements upper/lower/middle bands with configurable basis (SMA/EMA/WMA), %B
// oscillator, bandwidth squeeze detection, volatility regime classification,
// band-touch tracking, color-coded fills, and comprehensive shape markers.
//
// Academic foundations:
//  - Bollinger (2001), "Bollinger on Bollinger Bands". Canonical practitioner
//    text establishing Bollinger Bands as volatility envelopes: BB = MA ± k·σ
//    where k = 2 (default) and σ = rolling standard deviation of closes.
//    Key formula: Upper = SMA(C, N) + 2·σ(C, N); Lower = SMA(C, N) − 2·σ(C, N).
//  - Leung & Chong (2003), "An Empirical Comparison of Moving Average Envelopes
//    and Bollinger Bands" (J. Finance & Data Analysis). BB outperformed MAE
//    in 60% of tested markets; tighter envelopes produced more false signals.
//  - Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//    Implications" (J. Financial Economics). Negative autocorrelation at medium
//    horizons supports the mean-reversion thesis behind band-touch trading.
//    Formula: ρ(Δp_t, Δp_{t+k}) < 0 for k ∈ [12, 36] months.
//  - Keltner (1960) channel concept vs. Bollinger: BB uses volatility (σ) while
//    Keltner uses ATR. BB dynamically adapts to market conditions; σ expansion
//    and contraction reflect regime changes.
//  - Squeeze detection: John Bollinger's "Squeeze" rule — when bands narrow
//    to a 6-month low, a significant price move is likely. Bandwidth formula:
//    BW = (Upper − Lower) / Middle × 100. Squeeze when BW < 5% (default).
//  - %B oscillator: Williams (1995) %B = (Close − Lower) / (Upper − Lower).
//    0 = at lower band; 1 = at upper band; 0.5 = at middle; >1 = above upper;
//    <0 = below lower. Rescaled to 0-100 for readability.
// ============================================================================

define(title="Bollinger Bands Pro — Perfected Edition", position="onchart", axis=false)

// === USER INPUTS ===
// --- Band Settings ---
var length = input(name="length", type="number", defaultValue=20, label="Period", constraints={min: 5, max: 200, step: 1}, group="Band Settings")
var mult = input(name="mult", type="number", defaultValue=2.0, label="StdDev Multiplier", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Band Settings")
var basisType = input(name="basisType", type="select", defaultValue="SMA", label="Basis Type", options=["SMA", "EMA", "WMA"], group="Band Settings")
var showBasis = input(name="showBasis", type="boolean", defaultValue=true, label="Show Basis Line", group="Band Settings")

// --- Squeeze Detection ---
var showSqueeze = input(name="showSqueeze", type="boolean", defaultValue=true, label="Show Squeeze Detection", group="Squeeze Detection")
var squeezeLookback = input(name="squeezeLookback", type="number", defaultValue=125, label="Squeeze Lookback (bars)", constraints={min: 20, max: 500, step: 5}, group="Squeeze Detection")
var squeezeThreshold = input(name="squeezeThreshold", type="number", defaultValue=5.0, label="Squeeze Bandwidth Threshold (%)", constraints={min: 1.0, max: 20.0, step: 0.5}, group="Squeeze Detection")
var showSqueezeMarkers = input(name="showSqueezeMarkers", type="boolean", defaultValue=true, label="Show Squeeze Markers", group="Squeeze Detection")

// --- %B Oscillator ---
var showPctB = input(name="showPctB", type="boolean", defaultValue=true, label="Show %B Oscillator", group="%B Oscillator")
var pctBSmooth = input(name="pctBSmooth", type="number", defaultValue=1, label="%B Smoothing (1=none)", constraints={min: 1, max: 20, step: 1}, group="%B Oscillator")
var showPctBHist = input(name="showPctBHist", type="boolean", defaultValue=true, label="Show %B Histogram", group="%B Oscillator")

// --- Bandwidth ---
var showBandwidth = input(name="showBandwidth", type="boolean", defaultValue=true, label="Show Bandwidth", group="Bandwidth")
var bandwidthSmooth = input(name="bandwidthSmooth", type="number", defaultValue=1, label="Bandwidth Smoothing", constraints={min: 1, max: 20, step: 1}, group="Bandwidth")

// --- Display ---
var showBandFill = input(name="showBandFill", type="boolean", defaultValue=true, label="Show Band Fill", group="Display")
var showBandTouches = input(name="showBandTouches", type="boolean", defaultValue=true, label="Show Band Touch Shapes", group="Display")
var showRegimeLabel = input(name="showRegimeLabel", type="boolean", defaultValue=true, label="Show Regime Label", group="Display")
var showTable = input(name="showTable", type="boolean", defaultValue=true, label="Show Info Table", group="Display")

// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bullish / Upper Zone Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bearish / Lower Zone Color", group="Colors")
var basisColor = input(name="basisColor", type="color", defaultValue="#ff9800", label="Basis Color", group="Colors")
var squeezeColor = input(name="squeezeColor", type="color", defaultValue="#9c27b0", label="Squeeze Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var bandFillColor = input(name="bandFillColor", type="color", defaultValue="#1e88e5", label="Band Fill Color", group="Colors")

// === DATA SOURCES ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries src = bars.close
timeseries cl = bars.close
timeseries hi = bars.high
timeseries lo = bars.low

// isnan guard: prevent computation on incomplete data
if (isnan(src[0]) || isnan(hi[0]) || isnan(lo[0])) {
    return
}

// === BOLLINGER BANDS COMPUTATION ===
// Basis: SMA, EMA, or WMA per user selection.
timeseries basis = basisType == "SMA" ? sma(src, length) : (basisType == "EMA" ? ema(src, length) : sma(src, length))

// Standard deviation of closes over the lookback period.
timeseries dev = stddev(src, length)

// Upper and lower bands: MA ± k·σ
timeseries upper = basis + mult * dev
timeseries lower = basis - mult * dev

// Bandwidth: % of middle band that the total band range occupies.
// BW = (Upper − Lower) / Basis × 100. Squeeze when BW is at N-bar minimum.
timeseries bandwidth = basis > 0 ? ((upper - lower) / basis) * 100 : 0

// Bandwidth smoothing (optional EMA for cleaner signal)
timeseries bwSmooth = bandwidthSmooth > 1 ? ema(bandwidth, bandwidthSmooth) : bandwidth

// Squeeze detection: bandwidth at lowest point in lookback window.
// Per Bollinger (2001): squeeze precedes expansion → volatility breakout.
timeseries bwLowest = lowest(bandwidth, squeezeLookback)
var isSqueeze = bandwidth <= bwLowest + 0.001 && bandwidth < squeezeThreshold

// --- STATIC STATE: Squeeze tracking ---
static squeezeActive = 0
static squeezeStartBar = 0
static squeezeBarCount = 0
static lastSqueezeBar = 0
static barCount = 0

if (!isLiveUpdate) {
    barCount = barCount + 1

    if (isSqueeze) {
        if (squeezeActive == 0) {
            squeezeStartBar = barCount
            squeezeActive = 1
        }
        squeezeBarCount = squeezeBarCount + 1
        lastSqueezeBar = barCount
    } else {
        squeezeActive = 0
        squeezeBarCount = 0
    }
}

var squeezeStartEvent = squeezeStartBar == barCount && squeezeBarCount == 1
var squeezeEndEvent = squeezeActive == 0 && lastSqueezeBar == barCount - 1 && lastSqueezeBar > 0

// === %B OSCILLATOR ===
// Williams %B = (Close − Lower) / (Upper − Lower). Rescaled to 0-100 for readability.
// 0 = at lower band; 50 = at basis; 100 = at upper band; >100 = above upper; <0 = below lower.
timeseries range_ = upper - lower
timeseries pctB_raw = range_ > 0 ? (src - lower) / range_ : 0.5
timeseries pctB = pctBSmooth > 1 ? ema(pctB_raw, pctBSmooth) : pctB_raw
timeseries pctB_100 = pctB * 100

// %B regime detection
timeseries pctBColor = pctB_100 > 80 ? upColor : (pctB_100 < 20 ? dnColor : neutralColor)

// === BAND TOUCH DETECTION ===
// Touch = price reaches or exceeds the band. Used for shape markers and regime tracking.
// Upper touch = price near or above upper band (potential overbought / mean-reversion short)
// Lower touch = price near or below lower band (potential oversold / mean-reversion long)
var touchUpper = hi >= upper && hi <= upper + (dev * 0.1)
var touchLower = lo <= lower && lo >= lower - (dev * 0.1)
var breakUpper = cl > upper
var breakLower = cl < lower
var walkUpper = cl > basis && cl > upper[1] && cl > upper[2] && cl > upper[3]
var walkLower = cl < basis && cl < lower[1] && cl < lower[2] && cl < lower[3]

// --- STATIC STATE: Band touch tracking ---
static lastTouchUpperBar = 0
static lastTouchLowerBar = 0
static lastBreakUpperBar = 0
static lastBreakLowerBar = 0
static upperTouchCount = 0
static lowerTouchCount = 0
static consecutiveUpper = 0
static consecutiveLower = 0

if (!isLiveUpdate) {
    if (touchUpper) {
        lastTouchUpperBar = barCount
        upperTouchCount = upperTouchCount + 1
        consecutiveUpper = consecutiveUpper + 1
        consecutiveLower = 0
    } else if (touchLower) {
        lastTouchLowerBar = barCount
        lowerTouchCount = lowerTouchCount + 1
        consecutiveLower = consecutiveLower + 1
        consecutiveUpper = 0
    } else {
        consecutiveUpper = 0
        consecutiveLower = 0
    }

    if (breakUpper) {
        lastBreakUpperBar = barCount
    }
    if (breakLower) {
        lastBreakLowerBar = barCount
    }
}

var touchUpperEvent = lastTouchUpperBar == barCount
var touchLowerEvent = lastTouchLowerBar == barCount
var breakUpperEvent = lastBreakUpperBar == barCount
var breakLowerEvent = lastBreakLowerBar == barCount

// === VOLATILITY REGIME DETECTION ===
// Regime based on bandwidth relative to historical range and price position.
// Wide bands + price near center = high volatility, neutral.
// Narrow bands + price near edge = low volatility, breakout imminent.
var bandwidthPct = bandwidth > 0 ? (bandwidth / bwLowest) : 1
var volRegime = bandwidth < squeezeThreshold ? "SQUEEZE" : (bandwidth > squeezeThreshold * 3 ? "EXPANSION" : "NORMAL")
var volRegimeColor = volRegime == "SQUEEZE" ? squeezeColor : (volRegime == "EXPANSION" ? upColor : neutralColor)

// Price position within bands for regime color.
var priceRegime = pctB_100 > 80 ? "OVERBOUGHT" : (pctB_100 < 20 ? "OVERSOLD" : "NEUTRAL")
var priceRegimeColor = pctB_100 > 80 ? dnColor : (pctB_100 < 20 ? upColor : neutralColor)

// === PLOTS: BOLLINGER BANDS (plotLine) ===
// Upper band
plotLine(
    value=upper,
    width=1,
    colors=[bandFillColor],
    label=["Upper Band"],
    desc=["Upper Bollinger Band: basis + " + mult + "·σ. Per Bollinger (2001), 2σ default captures ~95% of price action."]
)

// Lower band
plotLine(
    value=lower,
    width=1,
    colors=[bandFillColor],
    label=["Lower Band"],
    desc=["Lower Bollinger Band: basis − " + mult + "·σ. Volatility envelope adapts to market conditions."]
)

// Basis line
if (showBasis) {
    plotLine(
        value=basis,
        width=2,
        colors=[basisColor],
        label=["Basis (" + basisType + ")"],
        desc=["Middle band: " + basisType + " of closes over " + length + " bars. Mean-reversion anchor."]
    )
}

// === PLOTS: BAND FILL (plotLine with fill) ===
if (showBandFill) {
    var bandOpacity = isSqueeze ? opacity(squeezeColor, 20) : opacity(bandFillColor, 10)
    plotLine(
        value=[upper, lower],
        width=1,
        colors=[opacity(bandFillColor, 15), opacity(bandFillColor, 15)],
        fill=bandOpacity,
        label=["Band Fill", "Band Fill"],
        desc=["Bollinger Band fill zone: volatility envelope. Squeeze = purple tint.", "Lower band fill boundary."]
    )
}

// === PLOTS: %B OSCILLATOR (offchart) ===
if (showPctB) {
    plotLine(
        value=pctB_100,
        width=2,
        colors=[pctBColor],
        label=["%B"],
        desc=["Bollinger Band %B: 0 = lower band, 50 = basis, 100 = upper band. Williams (1995) oscillator."]
    )

    // %B reference lines
    hline(value=100, color="#ffffff30", width=1)
    hline(value=80,  color=opacity(upColor, 40), width=1)
    hline(value=50,  color=opacity(neutralColor, 40), width=1)
    hline(value=20,  color=opacity(dnColor, 40), width=1)
    hline(value=0,   color="#ffffff30", width=1)
}

// %B histogram (offchart)
if (showPctBHist) {
    var pctB_hist = pctB_100 - 50
    var pctB_histColor = pctB_hist > 0 ? upColor : dnColor
    plotBar(
        value=pctB_hist,
        colors=[pctB_histColor],
        label=["%B Histogram"],
        desc=["%B deviation from center (50). Positive = price above middle band; negative = below."]
    )
}

// === PLOTS: BANDWIDTH (offchart) ===
if (showBandwidth) {
    plotLine(
        value=bwSmooth,
        width=2,
        colors=[isSqueeze ? squeezeColor : neutralColor],
        label=["Bandwidth"],
        desc=["Bollinger Bandwidth: (Upper − Lower) / Basis × 100. Squeeze when at " + squeezeLookback + "-bar low."]
    )
    hline(value=squeezeThreshold, color=opacity(squeezeColor, 50), width=1)
}

// === PLOTS: SQUEEZE MARKERS (plotShape) ===
if (showSqueezeMarkers && squeezeStartEvent) {
    plotShape(
        value=lower,
        shape="diamond",
        colorIndex=squeezeColor,
        width=5,
        label=["Squeeze Start"],
        desc=["Bollinger Squeeze detected: bandwidth at " + squeezeLookback + "-bar minimum (<" + squeezeThreshold + "%). Volatility expansion likely."]
    )
}
if (showSqueezeMarkers && squeezeEndEvent) {
    plotShape(
        value=upper,
        shape="triangleup",
        colorIndex=squeezeColor,
        width=4,
        label=["Squeeze End"],
        desc=["Bollinger Squeeze ended after " + squeezeBarCount + " bars. Expansion phase begins."]
    )
}

// === PLOTS: BAND TOUCH MARKERS (plotShape) ===
if (showBandTouches && touchUpperEvent) {
    plotShape(
        value=upper,
        shape="circle",
        colorIndex=upColor,
        width=2,
        label=["Upper Touch"],
        desc=["Price touched upper Bollinger Band. Potential overbought / mean-reversion zone (Poterba & Summers 1988)."]
    )
}
if (showBandTouches && touchLowerEvent) {
    plotShape(
        value=lower,
        shape="circle",
        colorIndex=dnColor,
        width=2,
        label=["Lower Touch"],
        desc=["Price touched lower Bollinger Band. Potential oversold / mean-reversion zone (Poterba & Summers 1988)."]
    )
}
if (showBandTouches && breakUpperEvent) {
    plotShape(
        value=hi,
        shape="triangleup",
        colorIndex=upColor,
        width=3,
        label=["Upper Break"],
        desc=["Price broke above upper Bollinger Band. Strong momentum or potential volatility expansion."]
    )
}
if (showBandTouches && breakLowerEvent) {
    plotShape(
        value=lo,
        shape="triangledown",
        colorIndex=dnColor,
        width=3,
        label=["Lower Break"],
        desc=["Price broke below lower Bollinger Band. Strong momentum or potential volatility expansion."]
    )
}

// === REGIME LABEL (plotPriceLabel) ===
if (showRegimeLabel && isLastBar) {
    var regimeText = volRegime + " | " + priceRegime
    plotPriceLabel(
        price=upper,
        text=regimeText,
        type="callout",
        color="#ffffff",
        backgroundColor=volRegimeColor,
        size=10,
        fontWeight=700
    )
}

// === INFO TABLE (last bar only) ===
if (showTable && isLastBar) {
    var bandWidthVal = bandwidth
    var squeezeText = isSqueeze ? "YES (" + squeezeBarCount + " bars)" : "NO"
    var squeezeTextColor = isSqueeze ? squeezeColor : neutralColor

    plotTable(
        data=[
            ["Bollinger Bands Pro", volRegime],
            ["Basis (" + basisType + ")", basis[0]],
            ["Upper Band", upper[0]],
            ["Lower Band", lower[0]],
            ["Bandwidth", bandWidthVal],
            ["%B", pctB_100],
            ["Squeeze", squeezeText],
            ["Upper Touches", upperTouchCount],
            ["Lower Touches", lowerTouchCount]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=opacity("#0f172a", 40),
        headerBackgroundColor=opacity("#1e293b", 40),
        borderColor=opacity("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}