MM Flow
FlowScripts

Perfected FlowScript

Fair Value Gaps

Fair Value Gaps — Three-Candle Imbalance with Mitigation is indexed as 034_fair_value_gaps.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

13.6 KB

Lines

332

Native Signal Candidates

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

5/5 guarded

Bull FVG Formed

line 265:5

Trigger

(showFVGShapes && bullFVGFormed)

Value

fvgBullTop

Deps

bullFVGFormed:var, showFVGShapes:input

Bear FVG Formed

line 275:5

Trigger

(showFVGShapes && bearFVGFormed)

Value

fvgBearBot

Deps

bearFVGFormed:var, showFVGShapes:input

Bull FVG Mitigated

line 288:9

Trigger

(showMitigation && fvgBullActive == 1 && fvgBullMitigated == 1 && fvgBullBar != barCount) && (lo <= fvgBullBot)

Value

fvgBullBot

Deps

barCount:static, fvgBullActive:static, fvgBullBar:static, fvgBullBot:static, fvgBullMitigated:static, lo:timeseries, showMitigation:input

Bear FVG Mitigated

line 300:9

Trigger

(showMitigation && fvgBearActive == 1 && fvgBearMitigated == 1 && fvgBearBar != barCount) && (hi >= fvgBearTop)

Value

fvgBearTop

Deps

barCount:static, fvgBearActive:static, fvgBearBar:static, fvgBearMitigated:static, fvgBearTop:static, hi:timeseries, showMitigation:input

FVG Confluence

line 323:5

Trigger

(showConfluence && bullBearConfluence)

Value

cl

Deps

bullBearConfluence:var, showConfluence:input

034_fair_value_gaps.flowscript

source path: kscripts/perfected/034_fair_value_gaps.flowscript · sha256:e14d53e7b7a789f39124724e09ee9f09a272095fe4d720323adc737aaa6b3665

hash verified
//@version=2
// ============================================================================
// Fair Value Gaps — Three-Candle Imbalance with Mitigation & Confluence
// Author: BackQuant (@BackQuant) — Perfected Edition
// Tags: CORE, #fvg, #scalping, #trading, #smc, #imbalance, #mitigation
//
// Production-grade FVG detector with three-candle pattern recognition,
// box drawing with forward extension, fill areas, mitigation tracking
// (price returning to close the gap), confluence detection, and
// ATR-scaled minimum gap size filtering.
//
// 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 flow overwhelms one side of the book.
//
//  - Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey"
//    (J. Financial Markets, 699+ citations). Framework: latent demands
//    D(p) → realized prices/volumes via λ·ΣX_i. Explains FVGs as price-
//    discovery inefficiencies when aggressive flow absorbs available liquidity.
//
//  - Smart Money Pros (2024), "What is a Fair Value Gap/Imbalance?"
//    Three-candle pattern formalization: bullish FVG = low[0] > high[2];
//    bearish FVG = high[0] < low[2]. Markets seek to "fill" gaps.
//
//  - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
//    Events" (J. Financial Econometrics, 12(1)). Linear price-impact model:
//    Δp ≈ λ·OFI; FVG size proportional to orderflow imbalance magnitude.
//    DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  - Bhusal (2025), "Timing the Trap: Stop Hunt Zones & Price Manipulation"
//    (SSRN 5276088). Documents engineered liquidity traps; FVGs near
//    stop-hunt zones have higher probability of acting as reversal magnets.
// ============================================================================

define(title="Fair Value Gaps — Three-Candle Imbalance with Mitigation", position="onchart", axis=false)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- FVG Detection --
var extendBars = input(name="extendBars", type="number", defaultValue=50, label="Forward Extension (bars)", constraints={min: 10, max: 200, step: 5}, group="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 atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length (for min size filter)", constraints={min: 5, max: 100, step: 1}, group="FVG Detection")
var useATRFilter = input(name="useATRFilter", type="boolean", defaultValue=false, label="Use ATR-Based Min Size", group="FVG Detection")
var atrMult = input(name="atrMult", type="number", defaultValue=0.2, label="ATR Multiple for Min Size", constraints={min: 0.0, max: 2.0, step: 0.1}, group="FVG Detection")

// -- Display --
var showBull = input(name="showBull", type="boolean", defaultValue=true, label="Show Bull FVGs", group="Display")
var showBear = input(name="showBear", type="boolean", defaultValue=true, label="Show Bear FVGs", group="Display")
var showMitigation = input(name="showMitigation", type="boolean", defaultValue=true, label="Show Mitigation Markers", group="Display")
var showFVGShapes = input(name="showFVGShapes", type="boolean", defaultValue=true, label="Show FVG Formation Shapes", group="Display")
var showConfluence = input(name="showConfluence", type="boolean", defaultValue=true, label="Show Confluence Zones", group="Display")
var showFVGStats = input(name="showFVGStats", type="boolean", defaultValue=true, label="Show FVG Size Histogram", group="Display")

// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bull FVG Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bear FVG Color", group="Colors")
var bullWeakColor = input(name="bullWeakColor", type="color", defaultValue="#4db6ac", label="Bull FVG Mitigated Color", group="Colors")
var bearWeakColor = input(name="bearWeakColor", type="color", defaultValue="#ef9a9a", label="Bear FVG Mitigated Color", group="Colors")
var fillOpacity = input(name="fillOpacity", type="number", defaultValue=30, label="Fill Opacity (%)", constraints={min: 5, max: 80, step: 5}, group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries hi = bars.high
timeseries lo = bars.low
timeseries op = bars.open
timeseries cl = bars.close

// Guard: halt until OHLCV has loaded to avoid NaN propagation on startup
if (isnan(cl[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(op[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 ATR for minimum gap size filtering --
// True Range = max(high - low, |high - close[1]|, |low - close[1]|)
timeseries prevClose = isnan(cl[1]) ? cl : cl[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, atrLen)
timeseries minGapSize = useATRFilter ? atr * atrMult : fvgMinSize

// -- 3.2 Bar counter for event tracking and right-extension --
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// -- 3.3 Three-candle FVG pattern detection --
// Bullish FVG: low of current bar > high of bar 2 bars ago (low[0] > high[2])
//   → gap zone = high[2] to low[0] (unfilled demand below current price)
// Bearish FVG: high of current bar < low of bar 2 bars ago (high[0] < low[2])
//   → gap zone = low[2] to high[0] (unfilled supply above current price)
//
// The gap must persist: if price later returns to the zone, it is "mitigated".

var bullishFVG = !isnan(hi[2]) && lo > hi[2] && (lo - hi[2]) >= minGapSize
var bearishFVG = !isnan(lo[2]) && hi < lo[2] && (lo[2] - hi) >= minGapSize

// -- 3.4 STATIC STATE: Bullish FVG tracking --
// Track up to one active bullish FVG at a time (most recent).
// On a new FVG formation, store the zone boundaries and formation bar.
static fvgBullTop = 0.0
static fvgBullBot = 0.0
static fvgBullBar = 0
static fvgBullActive = 0
static fvgBullMitigated = 0
static fvgBullAge = 0

// -- 3.5 STATIC STATE: Bearish FVG tracking --
static fvgBearTop = 0.0
static fvgBearBot = 0.0
static fvgBearBar = 0
static fvgBearActive = 0
static fvgBearMitigated = 0
static fvgBearAge = 0

// -- 3.6 STATE UPDATE (only on bar close) --
if (!isLiveUpdate) {
    // Increment age of active FVGs
    if (fvgBullActive == 1) {
        fvgBullAge = fvgBullAge + 1
    }
    if (fvgBearActive == 1) {
        fvgBearAge = fvgBearAge + 1
    }

    // Bullish FVG formation: new gap detected
    if (bullishFVG) {
        fvgBullTop = lo
        fvgBullBot = hi[2]
        fvgBullBar = barCount
        fvgBullActive = 1
        fvgBullMitigated = 0
        fvgBullAge = 0
    }

    // Bearish FVG formation: new gap detected
    if (bearishFVG) {
        fvgBearTop = lo[2]
        fvgBearBot = hi
        fvgBearBar = barCount
        fvgBearActive = 1
        fvgBearMitigated = 0
        fvgBearAge = 0
    }

    // Mitigation detection: price returns to fill the gap
    // Bullish FVG mitigated when low <= bottom of gap (hi[2] at formation)
    if (fvgBullActive == 1 && fvgBullMitigated == 0) {
        if (lo <= fvgBullBot) {
            fvgBullMitigated = 1
        }
    }

    // Bearish FVG mitigated when high >= top of gap (lo[2] at formation)
    if (fvgBearActive == 1 && fvgBearMitigated == 0) {
        if (hi >= fvgBearTop) {
            fvgBearMitigated = 1
        }
    }

    // Extension expiry: deactivate FVGs that have extended beyond max bars
    if (fvgBullActive == 1 && fvgBullAge > extendBars) {
        fvgBullActive = 0
    }
    if (fvgBearActive == 1 && fvgBearAge > extendBars) {
        fvgBearActive = 0
    }
}

// -- 3.7 FVG size for plotBar histogram --
timeseries fvgBullSize = (fvgBullActive == 1) ? (fvgBullTop - fvgBullBot) : 0
timeseries fvgBearSize = (fvgBearActive == 1) ? (fvgBearTop - fvgBearBot) : 0

// -- 3.8 Confluence detection: multiple FVGs or FVG near recent swing --
// A confluence zone exists when both bull and bear FVGs are active simultaneously
// (rare but indicates high volatility / imbalance) or when an FVG forms near
// a recent price swing (within ATR distance).
var bullBearConfluence = fvgBullActive == 1 && fvgBearActive == 1

// -- 3.9 Event flags for plotting --
var bullFVGFormed = bullishFVG && fvgBullBar == barCount
var bearFVGFormed = bearishFVG && fvgBearBar == barCount

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — FVG zones as filled boxes, shapes, and histograms
// ---------------------------------------------------------------------------

// 4.1 Bullish FVG zone (plotLine with fill — box drawing)
if (showBull && fvgBullActive == 1) {
    var bullFillColor = fvgBullMitigated == 1 ? opacity(bullWeakColor, fillOpacity) : opacity(bullColor, fillOpacity)
    var bullLineColor = fvgBullMitigated == 1 ? bullWeakColor : bullColor

    // Filled box: top and bottom boundaries
    plotLine(
        value=[fvgBullTop, fvgBullBot],
        width=1,
        colors=[bullLineColor, bullLineColor],
        fill=bullFillColor,
        label=["Bull FVG", "Bull FVG"],
        desc=["Bullish Fair Value Gap: low[0] > high[2]. Unfilled demand imbalance zone.", "Bullish FVG bottom boundary."]
    )

    // Explicit boundary lines for clarity
    plotLine(
        value=fvgBullTop,
        width=1,
        colors=[bullLineColor],
        label=["Bull FVG Top"],
        desc=["Top boundary of bullish FVG zone."]
    )
    plotLine(
        value=fvgBullBot,
        width=1,
        colors=[bullLineColor],
        label=["Bull FVG Bot"],
        desc=["Bottom boundary of bullish FVG zone. Mitigated when price touches."]
    )
}

// 4.2 Bearish FVG zone (plotLine with fill — box drawing)
if (showBear && fvgBearActive == 1) {
    var bearFillColor = fvgBearMitigated == 1 ? opacity(bearWeakColor, fillOpacity) : opacity(bearColor, fillOpacity)
    var bearLineColor = fvgBearMitigated == 1 ? bearWeakColor : bearColor

    plotLine(
        value=[fvgBearTop, fvgBearBot],
        width=1,
        colors=[bearLineColor, bearLineColor],
        fill=bearFillColor,
        label=["Bear FVG", "Bear FVG"],
        desc=["Bearish Fair Value Gap: high[0] < low[2]. Unfilled supply imbalance zone.", "Bearish FVG bottom boundary."]
    )

    plotLine(
        value=fvgBearTop,
        width=1,
        colors=[bearLineColor],
        label=["Bear FVG Top"],
        desc=["Top boundary of bearish FVG zone. Mitigated when price touches."]
    )
    plotLine(
        value=fvgBearBot,
        width=1,
        colors=[bearLineColor],
        label=["Bear FVG Bot"],
        desc=["Bottom boundary of bearish FVG zone."]
    )
}

// 4.3 FVG formation shape markers (plotShape)
if (showFVGShapes && bullFVGFormed) {
    plotShape(
        value=fvgBullTop,
        shape="triangleup",
        colorIndex=bullColor,
        width=4,
        label=["Bull FVG Formed"],
        desc=["Bullish Fair Value Gap formed: low[0] > high[2]. Three-candle imbalance pattern."]
    )
}
if (showFVGShapes && bearFVGFormed) {
    plotShape(
        value=fvgBearBot,
        shape="triangledown",
        colorIndex=bearColor,
        width=4,
        label=["Bear FVG Formed"],
        desc=["Bearish Fair Value Gap formed: high[0] < low[2]. Three-candle imbalance pattern."]
    )
}

// 4.4 Mitigation markers (plotShape) — price returned to fill the gap
if (showMitigation && fvgBullActive == 1 && fvgBullMitigated == 1 && fvgBullBar != barCount) {
    if (lo <= fvgBullBot) {
        plotShape(
            value=fvgBullBot,
            shape="rectangle",
            colorIndex=bullWeakColor,
            width=3,
            label=["Bull FVG Mitigated"],
            desc=["Price returned to bullish FVG zone and filled the gap. Imbalance resolved."]
        )
    }
}
if (showMitigation && fvgBearActive == 1 && fvgBearMitigated == 1 && fvgBearBar != barCount) {
    if (hi >= fvgBearTop) {
        plotShape(
            value=fvgBearTop,
            shape="rectangle",
            colorIndex=bearWeakColor,
            width=3,
            label=["Bear FVG Mitigated"],
            desc=["Price returned to bearish FVG zone and filled the gap. Imbalance resolved."]
        )
    }
}

// 4.5 FVG size histogram (plotBar) — tracks active gap sizes over time
if (showFVGStats) {
    if (fvgBullSize > 0) {
        plotBar(value=fvgBullSize, colors=[bullColor], label=["Bull FVG Size"], desc=["Bullish FVG size in price units."])
    }
    if (fvgBearSize > 0) {
        plotBar(value=fvgBearSize, colors=[bearColor], label=["Bear FVG Size"], desc=["Bearish FVG size in price units."])
    }
}

// 4.6 Confluence marker (plotShape) — both bull and bear FVGs active
if (showConfluence && bullBearConfluence) {
    plotShape(
        value=cl,
        shape="diamond",
        colorIndex="#ffd700",
        width=3,
        label=["FVG Confluence"],
        desc=["Both bullish and bearish FVGs active simultaneously: high volatility / imbalance regime."]
    )
}