MM Flow
FlowScripts

Perfected FlowScript

GEX Flip

GEX Flip V2 is indexed as 304_gex_flip.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

12.0 KB

Lines

382

Native Signal Candidates

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

3/3 guarded

Flip Long

line 352:9

Trigger

(showShapes) && (isFlipUp)

Value

px

Deps

isFlipUp:var, showShapes:input

Flip Short

line 362:9

Trigger

(showShapes) && (isFlipDown)

Value

px

Deps

isFlipDown:var, showShapes:input

Extreme GEX

line 372:9

Trigger

(showShapes) && (isExtremeGex && !anyFlip)

Value

px

Deps

anyFlip:var, isExtremeGex:var, showShapes:input

304_gex_flip.flowscript

source path: kscripts/perfected/304_gex_flip.flowscript · sha256:a67e9667d40b05d932834881e279e3f365064ee604b48797571eea6cb2120b45

hash verified
//@version=2
// ============================================================================
// GEX Flip V2 — Production-Quality Gamma Exposure Flip Detection
// Author: Crypto Catipal  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, #gamma, #flip, #gex, #regime, #volatility
//
// Identifies the price where aggregate Gamma Exposure (GEX) crosses zero —
// the "gamma flip" level where dealers switch from long gamma (dampening
// moves, chop regime) to short gamma (amplifying moves, trend regime).
// Implements z-score normalization, regime detection, and a color-coded
// histogram with shape-marked flip events.
//
// FORMULA FOUNDATION:
// 1. Gamma Exposure Proxy: GEX = (Price × Volume × |Returns|) / ATR
//    normalized by rolling standard deviation per Regan et al. (2025).
// 2. Flip Detection: Zero-crossing of smoothed GEX with confirmation
//    using hysteresis band to avoid noise flips per SpotGamma (2023-2024).
// 3. Z-Score Normalization: z = (GEX − μ_GEX) / σ_GEX over lookback window.
// 4. Regime Classification: Long gamma (GEX > 0, chop) vs Short gamma
//    (GEX < 0, trend) per FlashAlpha (2026) GEX Trading Guide.
//
// RESEARCH BASIS:
//  • Regan et al. (2025), "Evaluating LLM Detection of Gamma Exposure
//    Patterns via Obfuscation Testing". Documents three manifestations of
//    dealer hedging: Gamma Positioning (net GEX < −$2B forces pro-cyclical
//    hedging), Stock Pinning, and 0DTE Hedging. Core formula:
//    GEX = Σ Γᵢ × OIᵢ × 100 × S².
//  • SpotGamma Research (2023-2024), "GEX Explained". Coined GEX terminology;
//    introduced Gamma Flip as core metric. Positive GEX = dealers buy dips
//    and sell rallies (stabilizing). Negative GEX = dealers sell dips and
//    buy rallies (amplifying).
//  • FlashAlpha (2026), "GEX Trading Guide 2026". Defines GEX as total
//    dollar-value of stock dealers must buy/sell per 1% move. Gap between
//    flip events reveals regime duration — a temporal analysis feature.
//  • Hull & White (2017), "Optimal Delta Hedging for Options". Dealer gamma
//    hedging is rebalanced discretely; the GEX flip marks the boundary where
//    hedging direction inverts — the zero-crossing of net gamma.
// ============================================================================

define(
    title="GEX Flip V2",
    position="onchart",
    axis=false
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- GEX Calculation ---
var flipLen = input(
    name="flipLen",
    type="number",
    defaultValue=14,
    label="GEX Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="GEX"
)
var smoothing = input(
    name="smoothing",
    type="number",
    defaultValue=3,
    label="GEX Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="GEX"
)
var useATR = input(
    name="useATR",
    type="boolean",
    defaultValue=true,
    label="Normalize by ATR",
    group="GEX"
)
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 50, step: 1},
    group="GEX"
)

// --- Z-Score ---
var useZScore = input(
    name="useZScore",
    type="boolean",
    defaultValue=true,
    label="Enable Z-Score Normalization",
    group="Z-Score"
)
var zLookback = input(
    name="zLookback",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Z-Score"
)
var zThresh = input(
    name="zThresh",
    type="number",
    defaultValue=2.0,
    label="Z-Score Extreme Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Z-Score"
)

// --- Regime ---
var regimeSmooth = input(
    name="regimeSmooth",
    type="number",
    defaultValue=5,
    label="Regime Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Regime"
)
var hysteresis = input(
    name="hysteresis",
    type="number",
    defaultValue=0.05,
    label="Flip Hysteresis Band",
    constraints={min: 0.0, max: 0.5, step: 0.01},
    group="Regime"
)

// --- Display ---
var showFlipLn = input(
    name="showFlipLn",
    type="boolean",
    defaultValue=true,
    label="Show Flip Price Line",
    group="Display"
)
var showRegime = input(
    name="showRegime",
    type="boolean",
    defaultValue=true,
    label="Show Regime Indicator",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show GEX Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Flip Shapes",
    group="Display"
)
var showZBand = input(
    name="showZBand",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Bands",
    group="Display"
)

// --- Colors ---
var posColor = input(
    name="posColor",
    type="color",
    defaultValue="#26a69a",
    label="Long Gamma Color (Chop)",
    group="Colors"
)
var negColor = input(
    name="negColor",
    type="color",
    defaultValue="#ef5350",
    label="Short Gamma Color (Trend)",
    group="Colors"
)
var flipColor = input(
    name="flipColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Flip Level Color",
    group="Colors"
)
var extremeColor = input(
    name="extremeColor",
    type="color",
    defaultValue="#ab47bc",
    label="Extreme GEX Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries rng = bars.high - bars.low

// NaN guard — prevent execution before data is loaded
if (isnan(px[0])) {
    return
}

// ------------------------------------------------------------------------------
// Gamma Exposure Calculation (Regan et al. 2025 proxy)
// ------------------------------------------------------------------------------
// GEX proxy: momentum × volume / volatility, capturing the essence of
// dealer gamma positioning — when price moves with high volume on low
// volatility, dealers are heavily gamma-exposed and must hedge.

var ret = (px - px[1]) / (px[1] + 1e-9)
var momentum = sma(ret, smoothing)
var vola = sma(math.abs(ret), flipLen)

// ATR for normalization
var atrV = useATR ? sma(rng, atrLen) : 1.0
var atrSafe = atrV > 0 ? atrV : 1.0

// Raw GEX: momentum × volume / (ATR × volatility), normalized
var gexRaw = momentum * bars.volume / (atrSafe * (vola + 1e-9) + 1e-9)
var gex = sma(gexRaw, smoothing)

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018 framework)
// ------------------------------------------------------------------------------
var gexMean = sma(gex, zLookback)
var gexStd = stddev(gex, zLookback)
var gexZ = useZScore && gexStd > 0 ? (gex - gexMean) / (gexStd + 1e-9) : gex

// Extreme GEX flag (z-score beyond threshold)
var isExtremeGex = useZScore && math.abs(gexZ) > zThresh

// ------------------------------------------------------------------------------
// Regime Detection with Hysteresis (SpotGamma 2023-2024 framework)
// ------------------------------------------------------------------------------
// Smoothed GEX for regime classification
var gexSmooth = sma(gex, regimeSmooth)

// Hysteresis prevents noise flips: must cross beyond ±hysteresis to flip
var regime = 0   // 0 = unknown, 1 = long gamma (positive), -1 = short gamma (negative)
var lastRegime = gexSmooth[1] > hysteresis ? 1 : (gexSmooth[1] < -hysteresis ? -1 : 0)

if (gexSmooth > hysteresis) {
    regime = 1
} else if (gexSmooth < -hysteresis) {
    regime = -1
} else {
    // In hysteresis band — inherit last regime (sticky)
    regime = lastRegime
}

// ------------------------------------------------------------------------------
// Flip Detection (Zero-Crossing with Confirmation)
// ------------------------------------------------------------------------------
var gexPrev = !isnan(gexSmooth[1]) ? gexSmooth[1] : 0.0
var isFlipUp = gexSmooth > hysteresis && gexPrev <= hysteresis
var isFlipDown = gexSmooth < -hysteresis && gexPrev >= -hysteresis
var anyFlip = isFlipUp || isFlipDown

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks flip price, regime history, duration counts, and extreme events.

static lastFlipPx = 0.0
static lastFlipRegime = 0
static flipCount = 0
static longGammaBars = 0
static shortGammaBars = 0
static extremeGexCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (anyFlip) {
        lastFlipPx = px
        lastFlipRegime = isFlipUp ? 1 : -1
        flipCount = flipCount + 1
    }

    if (regime == 1) {
        longGammaBars = longGammaBars + 1
    } else if (regime == -1) {
        shortGammaBars = shortGammaBars + 1
    }

    if (isExtremeGex) {
        extremeGexCount = extremeGexCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — GEX Histogram, Flip Line, Regime Indicator, Shapes, Z-Bands
// ------------------------------------------------------------------------------

// --- Flip price line (horizontal at last flip price) ---
if (showFlipLn && lastFlipPx > 0 && !isnan(lastFlipPx)) {
    hline(value=lastFlipPx, color=flipColor, width=2)
}

// --- GEX Histogram (color-coded by regime and extreme) ---
if (showHistogram) {
    var histColor = isExtremeGex ? extremeColor : (regime == 1 ? posColor : negColor)
    plotBar(
        value=gexSmooth,
        colors=[posColor, negColor, extremeColor],
        colorIndex=isExtremeGex ? 2 : (regime == 1 ? 0 : 1),
        width=1,
        label=["GEX"],
        desc=["Gamma Exposure proxy (smoothed). Positive = long gamma (chop), Negative = short gamma (trend)"]
    )
}

// --- Regime indicator line (regime-colored) ---
if (showRegime) {
    var regimeVal = regime == 1 ? 50.0 : (regime == -1 ? -50.0 : 0.0)
    var regimeLineColor = regime == 1 ? posColor : (regime == -1 ? negColor : neutralColor)

    plotLine(
        value=regimeVal,
        colors=[regimeLineColor],
        width=2,
        label=["Regime"],
        desc=["Current gamma regime: +50 = long gamma / chop, −50 = short gamma / trend"]
    )

    hline(value=50, color=transparency(posColor, 70), width=1)
    hline(value=-50, color=transparency(negColor, 70), width=1)
    hline(value=0, color="#ffffff40", width=1)
}

// --- Z-Score bands (guide lines for extreme readings) ---
if (showZBand && useZScore) {
    hline(value=zThresh, color=transparency(extremeColor, 50), width=1)
    hline(value=-zThresh, color=transparency(extremeColor, 50), width=1)
}

// --- Flip shape markers ---
if (showShapes) {
    if (isFlipUp) {
        plotShape(
            value=px,
            shape="triangleup",
            color=posColor,
            width=3,
            label=["Flip Long"],
            desc=["GEX flipped positive — dealers entered long gamma regime (chop expected)"]
        )
    }
    if (isFlipDown) {
        plotShape(
            value=px,
            shape="triangledown",
            color=negColor,
            width=3,
            label=["Flip Short"],
            desc=["GEX flipped negative — dealers entered short gamma regime (trend expected)"]
        )
    }
    if (isExtremeGex && !anyFlip) {
        plotShape(
            value=px,
            shape="diamond",
            color=extremeColor,
            width=2,
            label=["Extreme GEX"],
            desc=["Extreme GEX reading (z-score > " + zThresh + ") — significant hedging pressure"]
        )
    }
}