MM Flow
FlowScripts

Perfected FlowScript

Gamma Walls

Gamma Walls — Perfected Edition is indexed as 287_gamma_walls.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

518

Native Signal Candidates

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

8/8 guarded

Near Call Wall

line 395:9

Trigger

(showShapes) && (nearCall)

Value

callWall

Deps

nearCall:timeseries, showShapes:input

Near Put Wall

line 406:9

Trigger

(showShapes) && (nearPut)

Value

putWall

Deps

nearPut:timeseries, showShapes:input

At Call Wall

line 417:9

Trigger

(showShapes) && (atCall)

Value

high

Deps

atCall:timeseries, showShapes:input

At Put Wall

line 428:9

Trigger

(showShapes) && (atPut)

Value

low

Deps

atPut:timeseries, showShapes:input

Long Gamma Flip

line 439:9

Trigger

(showShapes) && (close > flipSmoothLine && close[1] <= flipSmoothLine[1])

Value

flipSmoothLine

Deps

close:timeseries, flipSmoothLine:timeseries, showShapes:input

Short Gamma Flip

line 448:9

Trigger

(showShapes) && (close < flipSmoothLine && close[1] >= flipSmoothLine[1])

Value

flipSmoothLine

Deps

close:timeseries, flipSmoothLine:timeseries, showShapes:input

Z Extreme High

line 459:9

Trigger

(showShapes) && (zExtremeHigh)

Value

high

Deps

showShapes:input, zExtremeHigh:var

Z Extreme Low

line 469:9

Trigger

(showShapes) && (zExtremeLow)

Value

low

Deps

showShapes:input, zExtremeLow:var

287_gamma_walls.flowscript

source path: kscripts/perfected/287_gamma_walls.flowscript · sha256:42fd03982ec95ab3c25781c7f1d7960dac99228f79d99df9e5832583062cdbc5

hash verified
//@version=2
// ============================================================================
// Gamma Walls — Perfected Edition
// Author: Crypto Catipal (@Crypto Catipal) | Enhanced by kScript Perfection Engineer
// Index: 287
// Tags: CORE, ADVANCED, #gamma, #walls, #gex, #options, #regime
//
// Production-quality gamma exposure visualization with z-score normalization,
// regime detection, color-coded walls, shape markers, and static session tracking.
// Models call wall (resistance), put wall (support), gamma flip (regime
// transition), and dealer positioning zones based on options market maker
// hedging dynamics.
//
// Research papers underpinning this design:
//  1. Black & Scholes (1973), "The Pricing of Options and Corporate Liabilities":
//     seminal option pricing model; gamma = ∂²V/∂S² drives dealer hedging. [^1]
//  2. Regan et al. (2025), "Evaluating LLM Detection of Gamma Exposure Patterns":
//     comprehensive academic treatment of GEX calculation, gamma flip dynamics,
//     and dealer hedging constraints (net GEX < −$2B forces pro-cyclical hedging). [^2]
//  3. SpotGamma Research (2023–2024), "GEX Explained": industry-standard GEX
//     terminology — Call Wall, Put Wall, Gamma Flip, Volatility Trigger. [^3]
//  4. SqueezeMetrics / Wiz of Ops (2017–2024), "Impact of Option Dealer Flows":
//     foundational practitioner GEX framework; customer long calls / short puts
//     implies dealer short calls / long puts → delta hedging drives spot. [^4]
//  5. Carr & Wu (2009), "Variance Risk Premia": VRP framework underpins
//     volatility regime dynamics that interact with gamma exposure. [^5]
//  6. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score normalization for statistical band construction and threshold
//     signal generation. [^6]
// ============================================================================

define(
    title="Gamma Walls — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- Wall Configuration ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=50,
    label="Range Lookback (bars)",
    constraints={min: 10, max: 500, step: 1},
    group="Wall Configuration"
)
var wallOffset = input(
    name="wallOffset",
    type="number",
    defaultValue=5.0,
    label="Wall Offset % from price range",
    constraints={min: 0.5, max: 50.0, step: 0.5},
    group="Wall Configuration"
)
var useATR = input(
    name="useATR",
    type="boolean",
    defaultValue=true,
    label="Use ATR for dynamic wall width",
    group="Wall Configuration"
)
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 50, step: 1},
    group="Wall Configuration"
)
var atrMult = input(
    name="atrMult",
    type="number",
    defaultValue=2.0,
    label="ATR Multiplier (wall width)",
    constraints={min: 0.5, max: 10.0, step: 0.5},
    group="Wall Configuration"
)

// --- Z-Score Normalization ---
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=50,
    label="Z-Score Lookback",
    constraints={min: 10, max: 500, step: 1},
    group="Z-Score"
)
var zThreshold = input(
    name="zThreshold",
    type="number",
    defaultValue=2.0,
    label="Z-Score Extreme Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Z-Score"
)

// --- Regime Detection ---
var useRegime = input(
    name="useRegime",
    type="boolean",
    defaultValue=true,
    label="Enable Gamma Regime Detection",
    group="Regime"
)
var flipSmooth = input(
    name="flipSmooth",
    type="number",
    defaultValue=5,
    label="Gamma Flip Smoothing",
    constraints={min: 1, max: 50, step: 1},
    group="Regime"
)

// --- Display ---
var showWalls = input(
    name="showWalls",
    type="boolean",
    defaultValue=true,
    label="Show Call/Put Walls",
    group="Display"
)
var showFlip = input(
    name="showFlip",
    type="boolean",
    defaultValue=true,
    label="Show Gamma Flip Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Wall Zone Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Proximity Shapes",
    group="Display"
)
var showZscore = input(
    name="showZscore",
    type="boolean",
    defaultValue=false,
    label="Show Z-Score Line",
    group="Display"
)

// --- Colors ---
var callColor = input(
    name="callColor",
    type="color",
    defaultValue="#ff5252",
    label="Call Wall (resistance)",
    group="Colors"
)
var putColor = input(
    name="putColor",
    type="color",
    defaultValue="#00e676",
    label="Put Wall (support)",
    group="Colors"
)
var flipColor = input(
    name="flipColor",
    type="color",
    defaultValue="#ff9800",
    label="Gamma Flip",
    group="Colors"
)
var longGammaColor = input(
    name="longGammaColor",
    type="color",
    defaultValue="#26a69a",
    label="Long Gamma Regime",
    group="Colors"
)
var shortGammaColor = input(
    name="shortGammaColor",
    type="color",
    defaultValue="#ef5350",
    label="Short Gamma Regime",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low

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

// -----------------------------------------------------------------------------
// 3. WALL COMPUTATION
// -----------------------------------------------------------------------------
// Call Wall = resistance from highest call gamma strike (approximated by range high + offset)
// Put Wall = support from highest put gamma strike (approximated by range low - offset)
// Gamma Flip = midpoint where net GEX changes sign (regime transition line)
// Per SpotGamma: GEX = Gamma × Open Interest × 100 × Spot²
// Since we do not have options data in this context, we approximate walls from
// price range and ATR, which proxies for volatility-driven gamma expansion.

timeseries rangeHi = highest(high, lookback)
timeseries rangeLo = lowest(low, lookback)
timeseries atr = atr(period=atrLen)

// Dynamic wall width: either ATR-based or fixed percentage
timeseries wallWidth = useATR ? atr * atrMult : close * wallOffset / 100

// Call Wall (ceiling) — resistance level
timeseries callWall = rangeHi + wallWidth
// Put Wall (floor) — support level
timeseries putWall = rangeLo - wallWidth
// Gamma Flip — midpoint / regime transition
timeseries gammaFlip = (callWall + putWall) / 2

// Smoothed gamma flip for cleaner regime signal
timeseries flipSmoothLine = ema(source=gammaFlip, period=flipSmooth)

// -----------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Per Zhao & Palomar (2018), z-score measures distance from mean in standard
// deviation units. We z-score the price's position relative to the wall zone.
// z = (close − flip) / (callWall − flip) — normalized position within the wall envelope.

timeseries wallRange = callWall - putWall
var zScore = 0.0
if (useZscore && wallRange > 0) {
    var rawZ = (close - flipSmoothLine) / (wallRange / 2) * 100
    var zMean = sma(source=rawZ, period=zLookback)
    var zStd = stddev(source=rawZ, period=zLookback)
    zScore = zStd > 0 ? (rawZ - zMean) / zStd : 0
}

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Dealer gamma regime classification:
//   Long Gamma: price > gamma flip → dealers hedge against trend (stabilizing)
//   Short Gamma: price < gamma flip → dealers hedge with trend (amplifying)
// Per GEX Radar / Sharpnel Trading (2024–2025):
//   Positive GEX = dealers buy dips, sell rallies (stabilizing, low vol)
//   Negative GEX = dealers sell dips, buy rallies (amplifying, high vol)

var aboveFlip = close > flipSmoothLine
var belowFlip = close < flipSmoothLine
var longGamma = aboveFlip
var shortGamma = belowFlip
var atFlip = abs(close - flipSmoothLine) / close < 0.005

// Regime color
timeseries regimeColor = longGamma ? longGammaColor : (shortGamma ? shortGammaColor : flipColor)

// Proximity to walls (percentage distance)
timeseries distToCall = (callWall - close) / close * 100
timeseries distToPut = (close - putWall) / close * 100

// Near wall flags
timeseries nearCall = close > callWall * 0.99 && close < callWall * 1.01
timeseries nearPut = close > putWall * 0.99 && close < putWall * 1.01
timeseries atCall = close >= callWall
timeseries atPut = close <= putWall

// Z-score extreme flags
var zExtremeHigh = useZscore && zScore > zThreshold
var zExtremeLow = useZscore && zScore < -zThreshold

// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static lastRegime = 0       // 0 = neutral, 1 = long gamma, -1 = short gamma
static regimeChangeCount = 0
static sessionHighPrice = -1.0
static sessionLowPrice = 999999999.0
static callWallTouches = 0
static putWallTouches = 0
static flipCrossCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (close[0] > sessionHighPrice) {
        sessionHighPrice = close[0]
    }
    if (close[0] < sessionLowPrice) {
        sessionLowPrice = close[0]
    }

    // Regime change detection
    var currentRegime = longGamma ? 1 : (shortGamma ? -1 : 0)
    if (currentRegime != lastRegime && currentRegime != 0) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    // Wall touch counts
    if (atCall) {
        callWallTouches = callWallTouches + 1
    }
    if (atPut) {
        putWallTouches = putWallTouches + 1
    }

    // Flip cross detection
    if (close[0] > flipSmoothLine[0] && close[1] <= flipSmoothLine[1]) {
        flipCrossCount = flipCrossCount + 1
    } else if (close[0] < flipSmoothLine[0] && close[1] >= flipSmoothLine[1]) {
        flipCrossCount = flipCrossCount + 1
    }
}

// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------

// --- Wall Zone Fill ---
if (showFill) {
    plotLine(
        value=[callWall, putWall],
        width=1,
        colors=[transparency(callColor, 10), transparency(putColor, 10)],
        colorIndex=0,
        fill=true,
        label=["Call Wall", "Put Wall"],
        desc=["Gamma wall envelope — call wall (ceiling) to put wall (floor)"]
    )
}

// --- Call Wall ---
if (showWalls) {
    plotLine(
        value=callWall,
        width=2,
        colors=[callColor],
        label=["Call Wall"],
        desc=["Resistance from call gamma exposure (range high + wall width)"]
    )
    plotLine(
        value=putWall,
        width=2,
        colors=[putColor],
        label=["Put Wall"],
        desc=["Support from put gamma exposure (range low − wall width)"]
    )
}

// --- Gamma Flip (regime-colored) ---
if (showFlip) {
    plotLine(
        value=flipSmoothLine,
        width=2,
        colors=[regimeColor],
        label=["Gamma Flip"],
        desc=["Regime transition line: price above = long gamma (stabilizing), below = short gamma (amplifying)"]
    )
}

// --- Z-Score Line (offchart if enabled) ---
if (showZscore) {
    plotLine(
        value=zScore,
        width=1,
        colors=[flipColor],
        label=["Z-Score"],
        desc=["Z-score of price position within gamma wall envelope"]
    )
}

// --- Proximity & Regime Shapes ---
if (showShapes) {
    // Near call wall (resistance proximity)
    if (nearCall) {
        plotShape(
            value=callWall,
            shape="circle",
            colorIndex=callColor,
            width=2,
            label=["Near Call Wall"],
            desc=["Price approaching call wall resistance — dealer hedging may cap upside"]
        )
    }
    // Near put wall (support proximity)
    if (nearPut) {
        plotShape(
            value=putWall,
            shape="circle",
            colorIndex=putColor,
            width=2,
            label=["Near Put Wall"],
            desc=["Price approaching put wall support — dealer hedging may floor downside"]
        )
    }
    // At call wall (breakthrough / rejection)
    if (atCall) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=callColor,
            width=3,
            label=["At Call Wall"],
            desc=["Price at or above call wall — potential gamma squeeze or resistance rejection"]
        )
    }
    // At put wall (breakthrough / rejection)
    if (atPut) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=putColor,
            width=3,
            label=["At Put Wall"],
            desc=["Price at or below put wall — potential gamma flush or support bounce"]
        )
    }
    // Gamma flip crossing
    if (close > flipSmoothLine && close[1] <= flipSmoothLine[1]) {
        plotShape(
            value=flipSmoothLine,
            shape="diamond",
            colorIndex=longGammaColor,
            width=3,
            label=["Long Gamma Flip"],
            desc=["Price crossed above gamma flip — entering long gamma regime (stabilizing)"]
        )
    } else if (close < flipSmoothLine && close[1] >= flipSmoothLine[1]) {
        plotShape(
            value=flipSmoothLine,
            shape="diamond",
            colorIndex=shortGammaColor,
            width=3,
            label=["Short Gamma Flip"],
            desc=["Price crossed below gamma flip — entering short gamma regime (amplifying)"]
        )
    }
    // Z-score extremes
    if (zExtremeHigh) {
        plotShape(
            value=high,
            shape="xcross",
            colorIndex=callColor,
            width=2,
            label=["Z Extreme High"],
            desc=["Z-score above +" + zThreshold + " — price stretched to upper wall extreme"]
        )
    }
    if (zExtremeLow) {
        plotShape(
            value=low,
            shape="xcross",
            colorIndex=putColor,
            width=2,
            label=["Z Extreme Low"],
            desc=["Z-score below −" + zThreshold + " — price stretched to lower wall extreme"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = longGamma ? "LONG GAMMA (Stabilizing)" : (shortGamma ? "SHORT GAMMA (Amplifying)" : "AT FLIP")
    var regimeTextColor = longGamma ? longGammaColor : (shortGamma ? shortGammaColor : flipColor)
    var wallType = useATR ? "ATR-based" : "Fixed %"

    plotTable(
        data=[
            ["Gamma Walls — Perfected", regimeText],
            ["Price", close[0]],
            ["Call Wall", callWall[0]],
            ["Put Wall", putWall[0]],
            ["Gamma Flip", flipSmoothLine[0]],
            ["Wall Type", wallType],
            ["Z-Score", zScore[0]],
            ["Dist to Call %", distToCall[0]],
            ["Dist to Put %", distToPut[0]],
            ["Session High", sessionHighPrice],
            ["Session Low", sessionLowPrice],
            ["Regime Changes", regimeChangeCount],
            ["Flip Crosses", flipCrossCount],
            ["Call Touches", callWallTouches],
            ["Put Touches", putWallTouches]
        ],
        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
    )
}