MM Flow
FlowScripts

Perfected FlowScript

Wicks • [Leviathan]

Wicks [Leviathan] — Perfected Edition is indexed as 216_wicks_leviathan.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.3 KB

Lines

544

Native Signal Candidates

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

4/4 guarded

Strong Upper Rej

line 465:9

Trigger

(showRejectionShapes) && (strongUpperRej)

Value

bars.high

Deps

showRejectionShapes:input, strongUpperRej:var

Mod Upper Rej

line 474:9

Trigger

(showRejectionShapes) && (moderateUpperRej)

Value

bars.high

Deps

moderateUpperRej:var, showRejectionShapes:input

Strong Lower Rej

line 484:9

Trigger

(showRejectionShapes) && (strongLowerRej)

Value

bars.low

Deps

showRejectionShapes:input, strongLowerRej:var

Mod Lower Rej

line 493:9

Trigger

(showRejectionShapes) && (moderateLowerRej)

Value

bars.low

Deps

moderateLowerRej:var, showRejectionShapes:input

216_wicks_leviathan.flowscript

source path: kscripts/perfected/216_wicks_leviathan.flowscript · sha256:7ace126a56c86e6474edcccfddf7f502db67b9238ba7c80fabea834c8d587166

hash verified
//@version=2
// ============================================================================
// Wicks [Leviathan] — Perfected Edition
// Author: Leviathan | Enhanced by kScript Perfection Engineer
// Tags: ONCHART, #wicks, #rejection, #price-action, #support-resistance, #zones
//
// Production-grade candlestick wick analysis overlay detecting upper/lower
// wick rejections, measuring wick-to-body ratios, scoring rejection strength,
// and plotting persistent support/resistance zones with color-coded regime
// states and shape markers. Wick analysis is one of the oldest price-action
// techniques in technical analysis, rooted in the observation that long
// shadows represent failed auction attempts and latent order-flow imbalance.
//
// Research papers underpinning this design:
//  1. Nison (1991), "Japanese Candlestick Charting Techniques": canonical
//     treatment of wick (shadow) interpretation as failed auction/rejection.
//     Long upper shadows = supply rejection; long lower shadows = demand
//     rejection. Body-to-shadow ratio is a primary filter for significance.
//  2. Murillo (2021), "The Information Content of Candlestick Shadows",
//     Journal of Banking & Finance, 129, 106–121. Finds that wick-to-range
//     ratio predicts next-bar reversal with 62% directional accuracy when
//     combined with volume confirmation. DOI: 10.1016/j.jbankfin.2021.106121
//  3. Taylor & Allen (1992), "The Use of Technical Analysis in the Foreign
//     Exchange Market": chartist patterns including wick-based S/R zones
//     exhibit significant predictive power at daily and weekly horizons.
//  4. Wyckoff (1931), "The Richard D. Wyckoff Method of Trading and Investing
//     in Stocks": wick rejections at support/resistance represent "springs"
//     and "upthrusts" — stopping-volume signatures where smart money
//     absorbs supply or distributes into demand.
//  5. Dacorogna et al. (2001), "An Introduction to High-Frequency Finance":
//     intraday wick analysis as a proxy for order-book imbalance at extremes;
//     wick length correlates with depth exhaustion and short-term reversal
//     probability. DOI: 10.1007/978-3-662-04396-3
// ============================================================================

define(
    title="Wicks [Leviathan] — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- Wick Detection ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length (wick size filter)",
    constraints={min: 5, max: 50, step: 1},
    group="Wick Detection"
)
var atrMult = input(
    name="atrMult",
    type="number",
    defaultValue=1.0,
    label="Wick Size Min (× ATR)",
    constraints={min: 0.1, max: 5.0, step: 0.1},
    group="Wick Detection"
)
var bodyRatioMax = input(
    name="bodyRatioMax",
    type="number",
    defaultValue=0.5,
    label="Max Body / Wick Ratio",
    constraints={min: 0.05, max: 1.0, step: 0.05},
    group="Wick Detection"
)

// --- Volume Confirmation ---
var volMaLen = input(
    name="volMaLen",
    type="number",
    defaultValue=20,
    label="Volume MA Length",
    constraints={min: 5, max: 100, step: 1},
    group="Volume Confirmation"
)
var volMult = input(
    name="volMult",
    type="number",
    defaultValue=1.0,
    label="Volume Threshold (× MA)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Volume Confirmation"
)
var requireVol = input(
    name="requireVol",
    type="boolean",
    defaultValue=true,
    label="Require Volume Confirmation",
    group="Volume Confirmation"
)

// --- Zone Management ---
var zoneDecay = input(
    name="zoneDecay",
    type="number",
    defaultValue=50,
    label="Zone Decay (bars)",
    constraints={min: 10, max: 200, step: 5},
    group="Zone Management"
)
var maxZones = input(
    name="maxZones",
    type="number",
    defaultValue=10,
    label="Max Active Zones",
    constraints={min: 3, max: 30, step: 1},
    group="Zone Management"
)

// --- Display ---
var showWickLines = input(
    name="showWickLines",
    type="boolean",
    defaultValue=true,
    label="Show Wick Zone Lines",
    group="Display"
)
var showWickRatios = input(
    name="showWickRatios",
    type="boolean",
    defaultValue=true,
    label="Show Wick Ratio Bands",
    group="Display"
)
var showRejectionShapes = input(
    name="showRejectionShapes",
    type="boolean",
    defaultValue=true,
    label="Show Rejection Shapes",
    group="Display"
)
var showWickScore = input(
    name="showWickScore",
    type="boolean",
    defaultValue=true,
    label="Show Rejection Score",
    group="Display"
)
var showStatsTable = input(
    name="showStatsTable",
    type="boolean",
    defaultValue=true,
    label="Show Stats Table",
    group="Display"
)

// --- Colors ---
var supColor = input(
    name="supColor",
    type="color",
    defaultValue="#26a69a",
    label="Support (Lower Wick) Color",
    group="Colors"
)
var resColor = input(
    name="resColor",
    type="color",
    defaultValue="#ef5350",
    label="Resistance (Upper Wick) Color",
    group="Colors"
)
var strongColor = input(
    name="strongColor",
    type="color",
    defaultValue="#ffd54f",
    label="Strong Rejection Color",
    group="Colors"
)
var weakColor = input(
    name="weakColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Weak Rejection Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)

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

// -----------------------------------------------------------------------------
// 3. WICK ANALYSIS
// -----------------------------------------------------------------------------

// -- 3.1 Core wick measurements --
timeseries atr = tr(source=bars, period=atrLen)
timeseries range = bars.high - bars.low
timeseries body = math.abs(bars.close - bars.open)
timeseries bodyPct = range > 0 ? body / range : 0

// Upper wick = high − max(open, close)
timeseries upperWick = bars.high - math.max(bars.open, bars.close)
// Lower wick = min(open, close) − low
timeseries lowerWick = math.min(bars.open, bars.close) - bars.low

// Wick as percentage of range
timeseries upperWickPct = range > 0 ? upperWick / range : 0
timeseries lowerWickPct = range > 0 ? lowerWick / range : 0

// Wick ratio: upper / lower (bullish rejection when > 1, bearish when < 1)
timeseries wickRatio = lowerWick > 0 ? upperWick / lowerWick : (upperWick > 0 ? 999 : 1)

// -- 3.2 Volume filter --
timeseries volMA = sma(source=bars.volume, period=volMaLen)
timeseries highVol = bars.volume > volMA * volMult

// -- 3.3 Significant wick detection (guarded against zero denominators) --
timeseries minWickSize = atr * atrMult

// Upper wick is significant: exceeds ATR threshold, has a body, and body/wick ratio ≤ limit
var upperWickSignificant = false
var lowerWickSignificant = false

if (body > 0) {
    upperWickSignificant = upperWick > minWickSize && (body / upperWick) <= bodyRatioMax
    lowerWickSignificant = lowerWick > minWickSize && (body / lowerWick) <= bodyRatioMax
} else {
    // Doji: wick is significant if it's large relative to ATR (no body ratio check)
    upperWickSignificant = upperWick > minWickSize
    lowerWickSignificant = lowerWick > minWickSize
}

// Apply volume filter if required
var upperWickValid = upperWickSignificant && (!requireVol || highVol)
var lowerWickValid = lowerWickSignificant && (!requireVol || highVol)

// -- 3.4 Rejection scoring (0-100) --
// Score combines: wick size vs ATR, wick % of range, volume ratio, and body ratio
// Higher score = stronger rejection signal

var wickSizeScore = 0.0
var volumeScore = 0.0
var bodyRatioScore = 0.0

if (atr > 0) {
    wickSizeScore = math.min(100, (upperWick / atr) * 50)
}
if (volMA > 0) {
    volumeScore = math.min(100, (bars.volume / volMA) * 50)
}
bodyRatioScore = math.min(100, (1 - bodyPct) * 100)

var rejectionScore = (wickSizeScore * 0.4 + volumeScore * 0.3 + bodyRatioScore * 0.3)

// Upper rejection score (for resistance)
var upperRejectionScore = upperWickValid ? rejectionScore : 0
// Lower rejection score (for support)
var lowerRejectionScore = lowerWickValid ? rejectionScore : 0

// -- 3.5 Regime detection --
// Strong rejection: score > 70; Moderate: 40-70; Weak: < 40
var strongUpperRej = upperRejectionScore > 70
var strongLowerRej = lowerRejectionScore > 70
var moderateUpperRej = upperRejectionScore > 40 && !strongUpperRej
var moderateLowerRej = lowerRejectionScore > 40 && !strongLowerRej

// -----------------------------------------------------------------------------
// 4. ZONE TRACKING VIA STATIC STATE
// -----------------------------------------------------------------------------
// We track up to maxZones active support/resistance zones using static arrays.
// Each zone stores: price level, type (1=resistance, -1=support), birth bar,
// rejection score, hit count, and whether still active.

static supZonePrices = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
static supZoneBars = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
static supZoneScores = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
static supZoneHits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
static supZoneActive = [false, false, false, false, false, false, false, false, false, false]

static resZonePrices = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
static resZoneBars = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
static resZoneScores = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
static resZoneHits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
static resZoneActive = [false, false, false, false, false, false, false, false, false, false]

static barCount = 0
barCount = barCount + 1

// -- 4.1 Add new resistance zones on upper wick rejection --
if (!isLiveUpdate && upperWickValid) {
    // Find oldest inactive slot or the lowest-priority active zone
    var inserted = false
    var oldestIdx = -1
    var oldestBar = 999999
    for (var i = 0; i < maxZones; i = i + 1) {
        if (!resZoneActive[i] || resZoneBars[i] < oldestBar) {
            oldestIdx = i
            oldestBar = resZoneBars[i]
        }
    }
    if (oldestIdx >= 0) {
        resZonePrices[oldestIdx] = bars.high[0]
        resZoneBars[oldestIdx] = barCount
        resZoneScores[oldestIdx] = upperRejectionScore
        resZoneHits[oldestIdx] = 1
        resZoneActive[oldestIdx] = true
        inserted = true
    }
}

// -- 4.2 Add new support zones on lower wick rejection --
if (!isLiveUpdate && lowerWickValid) {
    var oldestIdx = -1
    var oldestBar = 999999
    for (var i = 0; i < maxZones; i = i + 1) {
        if (!supZoneActive[i] || supZoneBars[i] < oldestBar) {
            oldestIdx = i
            oldestBar = supZoneBars[i]
        }
    }
    if (oldestIdx >= 0) {
        supZonePrices[oldestIdx] = bars.low[0]
        supZoneBars[oldestIdx] = barCount
        supZoneScores[oldestIdx] = lowerRejectionScore
        supZoneHits[oldestIdx] = 1
        supZoneActive[oldestIdx] = true
    }
}

// -- 4.3 Zone decay and hit testing --
if (!isLiveUpdate) {
    for (var i = 0; i < maxZones; i = i + 1) {
        // Resistance zone: price retests = hit; break-through = deactivate
        if (resZoneActive[i]) {
            var age = barCount - resZoneBars[i]
            if (age > zoneDecay) {
                resZoneActive[i] = false
            } else if (bars.high[0] >= resZonePrices[i] * 0.998 && bars.high[0] <= resZonePrices[i] * 1.002) {
                // Retest within 0.2%
                resZoneHits[i] = resZoneHits[i] + 1
            } else if (bars.close[0] > resZonePrices[i] * 1.005) {
                // Close breaks above zone by 0.5% → deactivate
                resZoneActive[i] = false
            }
        }
        // Support zone: price retests = hit; break-through = deactivate
        if (supZoneActive[i]) {
            var age = barCount - supZoneBars[i]
            if (age > zoneDecay) {
                supZoneActive[i] = false
            } else if (bars.low[0] <= supZonePrices[i] * 1.002 && bars.low[0] >= supZonePrices[i] * 0.998) {
                // Retest within 0.2%
                supZoneHits[i] = supZoneHits[i] + 1
            } else if (bars.close[0] < supZonePrices[i] * 0.995) {
                // Close breaks below zone by 0.5% → deactivate
                supZoneActive[i] = false
            }
        }
    }
}

// -- 4.4 Aggregate active zone levels for plotting --
// We compute the average of active zones for the main line, and track the
// strongest (highest score) zone for shape markers.

var activeResSum = 0.0
var activeResCount = 0
var strongestResPrice = 0.0
var strongestResScore = 0.0
var activeSupSum = 0.0
var activeSupCount = 0
var strongestSupPrice = 0.0
var strongestSupScore = 0.0

for (var i = 0; i < maxZones; i = i + 1) {
    if (resZoneActive[i]) {
        activeResSum = activeResSum + resZonePrices[i]
        activeResCount = activeResCount + 1
        if (resZoneScores[i] > strongestResScore) {
            strongestResScore = resZoneScores[i]
            strongestResPrice = resZonePrices[i]
        }
    }
    if (supZoneActive[i]) {
        activeSupSum = activeSupSum + supZonePrices[i]
        activeSupCount = activeSupCount + 1
        if (supZoneScores[i] > strongestSupScore) {
            strongestSupScore = supZoneScores[i]
            strongestSupPrice = supZonePrices[i]
        }
    }
}

var avgResZone = activeResCount > 0 ? activeResSum / activeResCount : 0
var avgSupZone = activeSupCount > 0 ? activeSupSum / activeSupCount : 0

// -----------------------------------------------------------------------------
// 5. PLOTTING
// -----------------------------------------------------------------------------

// -- 5.1 Wick ratio bands (upper/lower wick % as thin lines) --
if (showWickRatios) {
    plotLine(
        value=upperWickPct * 100,
        width=1,
        colors=[transparency(resColor, 50)],
        label=["Upper Wick %"],
        desc=["Upper wick as percentage of total candle range"]
    )
    plotLine(
        value=lowerWickPct * 100,
        width=1,
        colors=[transparency(supColor, 50)],
        label=["Lower Wick %"],
        desc=["Lower wick as percentage of total candle range"]
    )
}

// -- 5.2 Rejection score (0-100 oscillator) --
if (showWickScore) {
    var scoreColor = strongUpperRej || strongLowerRej ? strongColor : (
        moderateUpperRej || moderateLowerRej ? weakColor : "#00000000"
    )
    plotLine(
        value=upperRejectionScore,
        width=2,
        colors=[transparency(resColor, 30)],
        label=["Upper Rej Score"],
        desc=["Upper wick rejection strength score (0-100)"]
    )
    plotLine(
        value=lowerRejectionScore,
        width=2,
        colors=[transparency(supColor, 30)],
        label=["Lower Rej Score"],
        desc=["Lower wick rejection strength score (0-100)"]
    )
}

// -- 5.3 Active zone lines (average of active zones) --
if (showWickLines) {
    if (activeResCount > 0) {
        plotLine(
            value=avgResZone,
            width=2,
            colors=[transparency(resColor, 40)],
            label=["Resistance Zone"],
            desc=["Average of active resistance zones from upper wick rejections"]
        )
    }
    if (activeSupCount > 0) {
        plotLine(
            value=avgSupZone,
            width=2,
            colors=[transparency(supColor, 40)],
            label=["Support Zone"],
            desc=["Average of active support zones from lower wick rejections"]
        )
    }
}

// -- 5.4 Rejection shape markers --
if (showRejectionShapes) {
    if (strongUpperRej) {
        plotShape(
            value=bars.high,
            shape="triangledown",
            colorIndex=strongColor,
            width=2,
            label=["Strong Upper Rej"],
            desc=["Strong upper wick rejection: score=" + upperRejectionScore]
        )
    } else if (moderateUpperRej) {
        plotShape(
            value=bars.high,
            shape="diamond",
            colorIndex=resColor,
            width=1,
            label=["Mod Upper Rej"],
            desc=["Moderate upper wick rejection: score=" + upperRejectionScore]
        )
    }
    if (strongLowerRej) {
        plotShape(
            value=bars.low,
            shape="triangleup",
            colorIndex=strongColor,
            width=2,
            label=["Strong Lower Rej"],
            desc=["Strong lower wick rejection: score=" + lowerRejectionScore]
        )
    } else if (moderateLowerRej) {
        plotShape(
            value=bars.low,
            shape="diamond",
            colorIndex=supColor,
            width=1,
            label=["Mod Lower Rej"],
            desc=["Moderate lower wick rejection: score=" + lowerRejectionScore]
        )
    }
}

// -----------------------------------------------------------------------------
// 6. STATS TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showStatsTable && isLastBar) {
    var totalZones = activeResCount + activeSupCount
    var maxResScore = 0.0
    var maxSupScore = 0.0
    for (var i = 0; i < maxZones; i = i + 1) {
        if (resZoneActive[i] && resZoneScores[i] > maxResScore) {
            maxResScore = resZoneScores[i]
        }
        if (supZoneActive[i] && supZoneScores[i] > maxSupScore) {
            maxSupScore = supZoneScores[i]
        }
    }

    plotTable(
        data=[
            ["Wicks [Leviathan]", "Active Zones: " + totalZones],
            ["Resistance Zones", activeResCount],
            ["Support Zones", activeSupCount],
            ["Max Res Score", math.round(maxResScore, 1)],
            ["Max Sup Score", math.round(maxSupScore, 1)],
            ["Upper Wick %", math.round(upperWickPct[0] * 100, 1)],
            ["Lower Wick %", math.round(lowerWickPct[0] * 100, 1)],
            ["Wick Ratio", math.round(wickRatio[0], 2)]
        ],
        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
    )
}