MM Flow
FlowScripts

Perfected FlowScript

Fair Value Gaps - [haste]

Fair Value Gaps — Haste • Perfected Edition is indexed as 238_fair_value_gaps_haste.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

31.5 KB

Lines

834

Native Signal Candidates

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

5/5 guarded

Bull FVG Formed

line 730:9

Trigger

(showFormationMarkers) && (bullFormEvent1 || bullFormEvent2 || bullFormEvent3 || bullFormEvent4 || bullFormEvent5)

Value

high

Deps

bullFormEvent1:var, bullFormEvent2:var, bullFormEvent3:var, bullFormEvent4:var, bullFormEvent5:var, showFormationMarkers:input

Bear FVG Formed

line 740:9

Trigger

(showFormationMarkers) && (bearFormEvent1 || bearFormEvent2 || bearFormEvent3 || bearFormEvent4 || bearFormEvent5)

Value

low

Deps

bearFormEvent1:var, bearFormEvent2:var, bearFormEvent3:var, bearFormEvent4:var, bearFormEvent5:var, showFormationMarkers:input

Bull FVG Filled

line 756:9

Trigger

(showMitigationMarkers) && (bullFillEvent1 || bullFillEvent2 || bullFillEvent3 || bullFillEvent4 || bullFillEvent5)

Value

high

Deps

bullFillEvent1:var, bullFillEvent2:var, bullFillEvent3:var, bullFillEvent4:var, bullFillEvent5:var, showMitigationMarkers:input

Bear FVG Filled

line 766:9

Trigger

(showMitigationMarkers) && (bearFillEvent1 || bearFillEvent2 || bearFillEvent3 || bearFillEvent4 || bearFillEvent5)

Value

low

Deps

bearFillEvent1:var, bearFillEvent2:var, bearFillEvent3:var, bearFillEvent4:var, bearFillEvent5:var, showMitigationMarkers:input

Unlabeled shape

line 784:5

Trigger

(showActiveCount && isLastBar)

Value

high

Deps

isLastBar:builtin, showActiveCount:input

238_fair_value_gaps_haste.flowscript

source path: kscripts/perfected/238_fair_value_gaps_haste.flowscript · sha256:8492a239bd8cb41be423cdc3b0f39bf5010f2ea331625937bb3356f761d85467

hash verified
//@version=2
// ============================================================================
// Fair Value Gaps — Haste • Perfected Edition
// Author: living_anamoly (@living_anamoly) | Enhanced by kScript Perfection Engineer
// Tags: FLOW, #imbalance, #gap, #fvg, #microstructure, #smartmoney
//
// Production-grade fast Fair Value Gap detector with three-candle imbalance
// pattern recognition, stateful gap tracking with mitigation/invalidation,
// box drawing with fill, and shape markers for formation and rebalancing events.
// Implements "haste" mode: detects FVGs as soon as the third candle completes,
// tracks fill status across bars, and provides visual alerts on gap closure.
//
// Academic foundations:
//  - Pecchiari (2020), "Orderflow Imbalance and High Frequency Trading" (LUISS
//    Thesis). Quantile regression: OFI_t = γ₀ + γ₁·|ΔBid_t| + γ₂·|ΔAsk_t| +
//    γ₃·Vol_t + u_t. FVGs manifest as order-flow imbalance signatures where
//    aggressive one-sided pressure creates rapid moves with little candle overlap.
//  - Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey" (J. Financial
//    Markets, 699+ citations). Framework: latent demands D(p) → realized prices
//    via λ·ΣX_i. FVGs represent temporary price-discovery inefficiencies—moments
//    when latent demand overwhelms available liquidity, leaving unfilled zones.
//  - 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"
//    these gaps to correct imbalance.
//  - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events"
//    (J. Financial Econometrics, 12(1), 47–88). OFI-price impact linearity:
//    Δp ∝ OFI/depth. FVG size is proportional to the depth-depletion event that
//    created it; larger gaps imply deeper liquidity exhaustion.
//  - Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
//    Order Flow and Stock Returns" (NBER 11439). Institutional flow creates
//    persistent price impact; FVGs mark zones where institutional absorption
//    left unfilled demand/supply that later attracts rebalancing.
// ============================================================================

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

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

// --- FVG Detection ---
var fvgMinSize = input(
    name="fvgMinSize",
    type="number",
    defaultValue=0.0,
    label="Minimum FVG Size (price units)",
    constraints={min: 0.0, max: 1000.0, step: 0.1},
    group="FVG Detection"
)
var gapThreshold = input(
    name="gapThreshold",
    type="number",
    defaultValue=0.001,
    label="Gap Threshold (% of close)",
    constraints={min: 0.0, max: 0.1, step: 0.001},
    group="FVG Detection"
)
var showBullish = input(
    name="showBullish",
    type="boolean",
    defaultValue=true,
    label="Show Bullish FVGs",
    group="FVG Detection"
)
var showBearish = input(
    name="showBearish",
    type="boolean",
    defaultValue=true,
    label="Show Bearish FVGs",
    group="FVG Detection"
)

// --- Mitigation ---
var showMitigated = input(
    name="showMitigated",
    type="boolean",
    defaultValue=true,
    label="Show Mitigated (Filled) Gaps",
    group="Mitigation"
)
var showMitigationMarkers = input(
    name="showMitigationMarkers",
    type="boolean",
    defaultValue=true,
    label="Show Mitigation Markers",
    group="Mitigation"
)

// --- Display ---
var showFVGBar = input(
    name="showFVGBar",
    type="boolean",
    defaultValue=true,
    label="Show FVG Size Histogram",
    group="Display"
)
var showFormationMarkers = input(
    name="showFormationMarkers",
    type="boolean",
    defaultValue=true,
    label="Show Formation Markers",
    group="Display"
)
var showActiveCount = input(
    name="showActiveCount",
    type="boolean",
    defaultValue=true,
    label="Show Active FVG Count Label",
    group="Display"
)

// --- Colors ---
var fvgBullColor = input(
    name="fvgBullColor",
    type="color",
    defaultValue="#00e676",
    label="Bullish FVG Color",
    group="Colors"
)
var fvgBullWeakColor = input(
    name="fvgBullWeakColor",
    type="color",
    defaultValue="#4db6ac",
    label="Bullish FVG Mitigated Color",
    group="Colors"
)
var fvgBearColor = input(
    name="fvgBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Bearish FVG Color",
    group="Colors"
)
var fvgBearWeakColor = input(
    name="fvgBearWeakColor",
    type="color",
    defaultValue="#ef9a9a",
    label="Bearish FVG Mitigated Color",
    group="Colors"
)
var fillBullColor = input(
    name="fillBullColor",
    type="color",
    defaultValue="#00e67640",
    label="Bullish Fill Color",
    group="Colors"
)
var fillBearColor = input(
    name="fillBearColor",
    type="color",
    defaultValue="#ff525240",
    label="Bearish Fill Color",
    group="Colors"
)
var formationColor = input(
    name="formationColor",
    type="color",
    defaultValue="#ffd700",
    label="Formation Marker Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

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

// isnan guard on first use of external data — prevents NaN propagation on startup
if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(open[0])) {
    return
}

// ------------------------------------------------------------------------------
// 3. THREE-CANDLE FVG PATTERN DETECTION
// ------------------------------------------------------------------------------
// Bullish FVG (bearish impulse gap): low[0] > high[2]
//   Candle 1: bearish impulse (strong down move)
//   Candle 2: consolidation inside Candle 1 range
//   Candle 3: continuation low above Candle 1 high → gap between C1 high and C3 low
// Bearish FVG (bullish impulse gap): high[0] < low[2]
//   Candle 1: bullish impulse (strong up move)
//   Candle 2: consolidation inside Candle 1 range
//   Candle 3: continuation high below Candle 1 low → gap between C1 low and C3 high
//
// Per Smart Money Pros (2024) and Pecchiari (2020) order-flow imbalance framework.

var bullishFVG = !isnan(high[2]) && low > high[2] && (low - high[2]) >= fvgMinSize && ((low - high[2]) / close) >= gapThreshold
var bearishFVG = !isnan(low[2]) && high < low[2] && (low[2] - high) >= fvgMinSize && ((low[2] - high) / close) >= gapThreshold

// Gap boundaries for this bar
var currBullTop = bullishFVG ? low : na
var currBullBot = bullishFVG ? high[2] : na
var currBearTop = bearishFVG ? low[2] : na
var currBearBot = bearishFVG ? high : na

// ------------------------------------------------------------------------------
// 4. BAR COUNTER & STATIC STATE
// ------------------------------------------------------------------------------
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// --- STATIC STATE: Bullish FVG tracking ---
// We track up to 5 concurrent bullish FVGs using arrays of static variables.
// For each gap: top, bottom, active flag, mitigated flag, formation bar, fill bar.
static fvgBullTop1 = 0.0
static fvgBullBot1 = 0.0
static fvgBullActive1 = 0
static fvgBullMitigated1 = 0
static fvgBullBar1 = 0
static fvgBullFillBar1 = 0

static fvgBullTop2 = 0.0
static fvgBullBot2 = 0.0
static fvgBullActive2 = 0
static fvgBullMitigated2 = 0
static fvgBullBar2 = 0
static fvgBullFillBar2 = 0

static fvgBullTop3 = 0.0
static fvgBullBot3 = 0.0
static fvgBullActive3 = 0
static fvgBullMitigated3 = 0
static fvgBullBar3 = 0
static fvgBullFillBar3 = 0

static fvgBullTop4 = 0.0
static fvgBullBot4 = 0.0
static fvgBullActive4 = 0
static fvgBullMitigated4 = 0
static fvgBullBar4 = 0
static fvgBullFillBar4 = 0

static fvgBullTop5 = 0.0
static fvgBullBot5 = 0.0
static fvgBullActive5 = 0
static fvgBullMitigated5 = 0
static fvgBullBar5 = 0
static fvgBullFillBar5 = 0

// --- STATIC STATE: Bearish FVG tracking ---
static fvgBearTop1 = 0.0
static fvgBearBot1 = 0.0
static fvgBearActive1 = 0
static fvgBearMitigated1 = 0
static fvgBearBar1 = 0
static fvgBearFillBar1 = 0

static fvgBearTop2 = 0.0
static fvgBearBot2 = 0.0
static fvgBearActive2 = 0
static fvgBearMitigated2 = 0
static fvgBearBar2 = 0
static fvgBearFillBar2 = 0

static fvgBearTop3 = 0.0
static fvgBearBot3 = 0.0
static fvgBearActive3 = 0
static fvgBearMitigated3 = 0
static fvgBearBar3 = 0
static fvgBearFillBar3 = 0

static fvgBearTop4 = 0.0
static fvgBearBot4 = 0.0
static fvgBearActive4 = 0
static fvgBearMitigated4 = 0
static fvgBearBar4 = 0
static fvgBearFillBar4 = 0

static fvgBearTop5 = 0.0
static fvgBearBot5 = 0.0
static fvgBearActive5 = 0
static fvgBearMitigated5 = 0
static fvgBearBar5 = 0
static fvgBearFillBar5 = 0

// Helper function to find first inactive bullish slot and assign
// (inline for kScript compatibility)
// --- STATE UPDATE (only on bar close) ---
if (!isLiveUpdate) {
    // --- Bullish FVG formation ---
    if (bullishFVG) {
        if (fvgBullActive1 == 0) {
            fvgBullTop1 = currBullTop
            fvgBullBot1 = currBullBot
            fvgBullActive1 = 1
            fvgBullMitigated1 = 0
            fvgBullBar1 = barCount
            fvgBullFillBar1 = 0
        } else if (fvgBullActive2 == 0) {
            fvgBullTop2 = currBullTop
            fvgBullBot2 = currBullBot
            fvgBullActive2 = 1
            fvgBullMitigated2 = 0
            fvgBullBar2 = barCount
            fvgBullFillBar2 = 0
        } else if (fvgBullActive3 == 0) {
            fvgBullTop3 = currBullTop
            fvgBullBot3 = currBullBot
            fvgBullActive3 = 1
            fvgBullMitigated3 = 0
            fvgBullBar3 = barCount
            fvgBullFillBar3 = 0
        } else if (fvgBullActive4 == 0) {
            fvgBullTop4 = currBullTop
            fvgBullBot4 = currBullBot
            fvgBullActive4 = 1
            fvgBullMitigated4 = 0
            fvgBullBar4 = barCount
            fvgBullFillBar4 = 0
        } else if (fvgBullActive5 == 0) {
            fvgBullTop5 = currBullTop
            fvgBullBot5 = currBullBot
            fvgBullActive5 = 1
            fvgBullMitigated5 = 0
            fvgBullBar5 = barCount
            fvgBullFillBar5 = 0
        } else {
            // Shift queue: oldest (1) dropped, 2→1, 3→2, 4→3, 5→4, new→5
            fvgBullTop1 = fvgBullTop2
            fvgBullBot1 = fvgBullBot2
            fvgBullActive1 = fvgBullActive2
            fvgBullMitigated1 = fvgBullMitigated2
            fvgBullBar1 = fvgBullBar2
            fvgBullFillBar1 = fvgBullFillBar2
            fvgBullTop2 = fvgBullTop3
            fvgBullBot2 = fvgBullBot3
            fvgBullActive2 = fvgBullActive3
            fvgBullMitigated2 = fvgBullMitigated3
            fvgBullBar2 = fvgBullBar3
            fvgBullFillBar2 = fvgBullFillBar3
            fvgBullTop3 = fvgBullTop4
            fvgBullBot3 = fvgBullBot4
            fvgBullActive3 = fvgBullActive4
            fvgBullMitigated3 = fvgBullMitigated4
            fvgBullBar3 = fvgBullBar4
            fvgBullFillBar3 = fvgBullFillBar4
            fvgBullTop4 = fvgBullTop5
            fvgBullBot4 = fvgBullBot5
            fvgBullActive4 = fvgBullActive5
            fvgBullMitigated4 = fvgBullMitigated5
            fvgBullBar4 = fvgBullBar5
            fvgBullFillBar4 = fvgBullFillBar5
            fvgBullTop5 = currBullTop
            fvgBullBot5 = currBullBot
            fvgBullActive5 = 1
            fvgBullMitigated5 = 0
            fvgBullBar5 = barCount
            fvgBullFillBar5 = 0
        }
    }

    // --- Bearish FVG formation ---
    if (bearishFVG) {
        if (fvgBearActive1 == 0) {
            fvgBearTop1 = currBearTop
            fvgBearBot1 = currBearBot
            fvgBearActive1 = 1
            fvgBearMitigated1 = 0
            fvgBearBar1 = barCount
            fvgBearFillBar1 = 0
        } else if (fvgBearActive2 == 0) {
            fvgBearTop2 = currBearTop
            fvgBearBot2 = currBearBot
            fvgBearActive2 = 1
            fvgBearMitigated2 = 0
            fvgBearBar2 = barCount
            fvgBearFillBar2 = 0
        } else if (fvgBearActive3 == 0) {
            fvgBearTop3 = currBearTop
            fvgBearBot3 = currBearBot
            fvgBearActive3 = 1
            fvgBearMitigated3 = 0
            fvgBearBar3 = barCount
            fvgBearFillBar3 = 0
        } else if (fvgBearActive4 == 0) {
            fvgBearTop4 = currBearTop
            fvgBearBot4 = currBearBot
            fvgBearActive4 = 1
            fvgBearMitigated4 = 0
            fvgBearBar4 = barCount
            fvgBearFillBar4 = 0
        } else if (fvgBearActive5 == 0) {
            fvgBearTop5 = currBearTop
            fvgBearBot5 = currBearBot
            fvgBearActive5 = 1
            fvgBearMitigated5 = 0
            fvgBearBar5 = barCount
            fvgBearFillBar5 = 0
        } else {
            // Shift queue
            fvgBearTop1 = fvgBearTop2
            fvgBearBot1 = fvgBearBot2
            fvgBearActive1 = fvgBearActive2
            fvgBearMitigated1 = fvgBearMitigated2
            fvgBearBar1 = fvgBearBar2
            fvgBearFillBar1 = fvgBearFillBar2
            fvgBearTop2 = fvgBearTop3
            fvgBearBot2 = fvgBearBot3
            fvgBearActive2 = fvgBearActive3
            fvgBearMitigated2 = fvgBearMitigated3
            fvgBearBar2 = fvgBearBar3
            fvgBearFillBar2 = fvgBearFillBar3
            fvgBearTop3 = fvgBearTop4
            fvgBearBot3 = fvgBearBot4
            fvgBearActive3 = fvgBearActive4
            fvgBearMitigated3 = fvgBearMitigated4
            fvgBearBar3 = fvgBearBar4
            fvgBearFillBar3 = fvgBearFillBar4
            fvgBearTop4 = fvgBearTop5
            fvgBearBot4 = fvgBearBot5
            fvgBearActive4 = fvgBearActive5
            fvgBearMitigated4 = fvgBearMitigated5
            fvgBearBar4 = fvgBearBar5
            fvgBearFillBar4 = fvgBearFillBar5
            fvgBearTop5 = currBearTop
            fvgBearBot5 = currBearBot
            fvgBearActive5 = 1
            fvgBearMitigated5 = 0
            fvgBearBar5 = barCount
            fvgBearFillBar5 = 0
        }
    }

    // --- Mitigation / Fill detection for bullish FVGs ---
    // Gap is filled when price closes into or through the gap zone
    if (fvgBullActive1 == 1 && fvgBullMitigated1 == 0) {
        if (low <= fvgBullBot1) {
            fvgBullMitigated1 = 1
            fvgBullFillBar1 = barCount
        }
    }
    if (fvgBullActive2 == 1 && fvgBullMitigated2 == 0) {
        if (low <= fvgBullBot2) {
            fvgBullMitigated2 = 1
            fvgBullFillBar2 = barCount
        }
    }
    if (fvgBullActive3 == 1 && fvgBullMitigated3 == 0) {
        if (low <= fvgBullBot3) {
            fvgBullMitigated3 = 1
            fvgBullFillBar3 = barCount
        }
    }
    if (fvgBullActive4 == 1 && fvgBullMitigated4 == 0) {
        if (low <= fvgBullBot4) {
            fvgBullMitigated4 = 1
            fvgBullFillBar4 = barCount
        }
    }
    if (fvgBullActive5 == 1 && fvgBullMitigated5 == 0) {
        if (low <= fvgBullBot5) {
            fvgBullMitigated5 = 1
            fvgBullFillBar5 = barCount
        }
    }

    // --- Mitigation / Fill detection for bearish FVGs ---
    if (fvgBearActive1 == 1 && fvgBearMitigated1 == 0) {
        if (high >= fvgBearTop1) {
            fvgBearMitigated1 = 1
            fvgBearFillBar1 = barCount
        }
    }
    if (fvgBearActive2 == 1 && fvgBearMitigated2 == 0) {
        if (high >= fvgBearTop2) {
            fvgBearMitigated2 = 1
            fvgBearFillBar2 = barCount
        }
    }
    if (fvgBearActive3 == 1 && fvgBearMitigated3 == 0) {
        if (high >= fvgBearTop3) {
            fvgBearMitigated3 = 1
            fvgBearFillBar3 = barCount
        }
    }
    if (fvgBearActive4 == 1 && fvgBearMitigated4 == 0) {
        if (high >= fvgBearTop4) {
            fvgBearMitigated4 = 1
            fvgBearFillBar4 = barCount
        }
    }
    if (fvgBearActive5 == 1 && fvgBearMitigated5 == 0) {
        if (high >= fvgBearTop5) {
            fvgBearMitigated5 = 1
            fvgBearFillBar5 = barCount
        }
    }
}

// ------------------------------------------------------------------------------
// 5. EVENT FLAGS FOR PLOTTING
// ------------------------------------------------------------------------------
var bullFormEvent1 = fvgBullBar1 == barCount && fvgBullActive1 == 1
var bullFormEvent2 = fvgBullBar2 == barCount && fvgBullActive2 == 1
var bullFormEvent3 = fvgBullBar3 == barCount && fvgBullActive3 == 1
var bullFormEvent4 = fvgBullBar4 == barCount && fvgBullActive4 == 1
var bullFormEvent5 = fvgBullBar5 == barCount && fvgBullActive5 == 1

var bearFormEvent1 = fvgBearBar1 == barCount && fvgBearActive1 == 1
var bearFormEvent2 = fvgBearBar2 == barCount && fvgBearActive2 == 1
var bearFormEvent3 = fvgBearBar3 == barCount && fvgBearActive3 == 1
var bearFormEvent4 = fvgBearBar4 == barCount && fvgBearActive4 == 1
var bearFormEvent5 = fvgBearBar5 == barCount && fvgBearActive5 == 1

var bullFillEvent1 = fvgBullFillBar1 == barCount && fvgBullMitigated1 == 1
var bullFillEvent2 = fvgBullFillBar2 == barCount && fvgBullMitigated2 == 1
var bullFillEvent3 = fvgBullFillBar3 == barCount && fvgBullMitigated3 == 1
var bullFillEvent4 = fvgBullFillBar4 == barCount && fvgBullMitigated4 == 1
var bullFillEvent5 = fvgBullFillBar5 == barCount && fvgBullMitigated5 == 1

var bearFillEvent1 = fvgBearFillBar1 == barCount && fvgBearMitigated1 == 1
var bearFillEvent2 = fvgBearFillBar2 == barCount && fvgBearMitigated2 == 1
var bearFillEvent3 = fvgBearFillBar3 == barCount && fvgBearMitigated3 == 1
var bearFillEvent4 = fvgBearFillBar4 == barCount && fvgBearMitigated4 == 1
var bearFillEvent5 = fvgBearFillBar5 == barCount && fvgBearMitigated5 == 1

// Active gap count for label
var activeBullCount = 0
var activeBearCount = 0
if (fvgBullActive1 == 1 && fvgBullMitigated1 == 0) { activeBullCount = activeBullCount + 1 }
if (fvgBullActive2 == 1 && fvgBullMitigated2 == 0) { activeBullCount = activeBullCount + 1 }
if (fvgBullActive3 == 1 && fvgBullMitigated3 == 0) { activeBullCount = activeBullCount + 1 }
if (fvgBullActive4 == 1 && fvgBullMitigated4 == 0) { activeBullCount = activeBullCount + 1 }
if (fvgBullActive5 == 1 && fvgBullMitigated5 == 0) { activeBullCount = activeBullCount + 1 }
if (fvgBearActive1 == 1 && fvgBearMitigated1 == 0) { activeBearCount = activeBearCount + 1 }
if (fvgBearActive2 == 1 && fvgBearMitigated2 == 0) { activeBearCount = activeBearCount + 1 }
if (fvgBearActive3 == 1 && fvgBearMitigated3 == 0) { activeBearCount = activeBearCount + 1 }
if (fvgBearActive4 == 1 && fvgBearMitigated4 == 0) { activeBearCount = activeBearCount + 1 }
if (fvgBearActive5 == 1 && fvgBearMitigated5 == 0) { activeBearCount = activeBearCount + 1 }

// Total FVG size for histogram
var fvgSize = 0.0
if (fvgBullActive1 == 1 && fvgBullMitigated1 == 0) { fvgSize = fvgSize + (fvgBullTop1 - fvgBullBot1) }
if (fvgBullActive2 == 1 && fvgBullMitigated2 == 0) { fvgSize = fvgSize + (fvgBullTop2 - fvgBullBot2) }
if (fvgBullActive3 == 1 && fvgBullMitigated3 == 0) { fvgSize = fvgSize + (fvgBullTop3 - fvgBullBot3) }
if (fvgBullActive4 == 1 && fvgBullMitigated4 == 0) { fvgSize = fvgSize + (fvgBullTop4 - fvgBullBot4) }
if (fvgBullActive5 == 1 && fvgBullMitigated5 == 0) { fvgSize = fvgSize + (fvgBullTop5 - fvgBullBot5) }
if (fvgBearActive1 == 1 && fvgBearMitigated1 == 0) { fvgSize = fvgSize + (fvgBearTop1 - fvgBearBot1) }
if (fvgBearActive2 == 1 && fvgBearMitigated2 == 0) { fvgSize = fvgSize + (fvgBearTop2 - fvgBearBot2) }
if (fvgBearActive3 == 1 && fvgBearMitigated3 == 0) { fvgSize = fvgSize + (fvgBearTop3 - fvgBearBot3) }
if (fvgBearActive4 == 1 && fvgBearMitigated4 == 0) { fvgSize = fvgSize + (fvgBearTop4 - fvgBearBot4) }
if (fvgBearActive5 == 1 && fvgBearMitigated5 == 0) { fvgSize = fvgSize + (fvgBearTop5 - fvgBearBot5) }

// ------------------------------------------------------------------------------
// 6. PLOTS: BULLISH FVG ZONES (plotLine with fill — boxes)
// ------------------------------------------------------------------------------
// Slot 1
if (showBullish && fvgBullActive1 == 1) {
    var b1color = fvgBullMitigated1 == 1 ? fvgBullWeakColor : fvgBullColor
    var b1fill = fvgBullMitigated1 == 1 ? opacity(fvgBullWeakColor, 30) : opacity(fvgBullColor, 50)
    if (fvgBullMitigated1 == 0 || showMitigated) {
        plotLine(
            value=[fvgBullTop1, fvgBullBot1],
            width=1,
            colors=[b1color, b1color],
            fill=b1fill,
            label=["Bull FVG 1", "Bull FVG 1"],
            desc=["Bullish Fair Value Gap top: low[0] > high[2]. Unfilled demand imbalance.", "Bullish FVG bottom boundary."]
        )
    }
}
if (showBullish && fvgBullActive2 == 1) {
    var b2color = fvgBullMitigated2 == 1 ? fvgBullWeakColor : fvgBullColor
    var b2fill = fvgBullMitigated2 == 1 ? opacity(fvgBullWeakColor, 30) : opacity(fvgBullColor, 50)
    if (fvgBullMitigated2 == 0 || showMitigated) {
        plotLine(
            value=[fvgBullTop2, fvgBullBot2],
            width=1,
            colors=[b2color, b2color],
            fill=b2fill,
            label=["Bull FVG 2", "Bull FVG 2"],
            desc=["Bullish Fair Value Gap top: low[0] > high[2]. Unfilled demand imbalance.", "Bullish FVG bottom boundary."]
        )
    }
}
if (showBullish && fvgBullActive3 == 1) {
    var b3color = fvgBullMitigated3 == 1 ? fvgBullWeakColor : fvgBullColor
    var b3fill = fvgBullMitigated3 == 1 ? opacity(fvgBullWeakColor, 30) : opacity(fvgBullColor, 50)
    if (fvgBullMitigated3 == 0 || showMitigated) {
        plotLine(
            value=[fvgBullTop3, fvgBullBot3],
            width=1,
            colors=[b3color, b3color],
            fill=b3fill,
            label=["Bull FVG 3", "Bull FVG 3"],
            desc=["Bullish Fair Value Gap top: low[0] > high[2]. Unfilled demand imbalance.", "Bullish FVG bottom boundary."]
        )
    }
}
if (showBullish && fvgBullActive4 == 1) {
    var b4color = fvgBullMitigated4 == 1 ? fvgBullWeakColor : fvgBullColor
    var b4fill = fvgBullMitigated4 == 1 ? opacity(fvgBullWeakColor, 30) : opacity(fvgBullColor, 50)
    if (fvgBullMitigated4 == 0 || showMitigated) {
        plotLine(
            value=[fvgBullTop4, fvgBullBot4],
            width=1,
            colors=[b4color, b4color],
            fill=b4fill,
            label=["Bull FVG 4", "Bull FVG 4"],
            desc=["Bullish Fair Value Gap top: low[0] > high[2]. Unfilled demand imbalance.", "Bullish FVG bottom boundary."]
        )
    }
}
if (showBullish && fvgBullActive5 == 1) {
    var b5color = fvgBullMitigated5 == 1 ? fvgBullWeakColor : fvgBullColor
    var b5fill = fvgBullMitigated5 == 1 ? opacity(fvgBullWeakColor, 30) : opacity(fvgBullColor, 50)
    if (fvgBullMitigated5 == 0 || showMitigated) {
        plotLine(
            value=[fvgBullTop5, fvgBullBot5],
            width=1,
            colors=[b5color, b5color],
            fill=b5fill,
            label=["Bull FVG 5", "Bull FVG 5"],
            desc=["Bullish Fair Value Gap top: low[0] > high[2]. Unfilled demand imbalance.", "Bullish FVG bottom boundary."]
        )
    }
}

// ------------------------------------------------------------------------------
// 7. PLOTS: BEARISH FVG ZONES (plotLine with fill — boxes)
// ------------------------------------------------------------------------------
if (showBearish && fvgBearActive1 == 1) {
    var r1color = fvgBearMitigated1 == 1 ? fvgBearWeakColor : fvgBearColor
    var r1fill = fvgBearMitigated1 == 1 ? opacity(fvgBearWeakColor, 30) : opacity(fvgBearColor, 50)
    if (fvgBearMitigated1 == 0 || showMitigated) {
        plotLine(
            value=[fvgBearTop1, fvgBearBot1],
            width=1,
            colors=[r1color, r1color],
            fill=r1fill,
            label=["Bear FVG 1", "Bear FVG 1"],
            desc=["Bearish Fair Value Gap top: high[0] < low[2]. Unfilled supply imbalance.", "Bearish FVG bottom boundary."]
        )
    }
}
if (showBearish && fvgBearActive2 == 1) {
    var r2color = fvgBearMitigated2 == 1 ? fvgBearWeakColor : fvgBearColor
    var r2fill = fvgBearMitigated2 == 1 ? opacity(fvgBearWeakColor, 30) : opacity(fvgBearColor, 50)
    if (fvgBearMitigated2 == 0 || showMitigated) {
        plotLine(
            value=[fvgBearTop2, fvgBearBot2],
            width=1,
            colors=[r2color, r2color],
            fill=r2fill,
            label=["Bear FVG 2", "Bear FVG 2"],
            desc=["Bearish Fair Value Gap top: high[0] < low[2]. Unfilled supply imbalance.", "Bearish FVG bottom boundary."]
        )
    }
}
if (showBearish && fvgBearActive3 == 1) {
    var r3color = fvgBearMitigated3 == 1 ? fvgBearWeakColor : fvgBearColor
    var r3fill = fvgBearMitigated3 == 1 ? opacity(fvgBearWeakColor, 30) : opacity(fvgBearColor, 50)
    if (fvgBearMitigated3 == 0 || showMitigated) {
        plotLine(
            value=[fvgBearTop3, fvgBearBot3],
            width=1,
            colors=[r3color, r3color],
            fill=r3fill,
            label=["Bear FVG 3", "Bear FVG 3"],
            desc=["Bearish Fair Value Gap top: high[0] < low[2]. Unfilled supply imbalance.", "Bearish FVG bottom boundary."]
        )
    }
}
if (showBearish && fvgBearActive4 == 1) {
    var r4color = fvgBearMitigated4 == 1 ? fvgBearWeakColor : fvgBearColor
    var r4fill = fvgBearMitigated4 == 1 ? opacity(fvgBearWeakColor, 30) : opacity(fvgBearColor, 50)
    if (fvgBearMitigated4 == 0 || showMitigated) {
        plotLine(
            value=[fvgBearTop4, fvgBearBot4],
            width=1,
            colors=[r4color, r4color],
            fill=r4fill,
            label=["Bear FVG 4", "Bear FVG 4"],
            desc=["Bearish Fair Value Gap top: high[0] < low[2]. Unfilled supply imbalance.", "Bearish FVG bottom boundary."]
        )
    }
}
if (showBearish && fvgBearActive5 == 1) {
    var r5color = fvgBearMitigated5 == 1 ? fvgBearWeakColor : fvgBearColor
    var r5fill = fvgBearMitigated5 == 1 ? opacity(fvgBearWeakColor, 30) : opacity(fvgBearColor, 50)
    if (fvgBearMitigated5 == 0 || showMitigated) {
        plotLine(
            value=[fvgBearTop5, fvgBearBot5],
            width=1,
            colors=[r5color, r5color],
            fill=r5fill,
            label=["Bear FVG 5", "Bear FVG 5"],
            desc=["Bearish Fair Value Gap top: high[0] < low[2]. Unfilled supply imbalance.", "Bearish FVG bottom boundary."]
        )
    }
}

// ------------------------------------------------------------------------------
// 8. PLOTS: FVG SIZE HISTOGRAM (plotBar)
// ------------------------------------------------------------------------------
if (showFVGBar && fvgSize > 0) {
    var histColor = activeBullCount > activeBearCount ? fvgBullColor : (activeBearCount > activeBullCount ? fvgBearColor : neutralColor)
    plotBar(
        value=fvgSize,
        colors=[transparency(histColor, 60)],
        width=1,
        label=["FVG Size"],
        desc=["Total active Fair Value Gap size in price units. Sum of all unfilled gaps."]
    )
}

// ------------------------------------------------------------------------------
// 9. PLOTS: FORMATION MARKERS (plotShape)
// ------------------------------------------------------------------------------
if (showFormationMarkers) {
    if (bullFormEvent1 || bullFormEvent2 || bullFormEvent3 || bullFormEvent4 || bullFormEvent5) {
        plotShape(
            value=high,
            shape="triangleup",
            colorIndex=formationColor,
            width=4,
            label=["Bull FVG Formed"],
            desc=["Bullish Fair Value Gap formed: three-candle imbalance. low[0] > high[2]."]
        )
    }
    if (bearFormEvent1 || bearFormEvent2 || bearFormEvent3 || bearFormEvent4 || bearFormEvent5) {
        plotShape(
            value=low,
            shape="triangledown",
            colorIndex=formationColor,
            width=4,
            label=["Bear FVG Formed"],
            desc=["Bearish Fair Value Gap formed: three-candle imbalance. high[0] < low[2]."]
        )
    }
}

// ------------------------------------------------------------------------------
// 10. PLOTS: MITIGATION MARKERS (plotShape)
// ------------------------------------------------------------------------------
if (showMitigationMarkers) {
    if (bullFillEvent1 || bullFillEvent2 || bullFillEvent3 || bullFillEvent4 || bullFillEvent5) {
        plotShape(
            value=high,
            shape="xcross",
            colorIndex=fvgBullWeakColor,
            width=3,
            label=["Bull FVG Filled"],
            desc=["Bullish Fair Value Gap filled: price returned to the imbalance zone."]
        )
    }
    if (bearFillEvent1 || bearFillEvent2 || bearFillEvent3 || bearFillEvent4 || bearFillEvent5) {
        plotShape(
            value=low,
            shape="xcross",
            colorIndex=fvgBearWeakColor,
            width=3,
            label=["Bear FVG Filled"],
            desc=["Bearish Fair Value Gap filled: price returned to the imbalance zone."]
        )
    }
}

// ------------------------------------------------------------------------------
// 11. ACTIVE FVG COUNT LABEL (last bar only)
// ------------------------------------------------------------------------------
if (showActiveCount && isLastBar) {
    var totalActive = activeBullCount + activeBearCount
    var labelText = "Active FVGs: " + totalActive + " (Bull:" + activeBullCount + " Bear:" + activeBearCount + ")"
    var labelColor = activeBullCount > activeBearCount ? fvgBullColor : (activeBearCount > activeBullCount ? fvgBearColor : neutralColor)
    plotPriceLabel(
        price=high,
        text=labelText,
        type="callout",
        color="#ffffff",
        backgroundColor=labelColor,
        size=9,
        fontWeight=700
    )
}

// ------------------------------------------------------------------------------
// 12. REGIME TABLE (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var totalActive = activeBullCount + activeBearCount
    var totalMitigated = 0
    if (fvgBullMitigated1 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBullMitigated2 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBullMitigated3 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBullMitigated4 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBullMitigated5 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBearMitigated1 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBearMitigated2 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBearMitigated3 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBearMitigated4 == 1) { totalMitigated = totalMitigated + 1 }
    if (fvgBearMitigated5 == 1) { totalMitigated = totalMitigated + 1 }

    plotTable(
        data=[
            ["FVG Haste • Perfected", "Active: " + totalActive],
            ["Bullish FVGs", activeBullCount],
            ["Bearish FVGs", activeBearCount],
            ["Mitigated Total", totalMitigated],
            ["Total FVG Size", fvgSize],
            ["Gap Threshold %", gapThreshold * 100]
        ],
        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
    )
}