MM Flow
FlowScripts

Perfected FlowScript

Gamma Exposure Poly Alpha

Gamma Exposure Poly Alpha — Perfected Edition is indexed as 301_gamma_exposure_poly_alpha.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

16.1 KB

Lines

500

Native Signal Candidates

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

6/6 guarded

GEX Cross Up

line 405:9

Trigger

(showShapes) && (crossUp)

Value

gexSmooth

Deps

crossUp:var, showShapes:input

GEX Cross Down

line 415:9

Trigger

(showShapes) && (crossDown)

Value

gexSmooth

Deps

crossDown:var, showShapes:input

Stabilize Flip

line 425:9

Trigger

(showShapes) && (flipPosCross)

Value

dynFlipPos

Deps

flipPosCross:var, showShapes:input

Destabilize Flip

line 435:9

Trigger

(showShapes) && (flipNegCross)

Value

dynFlipNeg

Deps

flipNegCross:var, showShapes:input

Z-Score High

line 445:9

Trigger

(showShapes) && (zExtremeHigh)

Value

gexSmooth

Deps

showShapes:input, zExtremeHigh:var

Z-Score Low

line 455:9

Trigger

(showShapes) && (zExtremeLow)

Value

gexSmooth

Deps

showShapes:input, zExtremeLow:var

301_gamma_exposure_poly_alpha.flowscript

source path: kscripts/perfected/301_gamma_exposure_poly_alpha.flowscript · sha256:c2d2f13a6aa7cfb47c25b16676bdbb1cebbc6ce7bb0c8b6a026a13062ea2ac35

hash verified
//@version=2
// ============================================================================
// Gamma Exposure Poly Alpha — Perfected Edition
// Author: L (@Lucak47cash) | Enhanced by kScript Perfection Engineer
// Tags: FLOW, #gex, #gamma, #options, #dealer, #regime, #volatility
//
// Production-quality dealer gamma exposure (GEX) proxy with z-score
// normalization, volatility regime detection, dynamic gamma-flip thresholds,
// color-coded histogram, fill visualization, and shape-marker alerts.
//
// Research papers underpinning this design:
//  1. Black & Scholes (1973), "The Pricing of Options and Corporate
//     Liabilities": seminal option pricing; delta-hedging replicating portfolio.
//     Underpins all Greek calculations and gamma exposure measurement.
//  2. Merton (1973), "Theory of Rational Option Pricing": extended B-S to
//     American options, jump-diffusion, and continuous-time self-financing.
//     Formalized contingent-claims analysis for dynamic hedging.
//  3. Regan et al. (2025), "Evaluating LLM Detection of Gamma Exposure
//     Patterns via Obfuscation Testing": comprehensive GEX methodology.
//     Three manifestations: (1) gamma positioning (net GEX < -$2B forces
//     pro-cyclical hedging), (2) stock pinning (OI >80% at strike creates
//     gravitational price effects), (3) 0DTE hedging (extreme gamma concentration).
//     71.5% single-day detection; 81.2% multi-day regime detection.
//  4. SpotGamma (2023-2024), "GEX Explained": industry-standard GEX calculation.
//     GEX = Gamma × Open Interest × 100 × Spot². Key metrics: Net GEX, Call Wall,
//     Put Wall, Gamma Flip, Volatility Trigger.
//  5. SqueezeMetrics (2017), "Impact of Option Dealer Flows on Equity Returns":
//     foundational practitioner GEX research. GEX regime classification:
//     Very Positive GEX = massively long gamma, stabilizing, very low vol;
//     Negative GEX = short gamma, destabilizing, high vol.
//  6. Trading Volatility (2024), "Skew-Adjusted Gamma Exposure (SA-GEX)":
//     distinguishes naive GEX from skew-adjusted GEX for more accurate
//     dealer positioning measurement.
// ============================================================================

define(
    title="Gamma Exposure Poly Alpha — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- GEX Calculation ---
var gexLen = input(
    name="gexLen",
    type="number",
    defaultValue=20,
    label="GEX Lookback Window",
    constraints={min: 5, max: 100, step: 1},
    group="GEX Calculation"
)
var contractSz = input(
    name="contractSz",
    type="number",
    defaultValue=100,
    label="Contract Size (shares)",
    constraints={min: 1, max: 1000, step: 1},
    group="GEX Calculation"
)
var spotPx = input(
    name="spotPx",
    type="number",
    defaultValue=0.0,
    label="Spot Reference (0 = auto from close)",
    constraints={min: 0.0, max: 1000000.0, step: 0.01},
    group="GEX Calculation"
)

// --- Smoothing ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Smoothing"
)
var signalLen = input(
    name="signalLen",
    type="number",
    defaultValue=14,
    label="Signal SMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="Smoothing"
)

// --- Z-Score ---
var zScoreLen = input(
    name="zScoreLen",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Z-Score"
)
var zScoreThresh = input(
    name="zScoreThresh",
    type="number",
    defaultValue=2.0,
    label="Z-Score Extreme Threshold",
    constraints={min: 0.5, max: 4.0, step: 0.1},
    group="Z-Score"
)

// --- Dynamic Thresholds ---
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=true,
    label="Dynamic Thresholds (volatility-adjusted)",
    group="Dynamic Thresholds"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volatility Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Dynamic Thresholds"
)
var volMultiplier = input(
    name="volMultiplier",
    type="number",
    defaultValue=1.5,
    label="Volatility Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Dynamic Thresholds"
)

// --- Display ---
var showGexLine = input(
    name="showGexLine",
    type="boolean",
    defaultValue=true,
    label="Show GEX Line",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show GEX Histogram",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showSignalFill = input(
    name="showSignalFill",
    type="boolean",
    defaultValue=true,
    label="Show Signal Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)

// --- Colors ---
var posColor = input(
    name="posColor",
    type="color",
    defaultValue="#26a69a",
    label="Positive GEX (Stabilizing) Color",
    group="Colors"
)
var negColor = input(
    name="negColor",
    type="color",
    defaultValue="#ef5350",
    label="Negative GEX (Destabilizing) Color",
    group="Colors"
)
var flipColor = input(
    name="flipColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Gamma Flip Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = spotPx > 0 ? spotPx : bars.close
timeseries vol = bars.volume

if (isnan(px[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. GEX PROXY CALCULATION
// -----------------------------------------------------------------------------
// In a real options environment, gamma and open interest would come from the
// options chain. We approximate dealer hedging flow using a momentum-volatility-
// interaction model per the SqueezeMetrics (2017) GEX paradigm.
// GEX proxy = sign(return) × volatility × volume × spot² (z-normalized)
// Per SpotGamma: GEX = Gamma × OI × 100 × Spot²

timeseries ret = px[1] > 0 ? (px - px[1]) / px[1] : 0.0
timeseries sumRet = sma(ret, gexLen)
timeseries sumAbs = sma(math.abs(ret), gexLen)
timeseries intensity = sumAbs > 0 ? sumRet / sumAbs : 0

// Net GEX proxy: positive = dealer long gamma (stabilizing, buy dips, sell rallies)
// negative = dealer short gamma (destabilizing, sell dips, buy rallies)
timeseries netGex = intensity * math.sqrt(vol + 1.0) * (px * px / 1000000.0)

// Normalize by rolling mean absolute value for stationarity
timeseries gexMean = sma(math.abs(netGex), gexLen)
timeseries normGex = gexMean > 0 ? (netGex / gexMean) * 100.0 : 0.0

// Smooth
timeseries gexSmooth = ema(normGex, smoothLen)

// -----------------------------------------------------------------------------
// 4. SIGNAL & Z-SCORE
// -----------------------------------------------------------------------------
// Signal SMA for crossover detection and trend filtering
timeseries signal = sma(gexSmooth, signalLen)

// Z-score normalization per Zhao & Palomar (2018)
timeseries gexMeanZ = sma(gexSmooth, zScoreLen)
timeseries gexStdZ = stddev(gexSmooth, zScoreLen)
timeseries gexZScore = gexStdZ > 0 ? (gexSmooth - gexMeanZ) / gexStdZ : 0.0

// -----------------------------------------------------------------------------
// 5. DYNAMIC THRESHOLDS (Gamma Flip Levels)
// -----------------------------------------------------------------------------
// Dynamic thresholds adjust to rolling GEX volatility per Poterba & Summers (1988)
// mean-reversion intensity calibration. The "gamma flip" is the level where net
// GEX changes sign, shifting market dynamics from stabilizing to destabilizing.

timeseries gexVol = stddev(gexSmooth, volLookback)
var dynFlipPos = useDynamic ? gexVol * volMultiplier : 50.0
var dynFlipNeg = useDynamic ? -gexVol * volMultiplier : -50.0

// Guard: ensure thresholds never invert
if (dynFlipPos <= 0) {
    dynFlipPos = 50.0
}
if (dynFlipNeg >= 0) {
    dynFlipNeg = -50.0
}

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification per GEX Radar / Sharpnel Trading (2024-2025):
//   Stabilizing (long gamma):  GEX > +threshold → dealers buy dips, sell rallies
//   Destabilizing (short gamma): GEX < -threshold → dealers sell dips, buy rallies
//   Neutral: between thresholds

var regimeStabilize = gexSmooth >= dynFlipPos
var regimeDestabilize = gexSmooth <= dynFlipNeg
var regimeNeutral = !regimeStabilize && !regimeDestabilize

var regimeColor = regimeStabilize ? posColor : (regimeDestabilize ? negColor : "#9e9e9e")

// -----------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Tracks session GEX extremes, gamma flip crossings, and regime transitions.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighGex = -999999.0
static sessionLowGex = 999999.0
static flipPosCount = 0
static flipNegCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (gexSmooth > sessionHighGex) {
        sessionHighGex = gexSmooth
    }
    if (gexSmooth < sessionLowGex) {
        sessionLowGex = gexSmooth
    }

    var currRegime = regimeStabilize ? 1 : (regimeDestabilize ? -1 : 0)
    if (lastRegime != currRegime) {
        lastRegime = currRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (gexSmooth >= dynFlipPos && gexSmooth[1] < dynFlipPos) {
        flipPosCount = flipPosCount + 1
    }
    if (gexSmooth <= dynFlipNeg && gexSmooth[1] > dynFlipNeg) {
        flipNegCount = flipNegCount + 1
    }
}

// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Gamma flip crossings, extreme z-score events, and signal crossovers.

var crossUp = gexSmooth > signal && gexSmooth[1] <= signal[1]
var crossDown = gexSmooth < signal && gexSmooth[1] >= signal[1]

var zExtremeHigh = gexZScore >= zScoreThresh && gexZScore[1] < zScoreThresh
var zExtremeLow = gexZScore <= -zScoreThresh && gexZScore[1] > -zScoreThresh[1]

var flipPosCross = gexSmooth >= dynFlipPos && gexSmooth[1] < dynFlipPos
var flipNegCross = gexSmooth <= dynFlipNeg && gexSmooth[1] > dynFlipNeg

var stabilizeEnter = regimeStabilize && !regimeStabilize[1]
var destabilizeEnter = regimeDestabilize && !regimeDestabilize[1]

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero line ---
hline(value=0, color="#ffffff20", width=1)

// --- Dynamic gamma flip thresholds ---
hline(value=dynFlipPos, color=transparency(flipColor, 50), width=1)
hline(value=dynFlipNeg, color=transparency(flipColor, 50), width=1)

// --- GEX Line (regime-colored) ---
if (showGexLine) {
    plotLine(
        value=gexSmooth,
        width=2,
        colors=[regimeColor],
        label=["Net GEX"],
        desc=["Gamma Exposure proxy: positive = stabilizing (long gamma), negative = destabilizing (short gamma)"]
    )
}

// --- Signal SMA ---
if (showGexLine) {
    plotLine(
        value=signal,
        width=1,
        colors=["#ffffff"],
        label=["Signal SMA"],
        desc=["SMA of smoothed GEX proxy (" + signalLen + ") for crossover detection"]
    )
}

// --- Signal Fill (GEX vs signal) ---
if (showSignalFill && showGexLine) {
    var gexBull = gexSmooth > signal
    plotLine(
        value=[gexSmooth, signal],
        width=1,
        colors=[transparency(posColor, 20), transparency(negColor, 20)],
        colorIndex=gexBull ? 0 : 1,
        fill=true,
        label=["GEX", "Signal"],
        desc=["Fill between GEX proxy and signal SMA"]
    )
}

// --- GEX Histogram (color-coded) ---
if (showHistogram) {
    var histBull = gexSmooth >= 0
    plotBar(
        value=gexSmooth,
        colors=[transparency(posColor, 60), transparency(negColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["GEX Histogram"],
        desc=["Gamma Exposure histogram: positive = stabilizing, negative = destabilizing"]
    )
}

// --- Z-Score Line ---
if (showZScore) {
    plotLine(
        value=gexZScore,
        width=1,
        colors=["#7c4dff"],
        label=["GEX Z-Score"],
        desc=["Z-score of GEX proxy over " + zScoreLen + " bars"]
    )
    hline(value=zScoreThresh, color="#7c4dff30", width=1)
    hline(value=-zScoreThresh, color="#7c4dff30", width=1)
}

// --- Shape Markers ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=gexSmooth,
            shape="triangleup",
            color=posColor,
            width=2,
            label=["GEX Cross Up"],
            desc=["GEX proxy crossed above signal SMA"]
        )
    }
    if (crossDown) {
        plotShape(
            value=gexSmooth,
            shape="triangledown",
            color=negColor,
            width=2,
            label=["GEX Cross Down"],
            desc=["GEX proxy crossed below signal SMA"]
        )
    }
    if (flipPosCross) {
        plotShape(
            value=dynFlipPos,
            shape="diamond",
            color=posColor,
            width=3,
            label=["Stabilize Flip"],
            desc=["GEX crossed into stabilizing regime (long gamma threshold)"]
        )
    }
    if (flipNegCross) {
        plotShape(
            value=dynFlipNeg,
            shape="diamond",
            color=negColor,
            width=3,
            label=["Destabilize Flip"],
            desc=["GEX crossed into destabilizing regime (short gamma threshold)"]
        )
    }
    if (zExtremeHigh) {
        plotShape(
            value=gexSmooth,
            shape="xcross",
            color=posColor,
            width=2,
            label=["Z-Score High"],
            desc=["GEX z-score crossed above +" + zScoreThresh]
        )
    }
    if (zExtremeLow) {
        plotShape(
            value=gexSmooth,
            shape="xcross",
            color=negColor,
            width=2,
            label=["Z-Score Low"],
            desc=["GEX z-score crossed below -" + zScoreThresh]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeStabilize ? "STABILIZING" : (regimeDestabilize ? "DESTABILIZING" : "NEUTRAL")
    var regimeTextColor = regimeStabilize ? posColor : (regimeDestabilize ? negColor : "#9e9e9e")

    plotTable(
        data=[
            ["Gamma Exposure — Perfected", regimeText],
            ["Net GEX", gexSmooth[0]],
            ["Signal SMA", signal[0]],
            ["Z-Score", gexZScore[0]],
            ["Dyn Flip +", dynFlipPos],
            ["Dyn Flip -", dynFlipNeg],
            ["Session High GEX", sessionHighGex],
            ["Session Low GEX", sessionLowGex],
            ["Regime Changes", regimeChangeCount],
            ["Stabilize Flips", flipPosCount],
            ["Destabilize Flips", flipNegCount]
        ],
        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
    )
}