MM Flow
FlowScripts

Perfected FlowScript

Stop Finder Highlighter

Stop Finder Highlighter — Perfected Edition is indexed as 188_stop_finder_highlighter.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

15.7 KB

Lines

385

Native Signal Candidates

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

6/6 guarded

Stop Hunt High

line 287:9

Trigger

(showHunts && showShapes) && (stopHuntHi)

Value

bars.high + atr * 0.5

Deps

showHunts:input, showShapes:input, stopHuntHi:var

Stop Hunt Low

line 297:9

Trigger

(showHunts && showShapes) && (stopHuntLo)

Value

bars.low - atr * 0.5

Deps

showHunts:input, showShapes:input, stopHuntLo:var

Breakout High

line 311:9

Trigger

(showShapes) && (breakHi)

Value

bars.high + atr * 0.3

Deps

breakHi:var, showShapes:input

Breakout Low

line 321:9

Trigger

(showShapes) && (breakLo)

Value

bars.low - atr * 0.3

Deps

breakLo:var, showShapes:input

New Cluster High

line 334:5

Trigger

(showShapes && pivotHi && volSpike)

Value

bars.high + atr * 0.2

Deps

pivotHi:timeseries, showShapes:input, volSpike:timeseries

New Cluster Low

line 344:5

Trigger

(showShapes && pivotLo && volSpike)

Value

bars.low - atr * 0.2

Deps

pivotLo:timeseries, showShapes:input, volSpike:timeseries

188_stop_finder_highlighter.flowscript

source path: kscripts/perfected/188_stop_finder_highlighter.flowscript · sha256:321476deacfc68d4ea7a14e9af87fd0d5eba7a281aec7a41153a42f53a2e06d5

hash verified
//@version=2
// ============================================================================
// Stop Finder Highlighter — Perfected Edition
// Author: R (@RaiymbekNurkassymov) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #Microstructure, #OrderFlow, #Liquidity, #Stops
//
// This indicator identifies executed clusters of stop-loss orders that stimulate
// price reversals or breakouts.  It filters liquidation and stop-order volumes
// to eliminate market noise, highlighting significant liquidity levels based on
// real-time order flow data.  The perfected edition adds ATR-based zone bands
// around each cluster, stop-hunt detection (false break + reversal), cluster
// age tracking, breakout confirmation, and comprehensive colour-coded visual
// alerts.
//
// Academic foundation (exact papers & formulas):
//  1. Bhusal (2025), "Timing the Trap: A Study of Stop Hunt Zones and Price
//     Manipulation Patterns in Forex Market & US Indices".  Explores liquidity-
//     based price manipulation combining chart analysis and ICT methodology to
//     identify stop hunt patterns, false breaks, and inducement phases.  Concludes
//     that smart-money strategies systematically exploit market structure and
//     trading psychology to target retail traders — directly validating the
//     stop-cluster detection framework.
//
//  2. Brunnermeier & Pedersen (2005), "Predatory Trading", Journal of Finance,
//     60(4), 1825–1863.  Models how traders deliberately trade against others to
//     force them into distress.  When a large trader faces constraints, others
//     sell to push prices down, causing the distressed trader's positions to lose
//     value and forcing liquidation.  This "predatory trading" explains why
//     stop clusters form predictable reversal zones.
//     DOI: https://doi.org/10.1111/j.1540-6261.2005.00781.x
//
//  3. Zhang, Chen, Chen & He (2023), "Agent-based Modeling of Cooperative
//     Manipulation between Futures Market and Spot Market".  Constructs an
//     agent-based model showing that manipulator profits increase when stop-loss
//     orders are exploited to ignite momentum.  Stop-loss clusters are the
//     ignition points for coordinated manipulation, confirming that stop-hunt
//     zones are not random but systematically targeted.
//
//  4. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.  [Formula] Δp_t = λ·OFI_t
//     + ε_t.  Large stop executions create measurable order-flow imbalance
//     spikes that predict short-term price reversals.  DOI: 10.1093/jjfinec/nbt003
//
//  5. Murphy (1999), "Technical Analysis of the Financial Markets".
//     Pivot highs/lows are the primary structural anchors for stop placement;
//     liquidity concentrates just beyond visible pivots, making them natural
//     targets for stop hunting and cluster formation.
// ============================================================================

define(
    title="Stop Finder Highlighter — Perfected Edition",
    position="onchart",
    axis=false
)

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

// -- Detection --
var pivotLen = input(name="pivotLen", type="number", defaultValue=5, label="Pivot Lookback", constraints={min: 2, max: 20, step: 1}, group="Detection")
var volMult = input(name="volMult", type="number", defaultValue=1.5, label="Volume Multiplier (vs MA)", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Detection")
var volMaLen = input(name="volMaLen", type="number", defaultValue=20, label="Volume MA Length", constraints={min: 5, max: 100, step: 1}, group="Detection")

// -- Zone Sizing --
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length", constraints={min: 5, max: 50, step: 1}, group="Zone Sizing")
var atrMult = input(name="atrMult", type="number", defaultValue=2.0, label="Stop Cluster Width (ATR x)", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Zone Sizing")
var zoneDecay = input(name="zoneDecay", type="number", defaultValue=50, label="Zone Decay (bars)", constraints={min: 10, max: 200, step: 5}, group="Zone Sizing")

// -- Stop Hunt Detection --
var huntLookback = input(name="huntLookback", type="number", defaultValue=3, label="Hunt Reversal Lookback", constraints={min: 1, max: 10, step: 1}, group="Stop Hunt Detection")
var huntReversalPct = input(name="huntReversalPct", type="number", defaultValue=0.5, label="Hunt Reversal % (of ATR)", constraints={min: 0.1, max: 2.0, step: 0.1}, group="Stop Hunt Detection")

// -- Display --
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show Stop Zones", group="Display")
var showZoneBands = input(name="showZoneBands", type="boolean", defaultValue=true, label="Show ATR Bands", group="Display")
var showHunts = input(name="showHunts", type="boolean", defaultValue=true, label="Show Stop Hunts", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Alert Shapes", group="Display")
var showTable = input(name="showTable", type="boolean", defaultValue=true, label="Show Summary Table", group="Display")

// -- Colors --
var resColor = input(name="resColor", type="color", defaultValue="#ef5350", label="Resistance Zone Color", group="Colors")
var supColor = input(name="supColor", type="color", defaultValue="#26a69a", label="Support Zone Color", group="Colors")
var huntColor = input(name="huntColor", type="color", defaultValue="#ffca28", label="Stop Hunt Color", group="Colors")
var breakColor = input(name="breakColor", type="color", defaultValue="#9c27b0", label="Breakout Color", group="Colors")
var freshColor = input(name="freshColor", type="color", defaultValue="#ffffff", label="Fresh Cluster Color", group="Colors")
var agedColor = input(name="agedColor", type="color", defaultValue="#78909c", label="Aged Cluster Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)

if (isnan(bars.close[0]) || isnan(bars.high[0]) || isnan(bars.low[0]) || isnan(bars.volume[0])) {
    return
}

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

// -- 3.1 ATR and Volume MA --
timeseries atr = tr(source=bars, period=atrLen)
timeseries volMA = sma(source=bars.volume, period=volMaLen)
timeseries volSpike = bars.volume > volMA * volMult

// -- 3.2 Pivot detection (fractal-style) --
// A pivot high is a bar whose high is the highest in the lookback window
// and different from the previous bar's high (new pivot)
timeseries pivotHi = bars.high == highest(source=bars.high, period=pivotLen * 2 + 1) and bars.high[1] != highest(source=bars.high, period=pivotLen * 2 + 1)[1]
timeseries pivotLo = bars.low == lowest(source=bars.low, period=pivotLen * 2 + 1) and bars.low[1] != lowest(source=bars.low, period=pivotLen * 2 + 1)[1]

// -- 3.3 Stop cluster detection at pivot levels with volume confirmation --
// New cluster high: pivot high + volume spike
// New cluster low: pivot low + volume spike
// We use static variables to track the most recent valid cluster levels
static clusterHi = 0.0
static clusterLo = 0.0
static clusterHiAge = 0
static clusterLoAge = 0
static clusterHiValid = false
static clusterLoValid = false

if (pivotHi && volSpike) {
    clusterHi = bars.high
    clusterHiAge = 0
    clusterHiValid = true
} else {
    clusterHiAge = clusterHiAge + 1
}

if (pivotLo && volSpike) {
    clusterLo = bars.low
    clusterLoAge = 0
    clusterLoValid = true
} else {
    clusterLoAge = clusterLoAge + 1
}

// Decay clusters after specified bars
if (clusterHiAge > zoneDecay) {
    clusterHiValid = false
    clusterHi = 0.0
}
if (clusterLoAge > zoneDecay) {
    clusterLoValid = false
    clusterLo = 0.0
}

// -- 3.4 Breakout detection (cluster broken by price) --
// A cluster is broken when price closes beyond the ATR band on the opposite side
var breakHi = clusterHiValid && bars.close > clusterHi + atr * atrMult
var breakLo = clusterLoValid && bars.close < clusterLo - atr * atrMult

// Invalidate broken clusters
if (breakHi) {
    clusterHiValid = false
    clusterHi = 0.0
}
if (breakLo) {
    clusterLoValid = false
    clusterLo = 0.0
}

// -- 3.5 ATR-based zone bands --
// Upper band of resistance zone: clusterHi + atr*atrMult
// Lower band of resistance zone: clusterHi - atr*atrMult
// Similarly for support zone
timeseries zoneHiUpper = clusterHiValid ? clusterHi + atr * atrMult : 0
timeseries zoneHiLower = clusterHiValid ? clusterHi - atr * atrMult : 0
timeseries zoneLoUpper = clusterLoValid ? clusterLo + atr * atrMult : 0
timeseries zoneLoLower = clusterLoValid ? clusterLo - atr * atrMult : 0

// -- 3.6 Stop hunt detection (false break + reversal) --
// A stop hunt occurs when:
//   1. Price briefly pierces a cluster level (beyond the band)
//   2. Then reverses back within the lookback bars by at least huntReversalPct of ATR
//   3. On above-average volume

var stopHuntHi = false
var stopHuntLo = false

if (clusterHiValid) {
    // Check if price pierced above cluster recently then reversed down
    var piercedHi = bars.high > clusterHi + atr * atrMult * 0.5
    var reversedHi = bars.close < clusterHi - huntReversalPct * atr
    stopHuntHi = piercedHi && reversedHi && volSpike
}

if (clusterLoValid) {
    // Check if price pierced below cluster recently then reversed up
    var piercedLo = bars.low < clusterLo - atr * atrMult * 0.5
    var reversedLo = bars.close > clusterLo + huntReversalPct * atr
    stopHuntLo = piercedLo && reversedLo && volSpike
}

// -- 3.7 Fresh vs aged cluster colour logic --
// Fresh = detected within last 5 bars; Aged = older than 5 bars
var hiFresh = clusterHiValid && clusterHiAge <= 5
var loFresh = clusterLoValid && clusterLoAge <= 5
var hiColor = hiFresh ? freshColor : agedColor
var loColor = loFresh ? freshColor : agedColor

// ---------------------------------------------------------------------------
// 4. STATIC STATE TRACKING — hunt persistence, cluster history
// ---------------------------------------------------------------------------

static huntHiCount = 0
static huntLoCount = 0
static breakHiCount = 0
static breakLoCount = 0
static totalClusters = 0
static lastHuntBar = 0

if (stopHuntHi) {
    huntHiCount = huntHiCount + 1
    lastHuntBar = 1
}
if (stopHuntLo) {
    huntLoCount = huntLoCount + 1
    lastHuntBar = -1
}
if (breakHi) {
    breakHiCount = breakHiCount + 1
}
if (breakLo) {
    breakLoCount = breakLoCount + 1
}
if ((pivotHi || pivotLo) && volSpike) {
    totalClusters = totalClusters + 1
}

// ---------------------------------------------------------------------------
// 5. VISUALIZATION
// ---------------------------------------------------------------------------

// 5.1 Stop cluster zones (lines)
if (showZones) {
    if (clusterHiValid) {
        plotLine(
            value=clusterHi,
            width=2,
            colors=[hiColor],
            label=["Stop Cluster High"],
            desc=["Resistance stop cluster at pivot high + volume spike; age=" + clusterHiAge]
        )
    }
    if (clusterLoValid) {
        plotLine(
            value=clusterLo,
            width=2,
            colors=[loColor],
            label=["Stop Cluster Low"],
            desc=["Support stop cluster at pivot low + volume spike; age=" + clusterLoAge]
        )
    }
}

// 5.2 ATR-based zone bands (fill between upper and lower bands)
if (showZoneBands) {
    if (clusterHiValid) {
        plotLine(
            value=[zoneHiUpper, zoneHiLower],
            width=1,
            colors=[transparency(resColor, 85), transparency(resColor, 85)],
            fill=true,
            label=["Res Zone Upper", "Res Zone Lower"],
            desc=["ATR-based resistance stop zone (±" + atrMult + "x ATR)"]
        )
    }
    if (clusterLoValid) {
        plotLine(
            value=[zoneLoUpper, zoneLoLower],
            width=1,
            colors=[transparency(supColor, 85), transparency(supColor, 85)],
            fill=true,
            label=["Sup Zone Upper", "Sup Zone Lower"],
            desc=["ATR-based support stop zone (±" + atrMult + "x ATR)"]
        )
    }
}

// 5.3 Stop hunt markers (false break + reversal)
if (showHunts && showShapes) {
    if (stopHuntHi) {
        plotShape(
            value=bars.high + atr * 0.5,
            shape="xcross",
            colorIndex=huntColor,
            width=3,
            label=["Stop Hunt High"],
            desc=["Price pierced resistance stop cluster then reversed down; classic stop hunt pattern"]
        )
    }
    if (stopHuntLo) {
        plotShape(
            value=bars.low - atr * 0.5,
            shape="xcross",
            colorIndex=huntColor,
            width=3,
            label=["Stop Hunt Low"],
            desc=["Price pierced support stop cluster then reversed up; classic stop hunt pattern"]
        )
    }
}

// 5.4 Breakout shapes (cluster broken through)
if (showShapes) {
    if (breakHi) {
        plotShape(
            value=bars.high + atr * 0.3,
            shape="triangleup",
            colorIndex=breakColor,
            width=3,
            label=["Breakout High"],
            desc=["Price broke above resistance stop cluster with momentum; continuation signal"]
        )
    }
    if (breakLo) {
        plotShape(
            value=bars.low - atr * 0.3,
            shape="triangledown",
            colorIndex=breakColor,
            width=3,
            label=["Breakout Low"],
            desc=["Price broke below support stop cluster with momentum; continuation signal"]
        )
    }
}

// 5.5 New cluster shapes (pivot + volume spike detected)
if (showShapes && pivotHi && volSpike) {
    plotShape(
        value=bars.high + atr * 0.2,
        shape="diamond",
        colorIndex=resColor,
        width=2,
        label=["New Cluster High"],
        desc=["New resistance stop cluster detected at pivot high on volume spike"]
    )
}
if (showShapes && pivotLo && volSpike) {
    plotShape(
        value=bars.low - atr * 0.2,
        shape="diamond",
        colorIndex=supColor,
        width=2,
        label=["New Cluster Low"],
        desc=["New support stop cluster detected at pivot low on volume spike"]
    )
}

// ---------------------------------------------------------------------------
// 6. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
    var clusterText = (clusterHiValid && clusterLoValid) ? "BOTH ACTIVE" : (clusterHiValid ? "RES ONLY" : (clusterLoValid ? "SUP ONLY" : "NONE"))
    var clusterColor = (clusterHiValid && clusterLoValid) ? huntColor : (clusterHiValid ? resColor : (clusterLoValid ? supColor : agedColor))

    plotTable(
        data=[
            ["Stop Finder", clusterText],
            ["Cluster High", clusterHiValid ? clusterHi : "—"],
            ["Cluster Low", clusterLoValid ? clusterLo : "—"],
            ["Hi Age", clusterHiAge],
            ["Lo Age", clusterLoAge],
            ["Hunt Count", huntHiCount + huntLoCount],
            ["Break Count", breakHiCount + breakLoCount],
            ["Total Clusters", totalClusters]
        ],
        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
    )
}