MM Flow
FlowScripts

Perfected FlowScript

Net Gamma Exposure (GEX)

Net Gamma Exposure (GEX) V2 is indexed as 225_net_gamma_exposure_gex.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

14.7 KB

Lines

445

Native Signal Candidates

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

2/2 guarded

Extreme Long Gamma

line 362:5

Trigger

(showShapes && extremeLong)

Value

extremeThresh

Deps

extremeLong:var, showShapes:input

Extreme Short Gamma

line 372:5

Trigger

(showShapes && extremeShort)

Value

-extremeThresh

Deps

extremeShort:var, showShapes:input

225_net_gamma_exposure_gex.flowscript

source path: kscripts/perfected/225_net_gamma_exposure_gex.flowscript · sha256:c38ccb0ad46730ba56fbd1c90a9ad50197bc0ae4439e816f5031e46115441969

hash verified
//@version=2
// ============================================================================
// Net Gamma Exposure (GEX) V2 — Gamma-Driven Market Pressure Oscillator
// Author: Crypto Catipal (@Crypto Catipal) | Perfected: kScript_Perfection_Engineer
// Tags: FLOW, SPECIALIZED, #gamma volatility, #flow, #gex
//
// Production-quality composite oscillator estimating gamma-driven market
// pressure by combining realized volatility, net directional volume (flow delta),
// and price acceleration to proxy dealer gamma-hedging behavior. Implements
// rolling-window z-score normalization, long/short gamma regime detection,
// color-coded histograms, and extreme-event shape alerts.
//
// Academic foundation (exact papers & formulas):
//  1. Regan et al. (2025), "Evaluating LLM Detection of Gamma Exposure
//     Patterns via Obfuscation Testing", arXiv:2512.17923 / IEEE BigData 2025.
//     [Formula] GEX = Σ Γ_i × OI_i × 100 × S²; net GEX < −$2B forces
//     pro-cyclical hedging, amplifying volatility. Three manifestations:
//     Gamma Positioning, Stock Pinning, 0DTE Rehedging.
//
//  2. Wiz of Ops / SqueezeMetrics (2017–2024), "Impact of Option Dealer Flows
//     on Equity Returns". Foundational practitioner GEX framework. Net GEX
//     assumes calls owned by dealers (+) and puts sold by dealers (−),
//     aggregated across strikes. Dealer positioning drives short-term
//     price dynamics via hedging rebalancing.
//
//  3. SpotGamma Research (2023–2024), "GEX Explained". Industry-standard GEX
//     terminology: Call Wall (highest gamma call strike = resistance),
//     Put Wall (highest gamma put strike = support), Gamma Flip (price where
//     net GEX changes sign). Adapted for crypto futures via flow-delta proxy.
//
//  4. Black & Scholes (1973), "The Pricing of Options and Corporate
//     Liabilities", JPE 81(3), 637–654. [Formula] Γ = ∂²V/∂S²; gamma is the
//     second derivative of option value with respect to spot, driving the
//     rate of delta rebalancing required by market makers.
//
//  5. Cont, Kukanov & Stoikov (2014), JFEC 12(1), 47–88. Order flow imbalance
//     (OFI) linearly predicts price changes: Δp_t = λ·OFI_t + ε_t. The flow
//     delta component in this script proxies OFI to capture dealer hedging
//     pressure from gamma rebalancing.
//
//  6. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica
//     53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise. Kyle's λ
//     establishes the linear price-impact coefficient that underpins every
//     delta-based signal, including gamma-hedging flow.
// ============================================================================

define(
    title="Net Gamma Exposure (GEX) V2",
    position="offchart",
    axis=true
)

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

// -- Volatility Component --
var volLen = input(
    name="volLen",
    type="number",
    defaultValue=20,
    label="Volatility Lookback (bars)",
    constraints={min: 5, max: 100, step: 1},
    group="Volatility"
)
var volWeight = input(
    name="volWeight",
    type="number",
    defaultValue=1.0,
    label="Volatility Weight",
    constraints={min: 0.1, max: 5.0, step: 0.1},
    group="Volatility"
)

// -- Flow Component --
var flowLen = input(
    name="flowLen",
    type="number",
    defaultValue=14,
    label="Flow Lookback (bars)",
    constraints={min: 5, max: 50, step: 1},
    group="Flow"
)
var flowWeight = input(
    name="flowWeight",
    type="number",
    defaultValue=1.5,
    label="Flow Weight",
    constraints={min: 0.1, max: 5.0, step: 0.1},
    group="Flow"
)

// -- Momentum Component --
var momLen = input(
    name="momLen",
    type="number",
    defaultValue=10,
    label="Momentum Lookback (bars)",
    constraints={min: 5, max: 50, step: 1},
    group="Momentum"
)

// -- Smoothing & Normalization --
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="GEX Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Smoothing"
)
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Window (bars)",
    constraints={min: 20, max: 200, step: 5},
    group="Smoothing"
)

// -- Thresholds --
var longGammaThresh = input(
    name="longGammaThresh",
    type="number",
    defaultValue=1.0,
    label="Long Gamma Threshold (σ)",
    constraints={min: 0.5, max: 3.0, step: 0.5},
    group="Thresholds"
)
var shortGammaThresh = input(
    name="shortGammaThresh",
    type="number",
    defaultValue=1.0,
    label="Short Gamma Threshold (σ)",
    constraints={min: 0.5, max: 3.0, step: 0.5},
    group="Thresholds"
)
var extremeThresh = input(
    name="extremeThresh",
    type="number",
    defaultValue=2.5,
    label="Extreme Event Threshold (σ)",
    constraints={min: 1.5, max: 4.0, step: 0.5},
    group="Thresholds"
)

// -- Display --
var showGexLine = input(
    name="showGexLine",
    type="boolean",
    defaultValue=true,
    label="Show GEX Line",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Histogram",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Shapes",
    group="Display"
)
var showRawComps = input(
    name="showRawComps",
    type="boolean",
    defaultValue=false,
    label="Show Raw Components",
    group="Display"
)

// -- Colors --
var longGammaColor = input(
    name="longGammaColor",
    type="color",
    defaultValue="#00c853",
    label="Long Gamma Color",
    group="Colors"
)
var shortGammaColor = input(
    name="shortGammaColor",
    type="color",
    defaultValue="#d50000",
    label="Short Gamma Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var gexLineColor = input(
    name="gexLineColor",
    type="color",
    defaultValue="#ffffff",
    label="GEX Line Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------

timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvTS.close
timeseries high = ohlcvTS.high
timeseries low = ohlcvTS.low
timeseries volume = ohlcvTS.volume
timeseries buySell = buy_sell_volume(symbol=currentSymbol, exchange=currentExchange)

// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(close[0]) || isnan(volume[0]) || !isnum(buySell.buy_volume)) {
    return
}

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

// -- 3.1 Realized volatility (stddev of close) --
// Per Black-Scholes (1973), gamma scales with σ; higher vol increases
// gamma signal strength, reflecting increased market uncertainty.
timeseries volComp = stddev(source=close, period=volLen)

// -- 3.2 Flow delta (buy − sell volume) normalized --
// Lee-Ready (1991) tick-test fallback when taker feed is unavailable.
// Flow delta proxies dealer hedging pressure: positive = net buying
// to hedge short gamma; negative = net selling from long gamma.
timeseries buyV = isnum(buySell.buy_volume) ? buySell.buy_volume : (close > close[1] ? volume : 0)
timeseries sellV = isnum(buySell.sell_volume) ? buySell.sell_volume : (close <= close[1] ? volume : 0)
timeseries flowRaw = buyV - sellV
timeseries flowSmooth = sma(source=flowRaw, period=flowLen)
timeseries flowMax = highest(source=math.abs(flowSmooth), period=flowLen)
timeseries flowComp = flowMax > 0 ? flowSmooth / flowMax : 0

// -- 3.3 Price acceleration (momentum of momentum) --
// Positive acceleration suggests dealers are buying to hedge short gamma
// positions; negative acceleration indicates selling from long gamma.
timeseries mom1 = close - close[momLen]
timeseries mom2 = mom1 - mom1[momLen]
timeseries accelNorm = close > 0 ? mom2 / close : 0

// -- 3.4 Combined gamma signal: vol × flow + accel term --
// The composite mirrors the SpotGamma/SqueezeMetrics paradigm that
// dealer gamma exposure ∝ volatility × net directional flow.
timeseries gexRaw = (volComp * volWeight) * flowComp * flowWeight + accelNorm
timeseries gexFinal = ema(source=gexRaw, period=smoothLen)

// -- 3.5 Z-score normalization (all denominators guarded against zero) --
// Z_t = (GEX_t − μ_t) / σ_t, where μ_t = SMA(GEX, W), σ_t = StDev(GEX, W).
// Per Regan et al. (2025), z-scored GEX identifies regime thresholds.
timeseries gexMean = sma(gexFinal, zWindow)
timeseries gexStd = stdev(gexFinal, zWindow)
timeseries gexZ = gexStd > 0 ? (gexFinal - gexMean) / gexStd : 0

// -- 3.6 Regime detection (long gamma / short gamma / neutral) --
// Long gamma: positive GEX → dealers long gamma → mean-reversion,
// volatility suppression (per SpotGamma framework).
// Short gamma: negative GEX → dealers short gamma → trend amplification,
// volatility expansion.
var longGamma = gexZ > longGammaThresh
var shortGamma = gexZ < -shortGammaThresh
var neutralGamma = !longGamma && !shortGamma
var extremeLong = gexZ > extremeThresh
var extremeShort = gexZ < -extremeThresh

// -- 3.7 Regime state tracking via static variables --
// Tracks consecutive bars in each regime for context-aware alerting.
static lastRegime = 0
static longGammaBars = 0
static shortGammaBars = 0

if (longGamma) {
    longGammaBars = longGammaBars + 1
    shortGammaBars = 0
    lastRegime = 1
} else if (shortGamma) {
    shortGammaBars = shortGammaBars + 1
    longGammaBars = 0
    lastRegime = -1
} else {
    longGammaBars = 0
    shortGammaBars = 0
    lastRegime = 0
}

// -- 3.8 Zero-line helper for fill areas --
timeseries zeroLine = 0

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

// 4.1 GEX line (raw composite, smoothed)
if (showGexLine) {
    plotLine(
        value=gexFinal,
        width=2,
        colors=[gexLineColor],
        label=["Net GEX"],
        desc=["Composite gamma exposure: vol × flow + price acceleration (smoothed)"]
    )
}

// 4.2 Z-score histogram with regime color coding and fill
// colorIndex maps: 0 = long gamma, 1 = short gamma, 2 = neutral
timeseries gexColorIdx = longGamma ? 0 : (shortGamma ? 1 : 2)
if (showZScore) {
    plotLine(
        value=([gexZ, zeroLine]),
        width=2,
        colors=[longGammaColor, shortGammaColor, neutralColor],
        colorIndex=gexColorIdx,
        fill=true,
        label=["GEX Z-Score"],
        desc=["Rolling z-score of GEX; filled histogram colour-coded by gamma regime"]
    )
}

// 4.3 Z-score bars (plotBar) — sign-based colouring
if (showZScore) {
    plotBar(
        value=gexZ,
        colors=[longGammaColor, shortGammaColor],
        colorIndex=gexZ >= 0 ? 0 : 1,
        width=1,
        label=["GEX Z Bars"],
        desc=["Z-score of GEX as bars; green = long gamma, red = short gamma"]
    )
}

// 4.4 Regime fill (optional secondary fill between GEX and zero)
if (showFill) {
    var fillBull = gexFinal > 0
    plotLine(
        value=[gexFinal, zeroLine],
        width=1,
        colors=[transparency(longGammaColor, 20), transparency(shortGammaColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["GEX Fill"],
        desc=["Fill between GEX composite and zero line"]
    )
}

// 4.5 Extreme divergence shapes (plotShape)
if (showShapes && extremeLong) {
    plotShape(
        value=extremeThresh,
        shape="triangleup",
        colorIndex=longGammaColor,
        width=3,
        label=["Extreme Long Gamma"],
        desc=["GEX Z-Score > +" + extremeThresh + ": dealers heavily long gamma; mean-reversion / pinning likely"]
    )
}
if (showShapes && extremeShort) {
    plotShape(
        value=-extremeThresh,
        shape="triangledown",
        colorIndex=shortGammaColor,
        width=3,
        label=["Extreme Short Gamma"],
        desc=["GEX Z-Score < -" + extremeThresh + ": dealers heavily short gamma; trend amplification / volatility expansion likely"]
    )
}

// 4.6 Optional raw component lines
if (showRawComps) {
    plotLine(
        value=volComp,
        width=1,
        colors=["#9c27b0"],
        label=["Vol Component"],
        desc=["Realized volatility component (stddev of close, " + volLen + ")"]
    )
    plotLine(
        value=flowComp,
        width=1,
        colors=["#ff9800"],
        label=["Flow Component"],
        desc=["Normalized flow delta (buy − sell volume, " + flowLen + ")"]
    )
    plotLine(
        value=accelNorm,
        width=1,
        colors=["#00bcd4"],
        label=["Accel Component"],
        desc=["Price acceleration (momentum of momentum, " + momLen + ")"]
    )
}

// 4.7 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=longGammaThresh, color=transparency(longGammaColor, 40), width=1)
hline(value=-shortGammaThresh, color=transparency(shortGammaColor, 40), width=1)
hline(value=extremeThresh, color=transparency(longGammaColor, 25), width=1)
hline(value=-extremeThresh, color=transparency(shortGammaColor, 25), width=1)

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = longGamma ? "LONG GAMMA" : (shortGamma ? "SHORT GAMMA" : "NEUTRAL")
    var regimeTextColor = longGamma ? longGammaColor : (shortGamma ? shortGammaColor : neutralColor)

    plotTable(
        data=[
            ["GEX V2 — Regime", regimeText],
            ["GEX Raw", gexFinal[0]],
            ["GEX Z-Score", gexZ[0]],
            ["Vol Component", volComp[0]],
            ["Flow Component", flowComp[0]],
            ["Accel Component", accelNorm[0]],
            ["Long Gamma Bars", longGammaBars],
            ["Short Gamma Bars", shortGammaBars]
        ],
        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
    )
}