Perfected FlowScript
(SMC FVG) Fair Value Gaps
(SMC FVG) Fair Value Gaps — Production Edition is indexed as 127_smc_fvg_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
16.4 KB
Lines
505
Native Signal Candidates
7 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull FVG Formed
line 404:5
Trigger
(showLabels && isNewBullFVG)
Value
fvgBullBot
Deps
isNewBullFVG:var, showLabels:input
Bear FVG Formed
line 414:5
Trigger
(showLabels && isNewBearFVG)
Value
fvgBearTop
Deps
isNewBearFVG:var, showLabels:input
Bull FVG Mitigated
line 426:5
Trigger
(showMitigation && isBullMitigated)
Value
fvgBullBot
Deps
isBullMitigated:var, showMitigation:input
Bear FVG Mitigated
line 436:5
Trigger
(showMitigation && isBearMitigated)
Value
fvgBearTop
Deps
isBearMitigated:var, showMitigation:input
Bull FVG Filled
line 448:5
Trigger
(showFillMarkers && isBullFilled)
Value
fvgBullBot
Deps
isBullFilled:var, showFillMarkers:input
Bear FVG Filled
line 458:5
Trigger
(showFillMarkers && isBearFilled)
Value
fvgBearTop
Deps
isBearFilled:var, showFillMarkers:input
Unlabeled shape
line 495:5
Trigger
(isLastBar)
Value
h
Deps
isLastBar:builtin
127_smc_fvg_fair_value_gaps.flowscript
source path: kscripts/perfected/127_smc_fvg_fair_value_gaps.flowscript · sha256:533925c1621d854c5a09675e42e1b22401791aa227d4aef9a421f20937678045
//@version=2
// ============================================================================
// (SMC FVG) Fair Value Gaps — Smart Money Concepts Inefficiency Detection
// Author: Alien_Algorithms (@Alien_Algorithms) — Perfected Edition
// Tags: CORE, ADVANCED, #fvg, #fairvaluegaps, #smc, #gaps, #marketstructure
//
// Production-grade Fair Value Gap detector with three-candle imbalance pattern
// confirmation, box drawing with fill, forward extension, mitigation tracking,
// partial fill detection, ATR-based minimum size filtering, and multi-gap state
// management via static tracking.
//
// Academic foundations:
// - Pecchiari (2020), "Orderflow Imbalance and High Frequency Trading" (LUISS
// Thesis). OFI_t = γ₀ + γ₁·|ΔBid_t| + γ₂·|ΔAsk_t| + γ₃·Vol_t + u_t. FVGs
// manifest as order-flow imbalance signatures where aggressive one-sided
// pressure creates non-overlapping candles. Formula: imbalance = (buy vol −
// sell vol) / total vol; |imbalance| > 0.6 creates detectable gap patterns.
// - Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey" (J. Financial
// Markets, 699+ citations). Framework: latent demands D(p) → realized prices
// via λ·ΣX_i where λ = price impact coefficient. FVGs are temporary price-
// discovery inefficiencies where latent demand is not fully reflected.
// - Bhusal (2025), "Timing the Trap: Stop Hunt Zones & Price Manipulation"
// (SSRN 5276088). Documents engineered liquidity traps and inducement phases;
// validates that FVGs are institutional-engineered inefficiencies that price
// later returns to "fill" — a core SMC concept.
// - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events" (J.
// Financial Econometrics 12(1), 47–88). ΔP ≈ OFI / Depth. Deeper books absorb
// imbalance with smaller gaps; shallow books create larger FVGs. The ATR-based
// minimum size filter operationalizes this finding.
// - Hasbrouck (1991), "Measuring the Information Content of Stock Trades" (J.
// Finance 46(1), 179–207). Trade informativeness = permanent price impact /
// total price impact. FVGs represent high-informativeness trades where the
// permanent component dominates, leaving an unfilled gap.
// ============================================================================
define(
title="(SMC FVG) Fair Value Gaps — Production Edition",
position="onchart",
axis=false
)
// === USER INPUTS ===
// --- FVG Detection ---
var fvgMode = input(
name="fvgMode",
type="select",
defaultValue="Both",
label="Display Mode",
options=["Active", "Filled", "Both"],
group="FVG Detection"
)
var useMinSize = input(
name="useMinSize",
type="boolean",
defaultValue=true,
label="Use Minimum Size Filter",
group="FVG Detection"
)
var minSizeMult = input(
name="minSizeMult",
type="number",
defaultValue=0.5,
label="Min Size (ATR Multiple)",
constraints={min: 0.0, max: 5.0, step: 0.1},
group="FVG Detection"
)
var atrLen = input(
name="atrLen",
type="number",
defaultValue=14,
label="ATR Length",
constraints={min: 5, max: 100, step: 1},
group="FVG Detection"
)
// --- Display ---
var showFVGZones = input(
name="showFVGZones",
type="boolean",
defaultValue=true,
label="Show FVG Zones (Boxes)",
group="Display"
)
var showLabels = input(
name="showLabels",
type="boolean",
defaultValue=true,
label="Show Formation Labels",
group="Display"
)
var showMitigation = input(
name="showMitigation",
type="boolean",
defaultValue=true,
label="Show Mitigation Markers",
group="Display"
)
var showFillMarkers = input(
name="showFillMarkers",
type="boolean",
defaultValue=true,
label="Show Fill Event Markers",
group="Display"
)
var extendLines = input(
name="extendLines",
type="boolean",
defaultValue=true,
label="Extend FVG Lines Forward",
group="Display"
)
var maxExtension = input(
name="maxExtension",
type="number",
defaultValue=50,
label="Max Extension (bars)",
constraints={min: 10, max: 500, step: 10},
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 bullMitigatedColor = input(
name="bullMitigatedColor",
type="color",
defaultValue="#4db6ac",
label="Bullish Mitigated Color",
group="Colors"
)
var bearMitigatedColor = input(
name="bearMitigatedColor",
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"
)
// === DATA SOURCES ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries h = bars.high
timeseries l = bars.low
timeseries c = bars.close
// isnan guard on first use of external data — prevents NaN propagation on startup
if (isnan(c[0]) || isnan(h[0]) || isnan(l[0])) {
return
}
// === COMPUTATION ===
// ATR (Wilder) for minimum size filtering — shallow books create larger gaps
// per Cont, Kukanov & Stoikov (2014).
timeseries prevClose = isnan(c[1]) ? c : c[1]
timeseries tr1 = h - l
timeseries tr2 = math.abs(h - prevClose)
timeseries tr3 = math.abs(l - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, atrLen)
timeseries minSize = atr * minSizeMult
// Bar counter for event tracking and forward extension
static barCount = 0
if (!isLiveUpdate) {
barCount = barCount + 1
}
// === FVG DETECTION (3-candle pattern) ===
// Bullish FVG: low[0] > high[2] (gap between candle 1's high and candle 3's low)
// Bearish FVG: high[0] < low[2] (gap between candle 1's low and candle 3's high)
// This is the three-candle imbalance pattern per Pecchiari (2020) and ICT SMC.
// Guard against isnan on historical references before detection
timeseries bullGapSize = (!isnan(h[2]) && l > h[2]) ? (l - h[2]) : 0.0
timeseries bearGapSize = (!isnan(l[2]) && h < l[2]) ? (l[2] - h) : 0.0
var bullishFVG = !isnan(h[2]) && l > h[2] && (!useMinSize || bullGapSize >= minSize)
var bearishFVG = !isnan(l[2]) && h < l[2] && (!useMinSize || bearGapSize >= minSize)
// === STATIC STATE: FVG Tracking ===
// We track the latest active FVG for each direction with full state:
// top/bottom boundaries, formation bar, mitigation status, fill status,
// and extension counter.
// Bullish FVG state
static fvgBullTop = 0.0
static fvgBullBot = 0.0
static fvgBullBar = 0
static fvgBullActive = 0
static fvgBullMitigated = 0
static fvgBullFilled = 0
static fvgBullExtCount = 0
// Bearish FVG state
static fvgBearTop = 0.0
static fvgBearBot = 0.0
static fvgBearBar = 0
static fvgBearActive = 0
static fvgBearMitigated = 0
static fvgBearFilled = 0
static fvgBearExtCount = 0
// Event flags for plotting (set on bar close only)
static newBullFVG = 0
static newBearFVG = 0
static bullMitigatedEvent = 0
static bearMitigatedEvent = 0
static bullFilledEvent = 0
static bearFilledEvent = 0
if (!isLiveUpdate) {
// Reset event flags each bar
newBullFVG = 0
newBearFVG = 0
bullMitigatedEvent = 0
bearMitigatedEvent = 0
bullFilledEvent = 0
bearFilledEvent = 0
// FVG detection and state update on bar close
if (bullishFVG) {
// New bullish FVG detected
fvgBullTop = l
fvgBullBot = h[2]
fvgBullBar = barCount
fvgBullActive = 1
fvgBullMitigated = 0
fvgBullFilled = 0
fvgBullExtCount = 0
newBullFVG = 1
}
if (bearishFVG) {
// New bearish FVG detected
fvgBearTop = l[2]
fvgBearBot = h
fvgBearBar = barCount
fvgBearActive = 1
fvgBearMitigated = 0
fvgBearFilled = 0
fvgBearExtCount = 0
newBearFVG = 1
}
// Mitigation: price returns to the FVG zone (touches or enters)
// Per Bhusal (2025) stop-hunt zone logic — partial return to engineered inefficiency
if (fvgBullActive == 1 && fvgBullFilled == 0) {
if (h >= fvgBullBot && l <= fvgBullTop) {
// Price entered the bullish FVG zone
if (fvgBullMitigated == 0) {
fvgBullMitigated = 1
bullMitigatedEvent = 1
}
}
}
if (fvgBearActive == 1 && fvgBearFilled == 0) {
if (l <= fvgBearTop && h >= fvgBearBot) {
// Price entered the bearish FVG zone
if (fvgBearMitigated == 0) {
fvgBearMitigated = 1
bearMitigatedEvent = 1
}
}
}
// Fill detection: price fully closes the gap
// Bullish FVG filled when low <= bottom boundary
if (fvgBullActive == 1 && fvgBullFilled == 0) {
if (l <= fvgBullBot) {
fvgBullFilled = 1
fvgBullActive = 0
bullFilledEvent = 1
}
}
// Bearish FVG filled when high >= top boundary
if (fvgBearActive == 1 && fvgBearFilled == 0) {
if (h >= fvgBearTop) {
fvgBearFilled = 1
fvgBearActive = 0
bearFilledEvent = 1
}
}
// Extension counter for forward line drawing
if (fvgBullActive == 1 && fvgBullExtCount < maxExtension) {
fvgBullExtCount = fvgBullExtCount + 1
}
if (fvgBearActive == 1 && fvgBearExtCount < maxExtension) {
fvgBearExtCount = fvgBearExtCount + 1
}
}
// === CURRENT BAR EVENT FLAGS ===
var isNewBullFVG = newBullFVG == 1
var isNewBearFVG = newBearFVG == 1
var isBullMitigated = bullMitigatedEvent == 1
var isBearMitigated = bearMitigatedEvent == 1
var isBullFilled = bullFilledEvent == 1
var isBearFilled = bearFilledEvent == 1
// Color determination based on state: active, mitigated, filled
var bullTopColor = fvgBullFilled == 1 ? filledColor : (fvgBullMitigated == 1 ? bullMitigatedColor : bullColor)
var bullBotColor = fvgBullFilled == 1 ? filledColor : (fvgBullMitigated == 1 ? bullMitigatedColor : bullColor)
var bearTopColor = fvgBearFilled == 1 ? filledColor : (fvgBearMitigated == 1 ? bearMitigatedColor : bearColor)
var bearBotColor = fvgBearFilled == 1 ? filledColor : (fvgBearMitigated == 1 ? bearMitigatedColor : bearColor)
// Fill opacity: active = 50%, mitigated = 35%, filled = 20%
var bullFillOpacity = fvgBullFilled == 1 ? opacity(filledColor, 20) : (fvgBullMitigated == 1 ? opacity(bullMitigatedColor, 35) : opacity(bullColor, 50))
var bearFillOpacity = fvgBearFilled == 1 ? opacity(filledColor, 20) : (fvgBearMitigated == 1 ? opacity(bearMitigatedColor, 35) : opacity(bearColor, 50))
// === PLOTS: BULLISH FVG ZONES (plotLine with fill) ===
// Display logic based on mode: Active, Filled, or Both
var showBullActive = (fvgMode == "Active" || fvgMode == "Both") && fvgBullActive == 1
var showBullFilled = (fvgMode == "Filled" || fvgMode == "Both") && fvgBullFilled == 1
if (showFVGZones && (showBullActive || showBullFilled)) {
// Box drawing: top and bottom boundaries as filled plotLine
plotLine(
value=[fvgBullTop, fvgBullBot],
width=1,
colors=[bullTopColor, bullBotColor],
fill=bullFillOpacity,
label=["Bull FVG Zone", "Bull FVG Zone"],
desc=[
"Bullish Fair Value Gap top: low[0] > high[2]. Three-candle imbalance. Unfilled demand inefficiency per Pecchiari (2020).",
"Bullish FVG bottom: high[2]. Price later returns to fill this gap."
]
)
// Explicit boundary lines for clarity
if (extendLines) {
plotLine(
value=fvgBullTop,
width=1,
colors=[bullTopColor],
label=["Bull FVG Top"],
desc=["Bullish FVG top boundary. Extended forward until filled or max bars reached."]
)
plotLine(
value=fvgBullBot,
width=1,
colors=[bullBotColor],
label=["Bull FVG Bot"],
desc=["Bullish FVG bottom boundary. Extended forward until filled or max bars reached."]
)
}
}
// === PLOTS: BEARISH FVG ZONES (plotLine with fill) ===
var showBearActive = (fvgMode == "Active" || fvgMode == "Both") && fvgBearActive == 1
var showBearFilled = (fvgMode == "Filled" || fvgMode == "Both") && fvgBearFilled == 1
if (showFVGZones && (showBearActive || showBearFilled)) {
plotLine(
value=[fvgBearTop, fvgBearBot],
width=1,
colors=[bearTopColor, bearBotColor],
fill=bearFillOpacity,
label=["Bear FVG Zone", "Bear FVG Zone"],
desc=[
"Bearish Fair Value Gap top: low[2]. Three-candle imbalance. Unfilled supply inefficiency per Biais et al. (2005).",
"Bearish FVG bottom: high[0] < low[2]. Price later returns to fill this gap."
]
)
if (extendLines) {
plotLine(
value=fvgBearTop,
width=1,
colors=[bearTopColor],
label=["Bear FVG Top"],
desc=["Bearish FVG top boundary. Extended forward until filled or max bars reached."]
)
plotLine(
value=fvgBearBot,
width=1,
colors=[bearBotColor],
label=["Bear FVG Bot"],
desc=["Bearish FVG bottom boundary. Extended forward until filled or max bars reached."]
)
}
}
// === PLOTS: FORMATION LABELS (plotShape) ===
if (showLabels && isNewBullFVG) {
plotShape(
value=fvgBullBot,
shape="diamond",
colorIndex=bullColor,
width=3,
label=["Bull FVG Formed"],
desc=["Bullish Fair Value Gap formed: low[0] > high[2]. Three-candle demand imbalance."]
)
}
if (showLabels && isNewBearFVG) {
plotShape(
value=fvgBearTop,
shape="diamond",
colorIndex=bearColor,
width=3,
label=["Bear FVG Formed"],
desc=["Bearish Fair Value Gap formed: high[0] < low[2]. Three-candle supply imbalance."]
)
}
// === PLOTS: MITIGATION MARKERS (plotShape) ===
if (showMitigation && isBullMitigated) {
plotShape(
value=fvgBullBot,
shape="rectangle",
colorIndex=bullMitigatedColor,
width=3,
label=["Bull FVG Mitigated"],
desc=["Price returned to bullish FVG zone. Partial fill — demand zone tested. Per Bhusal (2025) stop-hunt logic."]
)
}
if (showMitigation && isBearMitigated) {
plotShape(
value=fvgBearTop,
shape="rectangle",
colorIndex=bearMitigatedColor,
width=3,
label=["Bear FVG Mitigated"],
desc=["Price returned to bearish FVG zone. Partial fill — supply zone tested. Per Bhusal (2025) stop-hunt logic."]
)
}
// === PLOTS: FILL EVENT MARKERS (plotShape) ===
if (showFillMarkers && isBullFilled) {
plotShape(
value=fvgBullBot,
shape="cross",
colorIndex=filledColor,
width=4,
label=["Bull FVG Filled"],
desc=["Bullish FVG fully filled: price closed below the gap bottom. Inefficiency resolved."]
)
}
if (showFillMarkers && isBearFilled) {
plotShape(
value=fvgBearTop,
shape="cross",
colorIndex=filledColor,
width=4,
label=["Bear FVG Filled"],
desc=["Bearish FVG fully filled: price closed above the gap top. Inefficiency resolved."]
)
}
// === FVG SIZE INDICATOR (plotBar — offchart mini-histogram) ===
// Shows the size of the most recently formed FVG as a histogram
var fvgSize = 0.0
if (fvgBullActive == 1) {
fvgSize = fvgBullTop - fvgBullBot
} else if (fvgBearActive == 1) {
fvgSize = fvgBearTop - fvgBearBot
}
if (fvgSize > 0) {
var sizeColor = fvgBullActive == 1 ? bullColor : bearColor
plotBar(
value=fvgSize,
colors=[sizeColor],
width=1,
label=["FVG Size"],
desc=["Current active FVG size in price units. Larger gaps = stronger imbalance per Cont et al. (2014)."]
)
}
// === ACTIVE FVG COUNT LABEL (plotPriceLabel) ===
if (isLastBar) {
var activeCount = (fvgBullActive == 1 ? 1 : 0) + (fvgBearActive == 1 ? 1 : 0)
var statusText = "FVGs: " + (fvgBullActive == 1 ? "Bull" : "") + (fvgBullActive == 1 && fvgBearActive == 1 ? " + " : "") + (fvgBearActive == 1 ? "Bear" : "")
if (activeCount == 0) {
statusText = "No Active FVGs"
}
plotPriceLabel(
price=h,
text=statusText,
type="callout",
color="#ffffff",
backgroundColor=activeCount > 0 ? (fvgBullActive == 1 ? bullColor : bearColor) : filledColor,
size=9,
fontWeight=700
)
}