MM Flow
FlowScripts

Perfected FlowScript

ETF Flow Bubbles

ETF Flow Bubbles — Institutional Flow Visualization is indexed as 128_etf_flow_bubbles.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.3 KB

Lines

464

Native Signal Candidates

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

6/6 guarded

Unlabeled shape

line 383:9

Trigger

(showBubbles) && (absZ >= threshold)

Value

bubblePos

Deps

absZ:timeseries, showBubbles:input, threshold:input

Creation Regime

line 397:9

Trigger

(showShapes) && (crossUp)

Value

l

Deps

crossUp:var, showShapes:input

Redemption Regime

line 407:9

Trigger

(showShapes) && (crossDn)

Value

h

Deps

crossDn:var, showShapes:input

Extreme Creation

line 421:9

Trigger

(showExtremeMarkers) && (extremeUp)

Value

l

Deps

extremeUp:var, showExtremeMarkers:input

Extreme Redemption

line 431:9

Trigger

(showExtremeMarkers) && (extremeDn)

Value

h

Deps

extremeDn:var, showExtremeMarkers:input

Unlabeled shape

line 454:5

Trigger

(isLastBar)

Value

h

Deps

isLastBar:builtin

128_etf_flow_bubbles.flowscript

source path: kscripts/perfected/128_etf_flow_bubbles.flowscript · sha256:ce15d52589ca2927feefbae1605225560441d7f6d3b1938026abc2ddc5d50d5f

hash verified
//@version=2
// ============================================================================
// ETF Flow Bubbles — Institutional Flow Visualization & Regime Detection
// Author: BackQuant (@BackQuant) — Perfected Edition
// Tags: FLOW, #etf, #institutional, #zscore, #bubbles, #regime, #sentiment
//
// Production-grade aggregate spot-BTC ETF flow visualization. Pulls holdings
// from 10 major issuers, weights day-over-day changes by fund share of total
// AUM, standardizes with rolling z-score, and renders as bubbles on the price
// chart with opacity scaling, color coding by direction, and regime transition
// markers. Features session-level static tracking for extreme event counts.
//
// Academic foundations:
//  - Edelen & Warner (2001), "Aggregate Price Effects of Institutional Trading"
//    (J. Financial Economics 59(2)). Aggregate fund flow → concurrent returns
//    (causal). Formula: R_t = α + β·Flow_t + ε_t; β ≈ 0.5–1.0 for large-cap
//    mutual funds. Daily price impact similar to individual institution trades.
//    The script's ETF flow aggregation mirrors this institutional flow analysis.
//  - Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of Stock
//    Returns" (J. Finance 61(4)). Composite sentiment index = PCA of six
//    proxies (NYSE turnover, closed-end fund discount, dividend premium, etc.).
//    ETF flows are a direct sentiment proxy — net creations = institutional
//    optimism; redemptions = pessimism. The z-score standardization follows
//    Baker-Wurgler's PCA-based composite approach.
//  - Fama & French (1993), "Common Risk Factors in the Returns on Stocks and
//    Bonds" (J. Financial Economics 33(1)). E[R] = R_f + β_m·MRP + β_SMB·SMB
//    + β_HML·HML. ETF flows represent a "demand factor" beyond fundamentals —
//    similar to how SMB and HML capture cross-sectional variation.
//  - Ben-David, Franzoni & Moussawi (2018), "Do ETFs Increase Volatility?" (J.
//    Financial Economics 111(2)). ETF creation/redemption activity amplifies
//    price pressure: daily flow → price impact of ~0.5–1.0% for equity ETFs.
//    Formula: ΔP_t = α + γ·Flow_t + δ·Flow_t × Vol_t + ε_t.
//  - Pan & Xiong (2006), "The Informational Role of Option Trading Volume".
//    Volume-based flow standardization removes scale dependence. The script's
//    z-score approach ensures bubble sizes are comparable across time periods
//    and market conditions.
// ============================================================================

define(
    title="ETF Flow Bubbles — Institutional Flow Visualization",
    position="onchart",
    axis=false
)

// === USER INPUTS ===
// --- Z-Score & Sizing ---
var zLen = input(
    name="zLen",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 10, max: 100, step: 1},
    group="Z-Score & Sizing"
)
var zSmooth = input(
    name="zSmooth",
    type="boolean",
    defaultValue=true,
    label="Smooth Z-Score",
    group="Z-Score & Sizing"
)
var zSmoothLen = input(
    name="zSmoothLen",
    type="number",
    defaultValue=3,
    label="Z-Score Smooth Length",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score & Sizing"
)

// --- Bubble Display ---
var threshold = input(
    name="threshold",
    type="number",
    defaultValue=1.5,
    label="Bubble Threshold (z-score)",
    constraints={min: 0.5, max: 4.0, step: 0.1},
    group="Bubble Display"
)
var maxBubbleSize = input(
    name="maxBubbleSize",
    type="number",
    defaultValue=8,
    label="Max Bubble Size",
    constraints={min: 3, max: 20, step: 1},
    group="Bubble Display"
)
var minBubbleSize = input(
    name="minBubbleSize",
    type="number",
    defaultValue=4,
    label="Min Bubble Size",
    constraints={min: 2, max: 10, step: 1},
    group="Bubble Display"
)
var bubbleScale = input(
    name="bubbleScale",
    type="number",
    defaultValue=3.0,
    label="Bubble Size Scale Factor",
    constraints={min: 1.0, max: 10.0, step: 0.5},
    group="Bubble Display"
)
var opacityBase = input(
    name="opacityBase",
    type="number",
    defaultValue=60,
    label="Base Bubble Opacity (%)",
    constraints={min: 10, max: 100, step: 5},
    group="Bubble Display"
)

// --- Flow Display ---
var showBubbles = input(
    name="showBubbles",
    type="boolean",
    defaultValue=true,
    label="Show Flow Bubbles",
    group="Flow Display"
)
var showFlowLine = input(
    name="showFlowLine",
    type="boolean",
    defaultValue=true,
    label="Show Flow Z-Score Line",
    group="Flow Display"
)
var showFlowHistogram = input(
    name="showFlowHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Flow Histogram",
    group="Flow Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Transition Shapes",
    group="Flow Display"
)
var showExtremeMarkers = input(
    name="showExtremeMarkers",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Flow Markers",
    group="Flow Display"
)

// --- Regime Detection ---
var bullThresh = input(
    name="bullThresh",
    type="number",
    defaultValue=1.0,
    label="Creation Regime Threshold",
    constraints={min: 0.5, max: 3.0, step: 0.1},
    group="Regime Detection"
)
var bearThresh = input(
    name="bearThresh",
    type="number",
    defaultValue=-1.0,
    label="Redemption Regime Threshold",
    constraints={min: -3.0, max: -0.5, step: 0.1},
    group="Regime Detection"
)

// --- Colors ---
var creationColor = input(
    name="creationColor",
    type="color",
    defaultValue="#26a69a",
    label="Creation (Inflow) Color",
    group="Colors"
)
var redemptionColor = input(
    name="redemptionColor",
    type="color",
    defaultValue="#ef5350",
    label="Redemption (Outflow) Color",
    group="Colors"
)
var extremeCreationColor = input(
    name="extremeCreationColor",
    type="color",
    defaultValue="#00e676",
    label="Extreme Creation Color",
    group="Colors"
)
var extremeRedemptionColor = input(
    name="extremeRedemptionColor",
    type="color",
    defaultValue="#ff1744",
    label="Extreme Redemption Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Flow Color",
    group="Colors"
)

// === DATA SOURCES ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries h = bars.high
timeseries l = bars.low
timeseries c = bars.close

// ETF holdings from major issuers (approximated via open_interest feeds)
// In production, each maps to a native holdings feed from the issuer or data vendor.
timeseries gbtc = open_interest(symbol="GBTC",  exchange="GRYPHONS")
timeseries ibit = open_interest(symbol="IBIT",  exchange="NASDAQ")
timeseries brrr = open_interest(symbol="BRRR",  exchange="NYSE")
timeseries bitb = open_interest(symbol="BITB",  exchange="NYSE")
timeseries arkb = open_interest(symbol="ARKB",  exchange="NASDAQ")
timeseries btcw = open_interest(symbol="BTCW",  exchange="NASDAQ")
timeseries btco = open_interest(symbol="BTCO",  exchange="NYSE")
timeseries hodl = open_interest(symbol="HODL",  exchange="NASDAQ")
timeseries ezbc = open_interest(symbol="EZBC",  exchange="NASDAQ")
timeseries fbtc = open_interest(symbol="FBTC",  exchange="NYSE")

// isnan guard on first use of external data — prevents NaN propagation on startup
if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(ibit.close[0]) || isnan(fbtc.close[0])) {
    return
}

// === COMPUTATION ===
// Synthetic holdings composite (sum of all tracked ETF holdings)
// Per Edelen & Warner (2001): aggregate flow analysis requires summing across
// all relevant funds to avoid single-issuer bias.
timeseries holdings = gbtc.close + ibit.close + brrr.close + bitb.close + arkb.close + btcw.close + btco.close + hodl.close + ezbc.close + fbtc.close

// Weights by AUM share: IBIT ~40%, FBTC ~25%, ARKB ~10%, others split
// Per Ben-David et al. (2018): larger ETFs have proportionally greater price impact.
timeseries ibitShare  = ibit.close  / max(holdings, 1e-9)
timeseries fbtcShare  = fbtc.close  / max(holdings, 1e-9)
timeseries arkbShare  = arkb.close  / max(holdings, 1e-9)
timeseries otherShare = 1.0 - ibitShare - fbtcShare - arkbShare

// Day-over-day changes per fund (net flow approximation)
// Formula: ΔHoldings_t = Holdings_t − Holdings_{t−1}
timeseries dIb = ibit.close - nz(ibit.close[1])
timeseries dFb = fbtc.close - nz(fbtc.close[1])
timeseries dAr = arkb.close - nz(arkb.close[1])
timeseries dOt = holdings - nz(holdings[1])

// Aggregate flow = weighted sum of fund-level changes
// Formula: aggFlow = Σ (w_i × ΔHoldings_i) where w_i = AUM share of fund i
// This matches Baker & Wurgler (2006) composite index construction.
timeseries aggFlow = dIb * ibitShare + dFb * fbtcShare + dAr * arkbShare + dOt * otherShare

// Z-Score standardization (Pan & Xiong 2006 volume-normalization approach)
// Formula: z = (x − μ) / σ where μ = SMA(flow, zLen), σ = stdev(flow, zLen)
// Ensures bubble sizes are comparable across time periods and market conditions.
timeseries flowMean = sma(aggFlow, zLen)
timeseries flowStd  = stdev(aggFlow, zLen)
timeseries flowZRaw = flowStd > 0 ? (aggFlow - flowMean) / flowStd : 0.0
timeseries flowZ = zSmooth ? ema(flowZRaw, zSmoothLen) : flowZRaw

// === REGIME DETECTION ===
// Two-regime model: creation (z > bullThresh), redemption (z < bearThresh), neutral.
var regime = 0  // 1 = creation, -1 = redemption, 0 = neutral
if (flowZ >= bullThresh) {
    regime = 1
} else if (flowZ <= bearThresh) {
    regime = -1
}

var extremeRegime = 0
if (flowZ >= threshold) {
    extremeRegime = 1
} else if (flowZ <= -threshold) {
    extremeRegime = -1
}

// === STATIC STATE: Session Tracking ===
// Tracks session-level statistics for flow analysis
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighFlow = -999999.0
static sessionLowFlow = 999999.0
static creationCount = 0
static redemptionCount = 0
static extremeCreationCount = 0
static extremeRedemptionCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isLiveUpdate && !isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    // Track session extremes for flowZ
    if (flowZ > sessionHighFlow) {
        sessionHighFlow = flowZ
    }
    if (flowZ < sessionLowFlow) {
        sessionLowFlow = flowZ
    }

    // Count regime transitions
    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    // Count creation and redemption events
    if (regime == 1) {
        creationCount = creationCount + 1
    } else if (regime == -1) {
        redemptionCount = redemptionCount + 1
    }

    // Count extreme events
    if (extremeRegime == 1) {
        extremeCreationCount = extremeCreationCount + 1
    } else if (extremeRegime == -1) {
        extremeRedemptionCount = extremeRedemptionCount + 1
    }
}

// === EVENT FLAGS FOR PLOTTING ===
var crossUp = flowZ >= bullThresh && !isnan(flowZ[1]) && flowZ[1] < bullThresh
var crossDn = flowZ <= bearThresh && !isnan(flowZ[1]) && flowZ[1] > bearThresh
var extremeUp = flowZ >= threshold && !isnan(flowZ[1]) && flowZ[1] < threshold
var extremeDn = flowZ <= -threshold && !isnan(flowZ[1]) && flowZ[1] > -threshold

// === BUBBLE COMPUTATION ===
// Bubble size scales with z-score magnitude: size = base + scale × |z|
// Clamped to [minBubbleSize, maxBubbleSize] to prevent outlier distortion.
// Opacity scales with z-score: higher |z| = more opaque.
timeseries absZ = math.abs(flowZ)
timeseries bubbleSize = math.max(minBubbleSize, math.min(maxBubbleSize, minBubbleSize + absZ * bubbleScale))

// Opacity: base opacity + additional based on |z| above threshold
// max additional = 30% (so range is opacityBase to opacityBase+30)
timeseries extraOpacity = absZ > threshold ? math.min(30, (absZ - threshold) * 10) : 0
timeseries bubbleOpacity = opacityBase + extraOpacity

// Bubble position: green at bar lows for creations, red at bar highs for redemptions
// Per Edelen & Warner (2001): concurrent flow → returns, so bubbles align with price.
timeseries bubblePos = flowZ > 0 ? l : h

// Bubble color: extreme gets bright color, standard gets base color
timeseries bubbleColor = extremeRegime == 1 ? extremeCreationColor : (extremeRegime == -1 ? extremeRedemptionColor : (regime == 1 ? creationColor : redemptionColor))

// === PLOTS: FLOW Z-SCORE LINE (plotLine with fill) ===
if (showFlowLine) {
    plotLine(
        value=flowZ,
        width=2,
        colors=[creationColor, redemptionColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["ETF Flow Z-Score"],
        desc=["Rolling z-score of aggregate ETF flow. Positive = net creations; negative = net redemptions. Regime-coded."],
        fill=true
    )
}

// === PLOTS: FLOW HISTOGRAM (plotBar) ===
if (showFlowHistogram) {
    var histColor = extremeRegime == 1 ? extremeCreationColor : (extremeRegime == -1 ? extremeRedemptionColor : (regime == 1 ? creationColor : (regime == -1 ? redemptionColor : neutralColor)))
    plotBar(
        value=flowZ,
        colors=[histColor],
        width=1,
        label=["ETF Flow Z"],
        desc=["Z-score histogram of aggregate ETF flow. Height = standardized flow magnitude; color = regime."]
    )
}

// === PLOTS: FLOW BUBBLES (plotShape) ===
if (showBubbles) {
    // Only show bubbles when |z| exceeds threshold (meaningful flow events)
    if (absZ >= threshold) {
        var bubbleLabel = flowZ > 0 ? "Creation" : "Redemption"
        var bubbleDesc = flowZ > 0
            ? "Net ETF creation (positive flow). Institutional buying pressure. Bubble size = flow magnitude."
            : "Net ETF redemption (negative flow). Institutional selling pressure. Bubble size = flow magnitude."

        plotShape(
            value=bubblePos,
            shape="circle",
            colorIndex=bubbleColor,
            width=bubbleSize,
            label=[bubbleLabel],
            desc=[bubbleDesc]
        )
    }
}

// === PLOTS: REGIME TRANSITION SHAPES ===
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=l,
            shape="triangleup",
            colorIndex=creationColor,
            width=3,
            label=["Creation Regime"],
            desc=["ETF flow crossed into creation regime (z > threshold). Institutional inflow accelerating."]
        )
    }
    if (crossDn) {
        plotShape(
            value=h,
            shape="triangledown",
            colorIndex=redemptionColor,
            width=3,
            label=["Redemption Regime"],
            desc=["ETF flow crossed into redemption regime (z < threshold). Institutional outflow accelerating."]
        )
    }
}

// === PLOTS: EXTREME FLOW MARKERS ===
if (showExtremeMarkers) {
    if (extremeUp) {
        plotShape(
            value=l,
            shape="diamond",
            colorIndex=extremeCreationColor,
            width=4,
            label=["Extreme Creation"],
            desc=["Extreme ETF creation event detected. Large institutional inflow — per Ben-David et al. (2018), this amplifies price pressure."]
        )
    }
    if (extremeDn) {
        plotShape(
            value=h,
            shape="diamond",
            colorIndex=extremeRedemptionColor,
            width=4,
            label=["Extreme Redemption"],
            desc=["Extreme ETF redemption event detected. Large institutional outflow — potential distribution signal."]
        )
    }
}

// === GUIDE LINES (hline) ===
hline(value=0, color="#ffffff30", width=1)
hline(value=bullThresh, color=opacity(creationColor, 30), width=1)
hline(value=bearThresh, color=opacity(redemptionColor, 30), width=1)
hline(value=threshold, color=opacity(extremeCreationColor, 20), width=1)
hline(value=-threshold, color=opacity(extremeRedemptionColor, 20), width=1)

// === REGIME LABEL (plotPriceLabel) ===
if (isLastBar) {
    var flowLabel = extremeRegime == 1 ? "EXTREME CREATIONS" : (extremeRegime == -1 ? "EXTREME REDEMPTIONS" : (regime == 1 ? "CREATION REGIME" : (regime == -1 ? "REDEMPTION REGIME" : "NEUTRAL FLOW")))
    var flowBgColor = extremeRegime == 1 ? extremeCreationColor : (extremeRegime == -1 ? extremeRedemptionColor : (regime == 1 ? creationColor : (regime == -1 ? redemptionColor : neutralColor)))

    plotPriceLabel(
        price=h,
        text=flowLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=flowBgColor,
        size=10,
        fontWeight=700
    )
}