MM Flow
FlowScripts

Perfected FlowScript

Wick Inefficiency Detector

Wick Inefficiency Detector — Perfected Edition is indexed as 275_wick_inefficiency_detector.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.9 KB

Lines

512

Native Signal Candidates

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

6/6 guarded

Bear Rej

line 339:5

Trigger

(showUpper && upperRej)

Value

hi

Deps

showUpper:input, upperRej:timeseries

Bull Rej

line 351:5

Trigger

(showLower && lowerRej)

Value

lo

Deps

lowerRej:timeseries, showLower:input

Consec Bear

line 366:9

Trigger

(showConsecutive) && (consecUpper >= 2 && upperRej)

Value

hi

Deps

consecUpper:static, showConsecutive:input, upperRej:timeseries

Consec Bull

line 376:9

Trigger

(showConsecutive) && (consecLower >= 2 && lowerRej)

Value

lo

Deps

consecLower:static, lowerRej:timeseries, showConsecutive:input

Strong Bear Rej

line 392:9

Trigger

(showAlerts) && (strongUpper)

Value

hi

Deps

showAlerts:input, strongUpper:var

Strong Bull Rej

line 402:9

Trigger

(showAlerts) && (strongLower)

Value

lo

Deps

showAlerts:input, strongLower:var

275_wick_inefficiency_detector.flowscript

source path: kscripts/perfected/275_wick_inefficiency_detector.flowscript · sha256:35cace686923e51ceda596369be11415f4ce2c7e281da2341867e55aeba628f6

hash verified
//@version=2
// ============================================================================
// Wick Inefficiency Detector — Perfected Edition
// Author: RoronoaZoro (@RoronoaZoro) | Enhanced by kScript Perfection Engineer
// Tags: CORE, FLOW, #price_action, #inefficiency, #exhaustion, #absorption
//
// Production-grade candlestick wick-inefficiency detector with multi-factor
// scoring, ATR-scaled adaptive thresholds, volume z-score confirmation,
// consecutive-rejection tracking, and regime-based color coding. Identifies
// price probes that fail and reverse — the signature of exhaustion,
// absorption, and smart-money defense zones.
//
// Academic foundations:
//  1. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//     Supply and Demand" (J. Economic Literature). Liquidity memory time and
//     the square-root impact law: after a trade, liquidity is temporarily
//     depleted and gradually recovers. Cumulative impact of sequential trades
//     becomes sublinear due to this memory. When aggressive volume fails to
//     move price, it reflects passive liquidity replenishment — the "absorption"
//     signature that long-wick candles capture.
//  2. Steidlmayer & Hawkins (2003), "Steidlmayer on Markets: Trading with
//     Market Profile". "Excess" (single prints, poor highs/lows) and "tail"
//     candles: long wicks show where the market rejected value. Tails are
//     evidence of failed price acceptance and define the edges of value areas.
//  3. Nison (1991), "Japanese Candlestick Charting Techniques". Systematic
//     classification of long upper/lower shadows (wicks) as rejection signals.
//     Upper wick = rejection of higher prices; lower wick = rejection of lower
//     prices. The ratio of wick to body measures conviction failure.
//  4. Kyle (1985), "Continuous Auctions and Insider Trading" (Econometrica).
//     Price-impact coefficient λ in the informed-trader framework: Δp = λ·X.
//     When volume X is high but Δp is small (long wick, small body), λ is
//     suppressed — indicating deep liquidity or informed absorption, a
//     microstructural inefficiency that the market later corrects.
//  5. Hasbrouck (1991), "Measuring the Information Content of Stock Trades"
//     (J. Finance). Trade-sign decomposition: Δp_t = Σ_k ψ_k·x_{t−k} + ε_t.
//     The persistence of trade impact (ψ_k) is shorter when passive liquidity
//     absorbs the flow — consistent with wick-rejection dynamics where the
//     initial aggressive move is transient.
// ============================================================================

define(
    title="Wick Inefficiency Detector — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- Wick Detection ---
var wickRatio = input(
    name="wickRatio",
    type="number",
    defaultValue=0.6,
    label="Min Wick / Range Ratio",
    constraints={min: 0.1, max: 0.95, step: 0.05},
    group="Wick Detection"
)
var useAtrScale = input(
    name="useAtrScale",
    type="boolean",
    defaultValue=true,
    label="Use ATR-Scaled Wick Threshold",
    group="Wick Detection"
)
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 50, step: 1},
    group="Wick Detection"
)
var atrMinWick = input(
    name="atrMinWick",
    type="number",
    defaultValue=0.3,
    label="Min Wick Size (ATR multiple)",
    constraints={min: 0.1, max: 3.0, step: 0.1},
    group="Wick Detection"
)

// --- Volume Confirmation ---
var volMul = input(
    name="volMul",
    type="number",
    defaultValue=1.5,
    label="Volume Confirmation Multiplier",
    constraints={min: 1.0, max: 5.0, step: 0.1},
    group="Volume Confirmation"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume Confirmation"
)
var useVolZScore = input(
    name="useVolZScore",
    type="boolean",
    defaultValue=false,
    label="Use Volume Z-Score (vs SMA multiplier)",
    group="Volume Confirmation"
)

// --- Scoring & Display ---
var showUpper = input(
    name="showUpper",
    type="boolean",
    defaultValue=true,
    label="Show Upper-Wick Rejections",
    group="Scoring & Display"
)
var showLower = input(
    name="showLower",
    type="boolean",
    defaultValue=true,
    label="Show Lower-Wick Rejections",
    group="Scoring & Display"
)
var showScore = input(
    name="showScore",
    type="boolean",
    defaultValue=true,
    label="Show Inefficiency Score Histogram",
    group="Scoring & Display"
)
var showConsecutive = input(
    name="showConsecutive",
    type="boolean",
    defaultValue=true,
    label="Show Consecutive Rejection Markers",
    group="Scoring & Display"
)
var showZone = input(
    name="showZone",
    type="boolean",
    defaultValue=true,
    label="Show Rejection Zone Fill",
    group="Scoring & Display"
)
var showAlerts = input(
    name="showAlerts",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Scoring & Display"
)

// --- Colors ---
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Rejection Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Rejection Color",
    group="Colors"
)
var weakUpColor = input(
    name="weakUpColor",
    type="color",
    defaultValue="#4db6ac",
    label="Weak Bullish Rejection",
    group="Colors"
)
var weakDnColor = input(
    name="weakDnColor",
    type="color",
    defaultValue="#ef9a9a",
    label="Weak Bearish Rejection",
    group="Colors"
)
var scoreBull = input(
    name="scoreBull",
    type="color",
    defaultValue="#00e676",
    label="Score Bull Color",
    group="Colors"
)
var scoreBear = input(
    name="scoreBear",
    type="color",
    defaultValue="#ff5252",
    label="Score Bear Color",
    group="Colors"
)

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

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

// ---------------------------------------------------------------------------
// 3. WICK / RANGE / BODY COMPUTATIONS
// ---------------------------------------------------------------------------
timeseries range = hi - lo
timeseries body = math.abs(cl - op)
timeseries bodyPct = range > 0 ? body / range : 0

timeseries upperWick = hi - math.max(op, cl)
timeseries lowerWick = math.min(op, cl) - lo

timeseries upperRatio = range > 0 ? upperWick / range : 0
timeseries lowerRatio = range > 0 ? lowerWick / range : 0

// ---------------------------------------------------------------------------
// 4. ATR & ADAPTIVE THRESHOLDS
// ---------------------------------------------------------------------------
// True Range with isnan guard on 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(source=trueRange, period=atrLen)

// ATR-scaled minimum wick size
var atrWickMin = atr * atrMinWick

// ---------------------------------------------------------------------------
// 5. VOLUME CONFIRMATION
// ---------------------------------------------------------------------------
timeseries avgVol = sma(source=vol, period=volLookback)
timeseries volStd = stddev(source=vol, period=volLookback)
timeseries volZ = volStd > 0 ? (vol - avgVol) / volStd : 0

timeseries volConfirmed = useVolZScore ? volZ > volMul : vol > avgVol * volMul

// ---------------------------------------------------------------------------
// 6. REJECTION DETECTION (binary + scored)
// ---------------------------------------------------------------------------
// Upper rejection: long upper wick + (ATR-scaled or ratio) + volume confirmed
var upperAtrOk = !useAtrScale || upperWick >= atrWickMin
var lowerAtrOk = !useAtrScale || lowerWick >= atrWickMin

timeseries upperRej = upperRatio > wickRatio && upperAtrOk && volConfirmed
timeseries lowerRej = lowerRatio > wickRatio && lowerAtrOk && volConfirmed

// Inefficiency score: composite of wick ratio, volume excess, and ATR scale
// Score ∈ [0, 100] — higher = stronger inefficiency signature
var upperScore = 0.0
var lowerScore = 0.0

if (range > 0) {
    upperScore = (upperRatio * 40) + (vol > 0 && avgVol > 0 ? math.min(30, (vol / avgVol - 1) * 20) : 0) + (useAtrScale && atr > 0 ? math.min(30, (upperWick / atr) * 15) : 0)
    lowerScore = (lowerRatio * 40) + (vol > 0 && avgVol > 0 ? math.min(30, (vol / avgVol - 1) * 20) : 0) + (useAtrScale && atr > 0 ? math.min(30, (lowerWick / atr) * 15) : 0)
}

var ineffScore = 0.0
if (upperRej) {
    ineffScore = upperScore
} else if (lowerRej) {
    ineffScore = -lowerScore
}

// ---------------------------------------------------------------------------
// 7. STATIC STATE — consecutive rejection tracking, last rejection levels
// ---------------------------------------------------------------------------
static consecUpper = 0
static consecLower = 0
static lastRejHigh = 0.0
static lastRejLow = 0.0
static lastRejBar = 0
static totalRej = 0
static bullRejCount = 0
static bearRejCount = 0

if (!isLiveUpdate) {
    if (upperRej) {
        consecUpper = consecUpper + 1
        consecLower = 0
        lastRejHigh = hi
        lastRejBar = barCount
        totalRej = totalRej + 1
        bearRejCount = bearRejCount + 1
    } else if (lowerRej) {
        consecLower = consecLower + 1
        consecUpper = 0
        lastRejLow = lo
        lastRejBar = barCount
        totalRej = totalRej + 1
        bullRejCount = bullRejCount + 1
    } else {
        // Decay consecutive counts gradually (require fresh rejections)
        if (consecUpper > 0) {
            consecUpper = consecUpper - 1
        }
        if (consecLower > 0) {
            consecLower = consecLower - 1
        }
    }
}

// Bar counter for event tracking
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

var strongUpper = upperRej && consecUpper >= 2
var strongLower = lowerRej && consecLower >= 2

// ---------------------------------------------------------------------------
// 8. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime based on recent rejection dominance
var regime = "NEUTRAL"
if (bullRejCount > bearRejCount + 3) {
    regime = "BULLISH DEFENSE"
} else if (bearRejCount > bullRejCount + 3) {
    regime = "BEARISH DEFENSE"
}

var regimeColor = regime == "BULLISH DEFENSE" ? upColor : (regime == "BEARISH DEFENSE" ? dnColor : "#9e9e9e")

// ---------------------------------------------------------------------------
// 9. PLOTS: REJECTION SHAPES
// ---------------------------------------------------------------------------
if (showUpper && upperRej) {
    var upperColor = strongUpper ? dnColor : weakDnColor
    plotShape(
        value=hi,
        shape="triangledown",
        colorIndex=upperColor,
        width=strongUpper ? 5 : 3,
        label=["Bear Rej"],
        desc=["Bearish rejection: long upper wick + volume. Score: " + upperScore]
    )
}

if (showLower && lowerRej) {
    var lowerColor = strongLower ? upColor : weakUpColor
    plotShape(
        value=lo,
        shape="triangleup",
        colorIndex=lowerColor,
        width=strongLower ? 5 : 3,
        label=["Bull Rej"],
        desc=["Bullish rejection: long lower wick + volume. Score: " + lowerScore]
    )
}

// ---------------------------------------------------------------------------
// 10. PLOTS: CONSECUTIVE REJECTION MARKERS
// ---------------------------------------------------------------------------
if (showConsecutive) {
    if (consecUpper >= 2 && upperRej) {
        plotShape(
            value=hi,
            shape="xcross",
            colorIndex=dnColor,
            width=4,
            label=["Consec Bear"],
            desc=["Consecutive bearish rejections (≥2). Potential supply wall."]
        )
    }
    if (consecLower >= 2 && lowerRej) {
        plotShape(
            value=lo,
            shape="xcross",
            colorIndex=upColor,
            width=4,
            label=["Consec Bull"],
            desc=["Consecutive bullish rejections (≥2). Potential demand floor."]
        )
    }
}

// ---------------------------------------------------------------------------
// 11. PLOTS: ALERT SHAPES (strong rejection events)
// ---------------------------------------------------------------------------
if (showAlerts) {
    if (strongUpper) {
        plotShape(
            value=hi,
            shape="circle",
            colorIndex=dnColor,
            width=3,
            label=["Strong Bear Rej"],
            desc=["Strong bearish rejection: consecutive upper wicks with volume."]
        )
    }
    if (strongLower) {
        plotShape(
            value=lo,
            shape="circle",
            colorIndex=upColor,
            width=3,
            label=["Strong Bull Rej"],
            desc=["Strong bullish rejection: consecutive lower wicks with volume."]
        )
    }
}

// ---------------------------------------------------------------------------
// 12. PLOTS: INEFFICIENCY SCORE HISTOGRAM
// ---------------------------------------------------------------------------
if (showScore && ineffScore != 0) {
    var histColor = ineffScore > 0 ? scoreBull : scoreBear
    plotBar(
        value=ineffScore,
        colors=[transparency(histColor, 60)],
        label=["Ineff Score"],
        desc=["Wick inefficiency score: composite of wick ratio, volume excess, and ATR scale."]
    )
}

// ---------------------------------------------------------------------------
// 13. PLOTS: REJECTION ZONE FILL
// ---------------------------------------------------------------------------
// Fill between high and the rejection zone (top of body for upper, bottom of
// body for lower) to visualize the "inefficient" probe area.
if (showZone) {
    if (upperRej && range > 0) {
        var zoneTop = hi
        var zoneBot = math.max(op, cl)
        var zoneFill = transparency(dnColor, 25)
        plotLine(
            value=[zoneTop, zoneBot],
            width=1,
            colors=[zoneFill, zoneFill],
            fill=zoneFill,
            label=["Bear Zone", "Bear Zone"],
            desc=["Upper rejection inefficiency zone: price probed higher but closed lower.", "Body top boundary."]
        )
    }
    if (lowerRej && range > 0) {
        var zoneTop2 = math.min(op, cl)
        var zoneBot2 = lo
        var zoneFill2 = transparency(upColor, 25)
        plotLine(
            value=[zoneTop2, zoneBot2],
            width=1,
            colors=[zoneFill2, zoneFill2],
            fill=zoneFill2,
            label=["Bull Zone", "Bull Zone"],
            desc=["Lower rejection inefficiency zone: price probed lower but closed higher.", "Body bottom boundary."]
        )
    }
}

// ---------------------------------------------------------------------------
// 14. LAST REJECTION LEVELS (plotLine — extended reference)
// ---------------------------------------------------------------------------
if (lastRejHigh > 0) {
    plotLine(
        value=lastRejHigh,
        width=1,
        colors=[transparency(dnColor, 50)],
        label=["Last Rej High"],
        desc=["Last bearish rejection high: potential resistance reference."]
    )
}
if (lastRejLow > 0) {
    plotLine(
        value=lastRejLow,
        width=1,
        colors=[transparency(upColor, 50)],
        label=["Last Rej Low"],
        desc=["Last bullish rejection low: potential support reference."]
    )
}

// ---------------------------------------------------------------------------
// 15. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var tableData = [
        ["Wick Inefficiency", regime],
        ["Bull Rejections", bullRejCount],
        ["Bear Rejections", bearRejCount],
        ["Total Detected", totalRej],
        ["Consec Upper", consecUpper],
        ["Consec Lower", consecLower],
        ["ATR", atr[0]],
        ["Avg Vol", avgVol[0]]
    ]

    plotTable(
        data=tableData,
        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
    )
}