MM Flow
FlowScripts

Perfected FlowScript

Fair Value Gaps (FVGs) • [Leviathan]

Fair Value Gaps (FVGs) — Leviathan Perfected Edition is indexed as 091_fair_value_gaps_leviathan.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

26.1 KB

Lines

684

Native Signal Candidates

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

12/12 guarded

Bull FVG Formed

line 344:9

Trigger

(bull1Active == 1) && (showShapeMarkers && bull1Bar == barCount)

Value

bull1Top

Deps

barCount:static, bull1Active:static, bull1Bar:static, showShapeMarkers:input

Bull FVG Mitigated

line 356:13

Trigger

(bull1Active == 1) && (showMitigationMarkers && bull1Mitigated == 1 && bull1Bar != barCount) && (low <= bull1Top && high >= bull1Bot)

Value

bull1Bot

Deps

barCount:static, bull1Active:static, bull1Bar:static, bull1Bot:static, bull1Mitigated:static, bull1Top:static, high:timeseries, low:timeseries, showMitigationMarkers:input

Bull FVG Formed

line 395:9

Trigger

(bull2Active == 1) && (showShapeMarkers && bull2Bar == barCount)

Value

bull2Top

Deps

barCount:static, bull2Active:static, bull2Bar:static, showShapeMarkers:input

Bull FVG Mitigated

line 407:13

Trigger

(bull2Active == 1) && (showMitigationMarkers && bull2Mitigated == 1 && bull2Bar != barCount) && (low <= bull2Top && high >= bull2Bot)

Value

bull2Bot

Deps

barCount:static, bull2Active:static, bull2Bar:static, bull2Bot:static, bull2Mitigated:static, bull2Top:static, high:timeseries, low:timeseries, showMitigationMarkers:input

Bull FVG Formed

line 446:9

Trigger

(bull3Active == 1) && (showShapeMarkers && bull3Bar == barCount)

Value

bull3Top

Deps

barCount:static, bull3Active:static, bull3Bar:static, showShapeMarkers:input

Bull FVG Mitigated

line 458:13

Trigger

(bull3Active == 1) && (showMitigationMarkers && bull3Mitigated == 1 && bull3Bar != barCount) && (low <= bull3Top && high >= bull3Bot)

Value

bull3Bot

Deps

barCount:static, bull3Active:static, bull3Bar:static, bull3Bot:static, bull3Mitigated:static, bull3Top:static, high:timeseries, low:timeseries, showMitigationMarkers:input

Bear FVG Formed

line 500:9

Trigger

(bear1Active == 1) && (showShapeMarkers && bear1Bar == barCount)

Value

bear1Top

Deps

barCount:static, bear1Active:static, bear1Bar:static, showShapeMarkers:input

Bear FVG Mitigated

line 512:13

Trigger

(bear1Active == 1) && (showMitigationMarkers && bear1Mitigated == 1 && bear1Bar != barCount) && (high >= bear1Bot && low <= bear1Top)

Value

bear1Top

Deps

barCount:static, bear1Active:static, bear1Bar:static, bear1Bot:static, bear1Mitigated:static, bear1Top:static, high:timeseries, low:timeseries, showMitigationMarkers:input

Bear FVG Formed

line 551:9

Trigger

(bear2Active == 1) && (showShapeMarkers && bear2Bar == barCount)

Value

bear2Top

Deps

barCount:static, bear2Active:static, bear2Bar:static, showShapeMarkers:input

Bear FVG Mitigated

line 563:13

Trigger

(bear2Active == 1) && (showMitigationMarkers && bear2Mitigated == 1 && bear2Bar != barCount) && (high >= bear2Bot && low <= bear2Top)

Value

bear2Top

Deps

barCount:static, bear2Active:static, bear2Bar:static, bear2Bot:static, bear2Mitigated:static, bear2Top:static, high:timeseries, low:timeseries, showMitigationMarkers:input

Bear FVG Formed

line 602:9

Trigger

(bear3Active == 1) && (showShapeMarkers && bear3Bar == barCount)

Value

bear3Top

Deps

barCount:static, bear3Active:static, bear3Bar:static, showShapeMarkers:input

Bear FVG Mitigated

line 614:13

Trigger

(bear3Active == 1) && (showMitigationMarkers && bear3Mitigated == 1 && bear3Bar != barCount) && (high >= bear3Bot && low <= bear3Top)

Value

bear3Top

Deps

barCount:static, bear3Active:static, bear3Bar:static, bear3Bot:static, bear3Mitigated:static, bear3Top:static, high:timeseries, low:timeseries, showMitigationMarkers:input

091_fair_value_gaps_leviathan.flowscript

source path: kscripts/perfected/091_fair_value_gaps_leviathan.flowscript · sha256:ddacea0909364cd96627305d1d416560935a7d9fce3619ef99ec8ab210ac9664

hash verified
//@version=2
// ============================================================================
// Fair Value Gaps (FVGs) — Leviathan Perfected Edition
// Author: Leviathan (@Leviathan) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #fvg, #fairvaluegaps, #smc, #imbalance, #marketmicrostructure
//
// Production-grade Fair Value Gap detector with three-candle pattern recognition,
// zone tracking with forward extension, mitigation detection, fill visualization,
// and multi-regime color coding.
//
// Academic foundations:
//  1. Pecchiari (2020), "Orderflow Imbalance and High Frequency Trading" (LUISS
//     Thesis). Order flow imbalance drives short-term price moves; FVGs manifest as
//     order-flow imbalance signatures. Quantile regression: OFI_t = γ₀ + γ₁·|ΔBid_t| +
//     γ₂·|ΔAsk_t| + γ₃·Vol_t + u_t.
//  2. Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey" (J. Financial
//     Markets, 699+ citations). Latent demands D(p) → realized prices/volumes via
//     λ·ΣX_i, where λ = price impact coefficient (Kyle 1985). FVGs exist as
//     price-discovery inefficiencies.
//  3. Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape" (NBER 11439).
//     Regression method achieves ~12% R² predicting institutional ownership from
//     trade patterns. Validates FVGs as institutional footprint zones.
//  4. Jones & Lipson (2005), "Are Retail Orders Different?" 1,000 retail shares →
//     400+ institutional shares opposite within 5 minutes. Validates smart-money
//     exploitation of retail liquidity at FVG zones.
//  5. Bhusal (2025), "Timing the Trap: Stop Hunt Zones & Price Manipulation"
//     (SSRN 5276088). Documents engineered liquidity traps; validates stop-hunting
//     as observable microstructure phenomenon. FVGs often form after liquidity sweeps.
//  6. Smart Money Pros (2024), "What is a Fair Value Gap/Imbalance?" Core
//     practitioner reference: FVG = gap between Candle 1 high and Candle 3 low
//     (bullish) or Candle 1 low and Candle 3 high (bearish); markets "seek to fill".
// ============================================================================

define(
    title="Fair Value Gaps (FVGs) — Leviathan Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- FVG Detection ---
var minGapPct = input(name="minGapPct", type="number", defaultValue=0.1, label="Minimum gap size %", constraints={min: 0.0, max: 5.0, step: 0.05}, group="FVG Detection")
var fillPct = input(name="fillPct", type="number", defaultValue=50.0, label="% into zone that counts as filled", constraints={min: 0.0, max: 100.0, step: 5.0}, group="FVG Detection")

// --- Filters ---
var useVolFilter = input(name="useVolFilter", type="boolean", defaultValue=false, label="Filter by volume", group="Filters")
var volMaLen = input(name="volMaLen", type="number", defaultValue=20, label="Volume MA length", constraints={min: 5, max: 100, step: 1}, group="Filters")

// --- Display ---
var extendZones = input(name="extendZones", type="boolean", defaultValue=true, label="Extend zones to right", group="Display")
var showMidline = input(name="showMidline", type="boolean", defaultValue=true, label="Show zone midlines", group="Display")
var showMitigated = input(name="showMitigated", type="boolean", defaultValue=true, label="Show mitigated zones", group="Display")
var showFilled = input(name="showFilled", type="boolean", defaultValue=true, label="Show filled zones (gray)", group="Display")
var showShapeMarkers = input(name="showShapeMarkers", type="boolean", defaultValue=true, label="Show formation markers", group="Display")
var showFVGSize = input(name="showFVGSize", type="boolean", defaultValue=true, label="Show FVG size histogram", group="Display")
var showMitigationMarkers = input(name="showMitigationMarkers", type="boolean", defaultValue=true, label="Show mitigation markers", group="Display")

// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish FVG color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish FVG color", group="Colors")
var bullWeakColor = input(name="bullWeakColor", type="color", defaultValue="#4db6ac", label="Bullish mitigated color", group="Colors")
var bearWeakColor = input(name="bearWeakColor", type="color", defaultValue="#ef9a9a", label="Bearish mitigated color", group="Colors")
var filledColor = input(name="filledColor", type="color", defaultValue="#9e9e9e", label="Filled FVG color", group="Colors")
var bullShapeColor = input(name="bullShapeColor", type="color", defaultValue="#00e676", label="Bullish marker color", group="Colors")
var bearShapeColor = input(name="bearShapeColor", type="color", defaultValue="#ff1744", label="Bearish marker color", group="Colors")

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

// isnan guard — prevents NaN propagation on startup
if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(open[0]) || isnan(vol[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. BAR COUNTER
// ---------------------------------------------------------------------------
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// ---------------------------------------------------------------------------
// 4. THREE-CANDLE FVG DETECTION
// ---------------------------------------------------------------------------
// Bullish FVG: low[0] > high[2]  (gap up between candle 0 and candle 2)
// Bearish FVG: high[0] < low[2]  (gap down between candle 0 and candle 2)
// Need 2 historical bars for detection.

var hasHistory = !isnan(high[2]) && !isnan(low[2])

// Bullish FVG
var bullFVG = hasHistory && low > high[2]
var bullGapSize = hasHistory ? low - high[2] : 0
var bullGapPct = hasHistory && high[2] > 0 ? (bullGapSize / high[2]) * 100 : 0
var bullValid = bullFVG && bullGapPct > minGapPct

// Bearish FVG
var bearFVG = hasHistory && high < low[2]
var bearGapSize = hasHistory ? low[2] - high : 0
var bearGapPct = hasHistory && low[2] > 0 ? (bearGapSize / low[2]) * 100 : 0
var bearValid = bearFVG && bearGapPct > minGapPct

// Volume filter
var volMA = sma(source=vol, period=volMaLen)
var volOk = !useVolFilter || vol > volMA

// ---------------------------------------------------------------------------
// 5. STATIC STATE: ZONE TRACKING (3 bullish + 3 bearish slots)
// ---------------------------------------------------------------------------
// Since kScript does not support arrays, we emulate zone tracking with
// individual static variables per slot. Each slot tracks: top, bottom,
// formation bar, active flag, mitigated flag, and filled flag.

// --- Bullish Zone 1 ---
static bull1Top = 0.0
static bull1Bot = 0.0
static bull1Bar = 0
static bull1Active = 0
static bull1Mitigated = 0
static bull1Filled = 0

// --- Bullish Zone 2 ---
static bull2Top = 0.0
static bull2Bot = 0.0
static bull2Bar = 0
static bull2Active = 0
static bull2Mitigated = 0
static bull2Filled = 0

// --- Bullish Zone 3 ---
static bull3Top = 0.0
static bull3Bot = 0.0
static bull3Bar = 0
static bull3Active = 0
static bull3Mitigated = 0
static bull3Filled = 0

// --- Bearish Zone 1 ---
static bear1Top = 0.0
static bear1Bot = 0.0
static bear1Bar = 0
static bear1Active = 0
static bear1Mitigated = 0
static bear1Filled = 0

// --- Bearish Zone 2 ---
static bear2Top = 0.0
static bear2Bot = 0.0
static bear2Bar = 0
static bear2Active = 0
static bear2Mitigated = 0
static bear2Filled = 0

// --- Bearish Zone 3 ---
static bear3Top = 0.0
static bear3Bot = 0.0
static bear3Bar = 0
static bear3Active = 0
static bear3Mitigated = 0
static bear3Filled = 0

// ---------------------------------------------------------------------------
// 6. STATE UPDATE (only on bar close)
// ---------------------------------------------------------------------------
// All stateful transitions happen here to ensure consistency.

if (!isLiveUpdate && hasHistory) {
    // --- Spawn new bullish FVG in first inactive slot ---
    if (bullValid && volOk) {
        if (bull1Active == 0) {
            bull1Top = low
            bull1Bot = high[2]
            bull1Bar = barCount
            bull1Active = 1
            bull1Mitigated = 0
            bull1Filled = 0
        } else if (bull2Active == 0) {
            bull2Top = low
            bull2Bot = high[2]
            bull2Bar = barCount
            bull2Active = 1
            bull2Mitigated = 0
            bull2Filled = 0
        } else if (bull3Active == 0) {
            bull3Top = low
            bull3Bot = high[2]
            bull3Bar = barCount
            bull3Active = 1
            bull3Mitigated = 0
            bull3Filled = 0
        }
    }

    // --- Spawn new bearish FVG in first inactive slot ---
    if (bearValid && volOk) {
        if (bear1Active == 0) {
            bear1Top = low[2]
            bear1Bot = high
            bear1Bar = barCount
            bear1Active = 1
            bear1Mitigated = 0
            bear1Filled = 0
        } else if (bear2Active == 0) {
            bear2Top = low[2]
            bear2Bot = high
            bear2Bar = barCount
            bear2Active = 1
            bear2Mitigated = 0
            bear2Filled = 0
        } else if (bear3Active == 0) {
            bear3Top = low[2]
            bear3Bot = high
            bear3Bar = barCount
            bear3Active = 1
            bear3Mitigated = 0
            bear3Filled = 0
        }
    }

    // --- Mitigation: price returns to the zone (touches or enters) ---
    // Bullish FVG mitigated when price enters [bullBot, bullTop]
    if (bull1Active == 1 && bull1Filled == 0) {
        if (low <= bull1Top && high >= bull1Bot) {
            bull1Mitigated = 1
        }
    }
    if (bull2Active == 1 && bull2Filled == 0) {
        if (low <= bull2Top && high >= bull2Bot) {
            bull2Mitigated = 1
        }
    }
    if (bull3Active == 1 && bull3Filled == 0) {
        if (low <= bull3Top && high >= bull3Bot) {
            bull3Mitigated = 1
        }
    }

    if (bear1Active == 1 && bear1Filled == 0) {
        if (high >= bear1Bot && low <= bear1Top) {
            bear1Mitigated = 1
        }
    }
    if (bear2Active == 1 && bear2Filled == 0) {
        if (high >= bear2Bot && low <= bear2Top) {
            bear2Mitigated = 1
        }
    }
    if (bear3Active == 1 && bear3Filled == 0) {
        if (high >= bear3Bot && low <= bear3Top) {
            bear3Mitigated = 1
        }
    }

    // --- Fill detection: gap is closed when price crosses the fill threshold ---
    // Bullish filled when close <= bullBot + (bullTop - bullBot) * fillPct / 100
    if (bull1Active == 1 && bull1Filled == 0) {
        if (close <= bull1Bot + (bull1Top - bull1Bot) * fillPct / 100.0) {
            bull1Filled = 1
        }
    }
    if (bull2Active == 1 && bull2Filled == 0) {
        if (close <= bull2Bot + (bull2Top - bull2Bot) * fillPct / 100.0) {
            bull2Filled = 1
        }
    }
    if (bull3Active == 1 && bull3Filled == 0) {
        if (close <= bull3Bot + (bull3Top - bull3Bot) * fillPct / 100.0) {
            bull3Filled = 1
        }
    }

    if (bear1Active == 1 && bear1Filled == 0) {
        if (close >= bear1Bot + (bear1Top - bear1Bot) * fillPct / 100.0) {
            bear1Filled = 1
        }
    }
    if (bear2Active == 1 && bear2Filled == 0) {
        if (close >= bear2Bot + (bear2Top - bear2Bot) * fillPct / 100.0) {
            bear2Filled = 1
        }
    }
    if (bear3Active == 1 && bear3Filled == 0) {
        if (close >= bear3Bot + (bear3Top - bear3Bot) * fillPct / 100.0) {
            bear3Filled = 1
        }
    }
}

// ---------------------------------------------------------------------------
// 7. ACTIVE ZONE COUNTERS
// ---------------------------------------------------------------------------
var activeBullCount = 0
var activeBearCount = 0
var totalFVGSize = 0.0

if (bull1Active == 1 && bull1Filled == 0) { activeBullCount = activeBullCount + 1; totalFVGSize = totalFVGSize + (bull1Top - bull1Bot) }
if (bull2Active == 1 && bull2Filled == 0) { activeBullCount = activeBullCount + 1; totalFVGSize = totalFVGSize + (bull2Top - bull2Bot) }
if (bull3Active == 1 && bull3Filled == 0) { activeBullCount = activeBullCount + 1; totalFVGSize = totalFVGSize + (bull3Top - bull3Bot) }
if (bear1Active == 1 && bear1Filled == 0) { activeBearCount = activeBearCount + 1; totalFVGSize = totalFVGSize + (bear1Top - bear1Bot) }
if (bear2Active == 1 && bear2Filled == 0) { activeBearCount = activeBearCount + 1; totalFVGSize = totalFVGSize + (bear2Top - bear2Bot) }
if (bear3Active == 1 && bear3Filled == 0) { activeBearCount = activeBearCount + 1; totalFVGSize = totalFVGSize + (bear3Top - bear3Bot) }

// ---------------------------------------------------------------------------
// 8. BULLISH FVG ZONES (plotLine with fill)
// ---------------------------------------------------------------------------
// Zone 1
if (bull1Active == 1) {
    var b1TopColor = bull1Filled == 1 ? filledColor : (bull1Mitigated == 1 ? bullWeakColor : bullColor)
    var b1BotColor = bull1Filled == 1 ? filledColor : (bull1Mitigated == 1 ? bullWeakColor : bullColor)
    var b1Fill = bull1Filled == 1 ? transparency(filledColor, 20) : (bull1Mitigated == 1 ? transparency(bullWeakColor, 30) : transparency(bullColor, 40))

    if (bull1Filled == 0 || showFilled) {
        plotLine(
            value=[bull1Top, bull1Bot],
            width=1,
            colors=[b1TopColor, b1BotColor],
            fill=b1Fill,
            label=["Bull FVG 1", "Bull FVG 1"],
            desc=["Bullish FVG top boundary: low[0] > high[2]", "Bullish FVG bottom boundary"]
        )
        if (showMidline) {
            plotLine(
                value=(bull1Top + bull1Bot) / 2,
                width=1,
                colors=[transparency(bullColor, 50)],
                label=["Bull FVG 1 Mid"],
                desc=["Bullish FVG midline"]
            )
        }
    }

    if (showShapeMarkers && bull1Bar == barCount) {
        plotShape(
            value=bull1Top,
            shape="rectangle",
            colorIndex=bullShapeColor,
            width=4,
            label=["Bull FVG Formed"],
            desc=["Bullish Fair Value Gap formed: low[0] > high[2]"]
        )
    }

    if (showMitigationMarkers && bull1Mitigated == 1 && bull1Bar != barCount) {
        if (low <= bull1Top && high >= bull1Bot) {
            plotShape(
                value=bull1Bot,
                shape="rectangle",
                colorIndex=bullWeakColor,
                width=3,
                label=["Bull FVG Mitigated"],
                desc=["Price returned to bullish FVG zone"]
            )
        }
    }
}

// Zone 2
if (bull2Active == 1) {
    var b2TopColor = bull2Filled == 1 ? filledColor : (bull2Mitigated == 1 ? bullWeakColor : bullColor)
    var b2BotColor = bull2Filled == 1 ? filledColor : (bull2Mitigated == 1 ? bullWeakColor : bullColor)
    var b2Fill = bull2Filled == 1 ? transparency(filledColor, 20) : (bull2Mitigated == 1 ? transparency(bullWeakColor, 30) : transparency(bullColor, 40))

    if (bull2Filled == 0 || showFilled) {
        plotLine(
            value=[bull2Top, bull2Bot],
            width=1,
            colors=[b2TopColor, b2BotColor],
            fill=b2Fill,
            label=["Bull FVG 2", "Bull FVG 2"],
            desc=["Bullish FVG top boundary", "Bullish FVG bottom boundary"]
        )
        if (showMidline) {
            plotLine(
                value=(bull2Top + bull2Bot) / 2,
                width=1,
                colors=[transparency(bullColor, 50)],
                label=["Bull FVG 2 Mid"],
                desc=["Bullish FVG midline"]
            )
        }
    }

    if (showShapeMarkers && bull2Bar == barCount) {
        plotShape(
            value=bull2Top,
            shape="rectangle",
            colorIndex=bullShapeColor,
            width=4,
            label=["Bull FVG Formed"],
            desc=["Bullish Fair Value Gap formed: low[0] > high[2]"]
        )
    }

    if (showMitigationMarkers && bull2Mitigated == 1 && bull2Bar != barCount) {
        if (low <= bull2Top && high >= bull2Bot) {
            plotShape(
                value=bull2Bot,
                shape="rectangle",
                colorIndex=bullWeakColor,
                width=3,
                label=["Bull FVG Mitigated"],
                desc=["Price returned to bullish FVG zone"]
            )
        }
    }
}

// Zone 3
if (bull3Active == 1) {
    var b3TopColor = bull3Filled == 1 ? filledColor : (bull3Mitigated == 1 ? bullWeakColor : bullColor)
    var b3BotColor = bull3Filled == 1 ? filledColor : (bull3Mitigated == 1 ? bullWeakColor : bullColor)
    var b3Fill = bull3Filled == 1 ? transparency(filledColor, 20) : (bull3Mitigated == 1 ? transparency(bullWeakColor, 30) : transparency(bullColor, 40))

    if (bull3Filled == 0 || showFilled) {
        plotLine(
            value=[bull3Top, bull3Bot],
            width=1,
            colors=[b3TopColor, b3BotColor],
            fill=b3Fill,
            label=["Bull FVG 3", "Bull FVG 3"],
            desc=["Bullish FVG top boundary", "Bullish FVG bottom boundary"]
        )
        if (showMidline) {
            plotLine(
                value=(bull3Top + bull3Bot) / 2,
                width=1,
                colors=[transparency(bullColor, 50)],
                label=["Bull FVG 3 Mid"],
                desc=["Bullish FVG midline"]
            )
        }
    }

    if (showShapeMarkers && bull3Bar == barCount) {
        plotShape(
            value=bull3Top,
            shape="rectangle",
            colorIndex=bullShapeColor,
            width=4,
            label=["Bull FVG Formed"],
            desc=["Bullish Fair Value Gap formed: low[0] > high[2]"]
        )
    }

    if (showMitigationMarkers && bull3Mitigated == 1 && bull3Bar != barCount) {
        if (low <= bull3Top && high >= bull3Bot) {
            plotShape(
                value=bull3Bot,
                shape="rectangle",
                colorIndex=bullWeakColor,
                width=3,
                label=["Bull FVG Mitigated"],
                desc=["Price returned to bullish FVG zone"]
            )
        }
    }
}

// ---------------------------------------------------------------------------
// 9. BEARISH FVG ZONES (plotLine with fill)
// ---------------------------------------------------------------------------
// Zone 1
if (bear1Active == 1) {
    var be1TopColor = bear1Filled == 1 ? filledColor : (bear1Mitigated == 1 ? bearWeakColor : bearColor)
    var be1BotColor = bear1Filled == 1 ? filledColor : (bear1Mitigated == 1 ? bearWeakColor : bearColor)
    var be1Fill = bear1Filled == 1 ? transparency(filledColor, 20) : (bear1Mitigated == 1 ? transparency(bearWeakColor, 30) : transparency(bearColor, 40))

    if (bear1Filled == 0 || showFilled) {
        plotLine(
            value=[bear1Top, bear1Bot],
            width=1,
            colors=[be1TopColor, be1BotColor],
            fill=be1Fill,
            label=["Bear FVG 1", "Bear FVG 1"],
            desc=["Bearish FVG top boundary: high[0] < low[2]", "Bearish FVG bottom boundary"]
        )
        if (showMidline) {
            plotLine(
                value=(bear1Top + bear1Bot) / 2,
                width=1,
                colors=[transparency(bearColor, 50)],
                label=["Bear FVG 1 Mid"],
                desc=["Bearish FVG midline"]
            )
        }
    }

    if (showShapeMarkers && bear1Bar == barCount) {
        plotShape(
            value=bear1Top,
            shape="rectangle",
            colorIndex=bearShapeColor,
            width=4,
            label=["Bear FVG Formed"],
            desc=["Bearish Fair Value Gap formed: high[0] < low[2]"]
        )
    }

    if (showMitigationMarkers && bear1Mitigated == 1 && bear1Bar != barCount) {
        if (high >= bear1Bot && low <= bear1Top) {
            plotShape(
                value=bear1Top,
                shape="rectangle",
                colorIndex=bearWeakColor,
                width=3,
                label=["Bear FVG Mitigated"],
                desc=["Price returned to bearish FVG zone"]
            )
        }
    }
}

// Zone 2
if (bear2Active == 1) {
    var be2TopColor = bear2Filled == 1 ? filledColor : (bear2Mitigated == 1 ? bearWeakColor : bearColor)
    var be2BotColor = bear2Filled == 1 ? filledColor : (bear2Mitigated == 1 ? bearWeakColor : bearColor)
    var be2Fill = bear2Filled == 1 ? transparency(filledColor, 20) : (bear2Mitigated == 1 ? transparency(bearWeakColor, 30) : transparency(bearColor, 40))

    if (bear2Filled == 0 || showFilled) {
        plotLine(
            value=[bear2Top, bear2Bot],
            width=1,
            colors=[be2TopColor, be2BotColor],
            fill=be2Fill,
            label=["Bear FVG 2", "Bear FVG 2"],
            desc=["Bearish FVG top boundary", "Bearish FVG bottom boundary"]
        )
        if (showMidline) {
            plotLine(
                value=(bear2Top + bear2Bot) / 2,
                width=1,
                colors=[transparency(bearColor, 50)],
                label=["Bear FVG 2 Mid"],
                desc=["Bearish FVG midline"]
            )
        }
    }

    if (showShapeMarkers && bear2Bar == barCount) {
        plotShape(
            value=bear2Top,
            shape="rectangle",
            colorIndex=bearShapeColor,
            width=4,
            label=["Bear FVG Formed"],
            desc=["Bearish Fair Value Gap formed: high[0] < low[2]"]
        )
    }

    if (showMitigationMarkers && bear2Mitigated == 1 && bear2Bar != barCount) {
        if (high >= bear2Bot && low <= bear2Top) {
            plotShape(
                value=bear2Top,
                shape="rectangle",
                colorIndex=bearWeakColor,
                width=3,
                label=["Bear FVG Mitigated"],
                desc=["Price returned to bearish FVG zone"]
            )
        }
    }
}

// Zone 3
if (bear3Active == 1) {
    var be3TopColor = bear3Filled == 1 ? filledColor : (bear3Mitigated == 1 ? bearWeakColor : bearColor)
    var be3BotColor = bear3Filled == 1 ? filledColor : (bear3Mitigated == 1 ? bearWeakColor : bearColor)
    var be3Fill = bear3Filled == 1 ? transparency(filledColor, 20) : (bear3Mitigated == 1 ? transparency(bearWeakColor, 30) : transparency(bearColor, 40))

    if (bear3Filled == 0 || showFilled) {
        plotLine(
            value=[bear3Top, bear3Bot],
            width=1,
            colors=[be3TopColor, be3BotColor],
            fill=be3Fill,
            label=["Bear FVG 3", "Bear FVG 3"],
            desc=["Bearish FVG top boundary", "Bearish FVG bottom boundary"]
        )
        if (showMidline) {
            plotLine(
                value=(bear3Top + bear3Bot) / 2,
                width=1,
                colors=[transparency(bearColor, 50)],
                label=["Bear FVG 3 Mid"],
                desc=["Bearish FVG midline"]
            )
        }
    }

    if (showShapeMarkers && bear3Bar == barCount) {
        plotShape(
            value=bear3Top,
            shape="rectangle",
            colorIndex=bearShapeColor,
            width=4,
            label=["Bear FVG Formed"],
            desc=["Bearish Fair Value Gap formed: high[0] < low[2]"]
        )
    }

    if (showMitigationMarkers && bear3Mitigated == 1 && bear3Bar != barCount) {
        if (high >= bear3Bot && low <= bear3Top) {
            plotShape(
                value=bear3Top,
                shape="rectangle",
                colorIndex=bearWeakColor,
                width=3,
                label=["Bear FVG Mitigated"],
                desc=["Price returned to bearish FVG zone"]
            )
        }
    }
}

// ---------------------------------------------------------------------------
// 10. FVG SIZE HISTOGRAM
// ---------------------------------------------------------------------------
if (showFVGSize && totalFVGSize > 0) {
    var fvgBarColor = activeBullCount > activeBearCount ? bullColor : bearColor
    plotBar(
        value=totalFVGSize,
        colors=[fvgBarColor],
        width=1,
        label=["Total FVG Size"],
        desc=["Sum of active unfilled FVG zone sizes in price units"]
    )
}

// ---------------------------------------------------------------------------
// 11. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var totalActive = activeBullCount + activeBearCount
    var totalMitigated = 0
    if (bull1Mitigated == 1) { totalMitigated = totalMitigated + 1 }
    if (bull2Mitigated == 1) { totalMitigated = totalMitigated + 1 }
    if (bull3Mitigated == 1) { totalMitigated = totalMitigated + 1 }
    if (bear1Mitigated == 1) { totalMitigated = totalMitigated + 1 }
    if (bear2Mitigated == 1) { totalMitigated = totalMitigated + 1 }
    if (bear3Mitigated == 1) { totalMitigated = totalMitigated + 1 }

    var totalFilled = 0
    if (bull1Filled == 1) { totalFilled = totalFilled + 1 }
    if (bull2Filled == 1) { totalFilled = totalFilled + 1 }
    if (bull3Filled == 1) { totalFilled = totalFilled + 1 }
    if (bear1Filled == 1) { totalFilled = totalFilled + 1 }
    if (bear2Filled == 1) { totalFilled = totalFilled + 1 }
    if (bear3Filled == 1) { totalFilled = totalFilled + 1 }

    plotTable(
        data=[
            ["FVG Leviathan", "Summary"],
            ["Active bull", activeBullCount],
            ["Active bear", activeBearCount],
            ["Total active", totalActive],
            ["Mitigated", totalMitigated],
            ["Filled", totalFilled],
            ["Total FVG size", totalFVGSize]
        ],
        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
    )
}