MM Flow
FlowScripts

Perfected FlowScript

ICT Killzones + ICT HTF FVG (Merged)

ICT Killzones + HTF FVG — SMC & Market Structure is indexed as 296_ict_killzones_ict_htf_fvg_merged.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

18.6 KB

Lines

602

Native Signal Candidates

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

14/14 guarded

Asia KZ

line 372:9

Trigger

(showKZBackground) && (asianKZ && inAsian)

Value

px

Deps

asianKZ:input, inAsian:timeseries, showKZBackground:input

London KZ

line 382:9

Trigger

(showKZBackground) && (londonKZ && inLondon)

Value

px

Deps

inLondon:timeseries, londonKZ:input, showKZBackground:input

NY KZ

line 392:9

Trigger

(showKZBackground) && (nyKZ && inNY)

Value

px

Deps

inNY:timeseries, nyKZ:input, showKZBackground:input

London Close KZ

line 402:9

Trigger

(showKZBackground) && (londonCloseKZ && inLondonClose)

Value

px

Deps

inLondonClose:timeseries, londonCloseKZ:input, showKZBackground:input

Asia

line 415:5

Trigger

(asianKZ && inAsian)

Value

hi

Deps

asianKZ:input, inAsian:timeseries

London

line 425:5

Trigger

(londonKZ && inLondon)

Value

hi

Deps

inLondon:timeseries, londonKZ:input

NY

line 435:5

Trigger

(nyKZ && inNY)

Value

hi

Deps

inNY:timeseries, nyKZ:input

Bull FVG Formed

line 483:9

Trigger

(showFVG && fvgBullActive == 1) && (fvgBullBar == barCount)

Value

fvgBullTop

Deps

barCount:static, fvgBullActive:static, fvgBullBar:static, showFVG:input

Bear FVG Formed

line 505:9

Trigger

(showFVG && fvgBearActive == 1) && (fvgBearBar == barCount)

Value

fvgBearBot

Deps

barCount:static, fvgBearActive:static, fvgBearBar:static, showFVG:input

Bull BOS

line 521:9

Trigger

(showStructure) && (bullBOSEvent)

Value

lastHigh

Deps

bullBOSEvent:var, showStructure:input

Bear BOS

line 531:9

Trigger

(showStructure) && (bearBOSEvent)

Value

lastLow

Deps

bearBOSEvent:var, showStructure:input

Bull ChoCH

line 541:9

Trigger

(showStructure) && (bullChoCHEvent)

Value

lastHigh

Deps

bullChoCHEvent:var, showStructure:input

Bear ChoCH

line 551:9

Trigger

(showStructure) && (bearChoCHEvent)

Value

lastLow

Deps

bearChoCHEvent:var, showStructure:input

Unlabeled shape

line 566:5

Trigger

(isLastBar)

Value

hi

Deps

isLastBar:builtin

296_ict_killzones_ict_htf_fvg_merged.flowscript

source path: kscripts/perfected/296_ict_killzones_ict_htf_fvg_merged.flowscript · sha256:5c70ad690582336f4ea90e1cc399801884eb22740a8a6e1c8eb17321f90437e0

hash verified
//@version=2
// ============================================================================
// ICT Killzones + HTF FVG — Smart Money Concepts & Market Structure
// Author: kiyotaka (@kiyotaka) | Enhanced by kScript Perfection Engineer
// Index: 296
// Tags: CORE, #ict, #smc, #killzone, #fvg, #marketstructure, #bos, #choch
//
// Production-grade ICT killzone overlay with Higher-Timeframe Fair Value Gap
// detection, market structure tracking (BOS/ChoCH), session-based background
// coloring, and ATR-padded zone visualization with fill mitigation tracking.
//
// Academic foundations:
//  1. Harris (1986), "A Transaction Data Study of Weekly and Intradaily
//     Patterns in Stock Returns" (JFE, 16(1), 99–117). Seminal intraday
//     seasonality paper: significant weekday differences in first 45 min.
//     Supports killzone time-of-day effects. [^1]
//  2. Heston, Korajczyk & Sadka (2010), "Intra-day Patterns in the Cross-Section
//     of Stock Returns" (J. Finance, 65(4), 1369–1407). Return effects pronounced
//     in first and last half-hours; opening half-hour spread >11 bps. [^2]
//  3. Ito & Hashimoto (2006), "Intraday Seasonality in Activities of the Foreign
//     Exchange Markets" (NBER 12413). U-shaped activity patterns; London/NY
//     overlap drives largest price/volume effects. [^3]
//  4. Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
//     Order Flow and Stock Returns" (NBER 11439). ~12% R² in predicting
//     institutional ownership changes from trade patterns. [^4]
//  5. Jones & Lipson (2005), "Are Retail Orders Different?" 1,000 retail shares
//     → 400+ institutional shares opposite within 5 min. Validates smart-money
//     exploitation of retail liquidity. [^5]
//  6. Bhusal (2025), "Timing the Trap: Stop Hunt Zones & Price Manipulation"
//     (SSRN 5276088). Documents engineered liquidity traps and inducement phases;
//     validates stop-hunting as observable microstructure phenomenon. [^6]
//  7. Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey" (J.
//     Financial Markets, 699+ citations). Latent demands → realized prices via
//     λ·ΣX_i. Explains why Order Blocks and FVGs exist as price-discovery
//     inefficiencies. [^7]
//  8. Pecchiari (2020), "Orderflow Imbalance and High Frequency Trading" (LUISS
//     Thesis). Quantile regression: FVGs manifest as order-flow imbalance
//     signatures. [^8]
// ============================================================================

define(
    title="ICT Killzones + HTF FVG — SMC & Market Structure",
    position="onchart",
    axis=false
)

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

// --- Killzone Settings ---
var asianKZ = input(
    name="asianKZ",
    type="boolean",
    defaultValue=true,
    label="Show Asian Killzone",
    group="Killzones"
)
var londonKZ = input(
    name="londonKZ",
    type="boolean",
    defaultValue=true,
    label="Show London Killzone",
    group="Killzones"
)
var nyKZ = input(
    name="nyKZ",
    type="boolean",
    defaultValue=true,
    label="Show NY Killzone",
    group="Killzones"
)
var londonCloseKZ = input(
    name="londonCloseKZ",
    type="boolean",
    defaultValue=false,
    label="Show London Close Killzone",
    group="Killzones"
)
var showKZBackground = input(
    name="showKZBackground",
    type="boolean",
    defaultValue=true,
    label="Show Killzone Background",
    group="Killzones"
)

// --- FVG Settings ---
var showFVG = input(
    name="showFVG",
    type="boolean",
    defaultValue=true,
    label="Show HTF Fair Value Gaps",
    group="FVG Settings"
)
var fvgMinPct = input(
    name="fvgMinPct",
    type="number",
    defaultValue=0.15,
    label="FVG Min Size (%)",
    constraints={min: 0.01, max: 5.0, step: 0.01},
    group="FVG Settings"
)
var fvgMaxAge = input(
    name="fvgMaxAge",
    type="number",
    defaultValue=50,
    label="FVG Max Age (bars)",
    constraints={min: 10, max: 200, step: 5},
    group="FVG Settings"
)
var showFVGFill = input(
    name="showFVGFill",
    type="boolean",
    defaultValue=true,
    label="Show FVG Zone Fill",
    group="FVG Settings"
)

// --- Market Structure ---
var showStructure = input(
    name="showStructure",
    type="boolean",
    defaultValue=true,
    label="Show Market Structure (BOS/ChoCH)",
    group="Market Structure"
)
var pivotLen = input(
    name="pivotLen",
    type="number",
    defaultValue=5,
    label="Pivot Length (each side)",
    constraints={min: 2, max: 20, step: 1},
    group="Market Structure"
)
var showSwingLevels = input(
    name="showSwingLevels",
    type="boolean",
    defaultValue=true,
    label="Show Swing High/Low Lines",
    group="Market Structure"
)

// --- Colors ---
var asianColor = input(
    name="asianColor",
    type="color",
    defaultValue="#3f51b5",
    label="Asian Color",
    group="Colors"
)
var londonColor = input(
    name="londonColor",
    type="color",
    defaultValue="#9c27b0",
    label="London Color",
    group="Colors"
)
var nyColor = input(
    name="nyColor",
    type="color",
    defaultValue="#ff6d00",
    label="NY Color",
    group="Colors"
)
var londonCloseColor = input(
    name="londonCloseColor",
    type="color",
    defaultValue="#00bcd4",
    label="London Close Color",
    group="Colors"
)
var fvgBullColor = input(
    name="fvgBullColor",
    type="color",
    defaultValue="#00e676",
    label="Bull FVG Color",
    group="Colors"
)
var fvgBearColor = input(
    name="fvgBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Bear FVG Color",
    group="Colors"
)
var bosColor = input(
    name="bosColor",
    type="color",
    defaultValue="#ffd700",
    label="BOS Marker Color",
    group="Colors"
)
var chochColor = input(
    name="chochColor",
    type="color",
    defaultValue="#ff00ff",
    label="ChoCH Marker Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries op = bars.open
timeseries t = bars.time

if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(op[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. KILLZONE DETECTION (session-based time windows)
// -----------------------------------------------------------------------------
// Per ICT methodology and Harris (1986) / Heston et al. (2010) time-of-day effects.
// Asian: 00:00–05:00 UTC (consolidation / range establishment)
// London: 07:00–10:00 UTC (directional move / daily high-low formation)
// NY: 13:00–16:00 UTC (high volatility, continuation / reversal)
// London Close: 16:00–18:00 UTC (European repositioning, potential counter-trend)

timeseries hour = (t / 3600000) % 24

timeseries inAsian = hour >= 0 && hour < 5
timeseries inLondon = hour >= 7 && hour < 10
timeseries inNY = hour >= 13 && hour < 16
timeseries inLondonClose = hour >= 16 && hour < 18

// Session state (0=none, 1=Asian, 2=London, 3=NY, 4=LondonClose)
timeseries kzActive = inAsian ? 1 : (inLondon ? 2 : (inNY ? 3 : (inLondonClose ? 4 : 0)))
timeseries kzColor = inAsian ? asianColor : (inLondon ? londonColor : (inNY ? nyColor : (inLondonClose ? londonCloseColor : "transparent")))

// -----------------------------------------------------------------------------
// 4. SWING DETECTION & MARKET STRUCTURE
// -----------------------------------------------------------------------------
// Per ICT/SMC: BOS = continuation, ChoCH = reversal.
// Swing detection: pivot at [pivotLen] bars ago confirmed when current bar
// completes the right-side lookback.

var isSwingHigh = hi[pivotLen] == highest(hi, pivotLen * 2 + 1) && hi[pivotLen] > highest(hi, pivotLen)
var isSwingLow = lo[pivotLen] == lowest(lo, pivotLen * 2 + 1) && lo[pivotLen] < lowest(lo, pivotLen)

static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// Static state for market structure
static lastHigh = 0.0
static lastLow = 0.0
static prevHigh = 0.0
static prevLow = 0.0
static trend = 0  // 1 = bullish, -1 = bearish

static bullBOSBar = 0
static bearBOSBar = 0
static bullChoCHBar = 0
static bearChoCHBar = 0

if (!isLiveUpdate) {
    if (isSwingHigh) {
        if (lastHigh > 0) {
            prevHigh = lastHigh
        }
        lastHigh = hi[pivotLen]

        if (trend == 1 && prevHigh > 0 && lastHigh > prevHigh) {
            bullBOSBar = barCount
        } else if (trend == -1 && prevHigh > 0 && lastHigh > prevHigh) {
            bullChoCHBar = barCount
            trend = 1
        } else if (trend == 0) {
            trend = 1
        }
    }

    if (isSwingLow) {
        if (lastLow > 0) {
            prevLow = lastLow
        }
        lastLow = lo[pivotLen]

        if (trend == -1 && prevLow > 0 && lastLow < prevLow) {
            bearBOSBar = barCount
        } else if (trend == 1 && prevLow > 0 && lastLow < prevLow) {
            bearChoCHBar = barCount
            trend = -1
        } else if (trend == 0) {
            trend = -1
        }
    }
}

// Event flags for plotting
var bullBOSEvent = bullBOSBar == barCount
var bearBOSEvent = bearBOSBar == barCount
var bullChoCHEvent = bullChoCHBar == barCount
var bearChoCHEvent = bearChoCHBar == barCount

var regimeColor = trend == 1 ? fvgBullColor : (trend == -1 ? fvgBearColor : "#ffffff")
var regimeLabel = trend == 1 ? "BULLISH STRUCTURE" : (trend == -1 ? "BEARISH STRUCTURE" : "NEUTRAL")

// -----------------------------------------------------------------------------
// 5. HTF FAIR VALUE GAP DETECTION (stateful)
// -----------------------------------------------------------------------------
// Per Smart Money Pros (2024): FVG = three-candle imbalance pattern.
// Bullish FVG = low[0] > high[2]; Bearish FVG = high[0] < low[2].
// Markets often seek to "fill" FVGs to correct the imbalance.

var bullishFVG = !isnan(hi[2]) && lo > hi[2] && ((lo - hi[2]) / px * 100) > fvgMinPct
var bearishFVG = !isnan(lo[2]) && hi < lo[2] && ((lo[2] - hi) / px * 100) > fvgMinPct

// Static FVG tracking
static fvgBullTop = 0.0
static fvgBullBot = 0.0
static fvgBullActive = 0
static fvgBullBar = 0

static fvgBearTop = 0.0
static fvgBearBot = 0.0
static fvgBearActive = 0
static fvgBearBar = 0

if (!isLiveUpdate) {
    if (bullishFVG) {
        fvgBullTop = lo
        fvgBullBot = hi[2]
        fvgBullActive = 1
        fvgBullBar = barCount
    }
    if (bearishFVG) {
        fvgBearTop = lo[2]
        fvgBearBot = hi
        fvgBearActive = 1
        fvgBearBar = barCount
    }

    // FVG fill detection: gap is closed when price crosses into the imbalance zone
    if (fvgBullActive == 1) {
        if (lo <= fvgBullBot || barCount - fvgBullBar > fvgMaxAge) {
            fvgBullActive = 0
        }
    }
    if (fvgBearActive == 1) {
        if (hi >= fvgBearTop || barCount - fvgBearBar > fvgMaxAge) {
            fvgBearActive = 0
        }
    }
}

// FVG size for plotting
var fvgBullSize = fvgBullActive == 1 ? fvgBullTop - fvgBullBot : 0.0
var fvgBearSize = fvgBearActive == 1 ? fvgBearTop - fvgBearBot : 0.0

// -----------------------------------------------------------------------------
// 6. PLOTTING: KILLZONE BACKGROUNDS & SHAPES
// -----------------------------------------------------------------------------

// --- Killzone Background Shapes ---
if (showKZBackground) {
    if (asianKZ && inAsian) {
        plotShape(
            value=px,
            shape="rectangle",
            colorIndex=transparency(asianColor, 85),
            width=1,
            label=["Asia KZ"],
            desc=["Asian Killzone (00:00–05:00 UTC): consolidation / range establishment phase"]
        )
    }
    if (londonKZ && inLondon) {
        plotShape(
            value=px,
            shape="rectangle",
            colorIndex=transparency(londonColor, 85),
            width=1,
            label=["London KZ"],
            desc=["London Killzone (07:00–10:00 UTC): directional move, often sets daily high/low"]
        )
    }
    if (nyKZ && inNY) {
        plotShape(
            value=px,
            shape="rectangle",
            colorIndex=transparency(nyColor, 85),
            width=1,
            label=["NY KZ"],
            desc=["NY Killzone (13:00–16:00 UTC): high volatility, continuation or reversal"]
        )
    }
    if (londonCloseKZ && inLondonClose) {
        plotShape(
            value=px,
            shape="rectangle",
            colorIndex=transparency(londonCloseColor, 85),
            width=1,
            label=["London Close KZ"],
            desc=["London Close Killzone (16:00–18:00 UTC): European repositioning, counter-trend potential"]
        )
    }
}

// --- Killzone Session Labels (small shapes at bar open) ---
if (asianKZ && inAsian) {
    plotShape(
        value=hi,
        shape="circle",
        colorIndex=asianColor,
        width=1,
        label=["Asia"],
        desc=["Asian session active"]
    )
}
if (londonKZ && inLondon) {
    plotShape(
        value=hi,
        shape="circle",
        colorIndex=londonColor,
        width=1,
        label=["London"],
        desc=["London session active"]
    )
}
if (nyKZ && inNY) {
    plotShape(
        value=hi,
        shape="circle",
        colorIndex=nyColor,
        width=1,
        label=["NY"],
        desc=["New York session active"]
    )
}

// -----------------------------------------------------------------------------
// 7. PLOTTING: SWING LEVELS
// -----------------------------------------------------------------------------
if (showSwingLevels && showStructure) {
    if (lastHigh > 0) {
        plotLine(
            value=lastHigh,
            width=1,
            colors=["#ffffff40"],
            label=["Swing High"],
            desc=["Last confirmed swing high"]
        )
    }
    if (lastLow > 0) {
        plotLine(
            value=lastLow,
            width=1,
            colors=["#ffffff40"],
            label=["Swing Low"],
            desc=["Last confirmed swing low"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. PLOTTING: FVG ZONES
// -----------------------------------------------------------------------------
if (showFVG && fvgBullActive == 1) {
    var fvgBullFill = transparency(fvgBullColor, 40)
    plotLine(
        value=[fvgBullTop, fvgBullBot],
        width=1,
        colors=[fvgBullColor, fvgBullColor],
        fill=fvgBullFill,
        label=["Bull FVG", "Bull FVG"],
        desc=["Bullish Fair Value Gap: low > high[2]. Unfilled demand imbalance.", "Bullish FVG bottom boundary"]
    )
    if (fvgBullBar == barCount) {
        plotShape(
            value=fvgBullTop,
            shape="triangleup",
            colorIndex=fvgBullColor,
            width=2,
            label=["Bull FVG Formed"],
            desc=["Bullish FVG formed: three-candle demand imbalance"]
        )
    }
}

if (showFVG && fvgBearActive == 1) {
    var fvgBearFill = transparency(fvgBearColor, 40)
    plotLine(
        value=[fvgBearTop, fvgBearBot],
        width=1,
        colors=[fvgBearColor, fvgBearColor],
        fill=fvgBearFill,
        label=["Bear FVG", "Bear FVG"],
        desc=["Bearish Fair Value Gap: high < low[2]. Unfilled supply imbalance.", "Bearish FVG top boundary"]
    )
    if (fvgBearBar == barCount) {
        plotShape(
            value=fvgBearBot,
            shape="triangledown",
            colorIndex=fvgBearColor,
            width=2,
            label=["Bear FVG Formed"],
            desc=["Bearish FVG formed: three-candle supply imbalance"]
        )
    }
}

// -----------------------------------------------------------------------------
// 9. PLOTTING: MARKET STRUCTURE (BOS / ChoCH)
// -----------------------------------------------------------------------------
if (showStructure) {
    if (bullBOSEvent) {
        plotShape(
            value=lastHigh,
            shape="triangleup",
            colorIndex=bosColor,
            width=4,
            label=["Bull BOS"],
            desc=["Bullish Break of Structure: higher high in uptrend. Trend continuation."]
        )
    }
    if (bearBOSEvent) {
        plotShape(
            value=lastLow,
            shape="triangledown",
            colorIndex=bosColor,
            width=4,
            label=["Bear BOS"],
            desc=["Bearish Break of Structure: lower low in downtrend. Trend continuation."]
        )
    }
    if (bullChoCHEvent) {
        plotShape(
            value=lastHigh,
            shape="triangleup",
            colorIndex=chochColor,
            width=4,
            label=["Bull ChoCH"],
            desc=["Bullish Change of Character: higher high after lower lows. Trend reversal signal."]
        )
    }
    if (bearChoCHEvent) {
        plotShape(
            value=lastLow,
            shape="triangledown",
            colorIndex=chochColor,
            width=4,
            label=["Bear ChoCH"],
            desc=["Bearish Change of Character: lower low after higher highs. Trend reversal signal."]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. REGIME LABEL & TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    plotPriceLabel(
        price=hi,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )

    var activeKZ = inAsian ? "Asian" : (inLondon ? "London" : (inNY ? "NY" : (inLondonClose ? "London Close" : "None")))
    var activeKZColor = inAsian ? asianColor : (inLondon ? londonColor : (inNY ? nyColor : (inLondonClose ? londonCloseColor : neutralColor)))

    plotTable(
        data=[
            ["ICT Killzones + HTF FVG", regimeLabel],
            ["Active Killzone", activeKZ],
            ["Trend", trend == 1 ? "UP" : (trend == -1 ? "DOWN" : "UNDEFINED")],
            ["Bull FVG Active", fvgBullActive == 1 ? "YES" : "NO"],
            ["Bear FVG Active", fvgBearActive == 1 ? "YES" : "NO"],
            ["Last Swing High", lastHigh],
            ["Last Swing Low", lastLow]
        ],
        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
    )
}