MM Flow
FlowScripts

Perfected FlowScript

MAGNITO BY @MAGNUS_CAPITAL

MAGNITO BY @MAGNUS_CAPITAL — Perfected Edition is indexed as 302_magnito_by_magnus_capital.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

offchart

Axis

true

Size

16.4 KB

Lines

508

Native Signal Candidates

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

6/6 guarded

Gravity Cross Up

line 413:9

Trigger

(showShapes) && (crossUp)

Value

gravitySmooth

Deps

crossUp:var, showShapes:input

Gravity Cross Down

line 423:9

Trigger

(showShapes) && (crossDown)

Value

gravitySmooth

Deps

crossDown:var, showShapes:input

Hot Zone Enter

line 433:9

Trigger

(showShapes) && (hotEnter)

Value

gravitySmooth

Deps

hotEnter:var, showShapes:input

Cold Zone Enter

line 443:9

Trigger

(showShapes) && (coldEnter)

Value

gravitySmooth

Deps

coldEnter:var, showShapes:input

Hot Zone Exit

line 453:9

Trigger

(showShapes) && (hotExit)

Value

gravitySmooth

Deps

hotExit:var, showShapes:input

Cold Zone Exit

line 463:9

Trigger

(showShapes) && (coldExit)

Value

gravitySmooth

Deps

coldExit:var, showShapes:input

302_magnito_by_magnus_capital.flowscript

source path: kscripts/perfected/302_magnito_by_magnus_capital.flowscript · sha256:42d520046ca9b5a43d77d33dcc7f8d815ae13fa176b0361adf16241aa423cf50

hash verified
//@version=2
// ============================================================================
// MAGNITO BY @MAGNUS_CAPITAL — Perfected Edition
// Author: A (@ATG_Crypto) | Enhanced by kScript Perfection Engineer
// Tags: FLOW, #liquidation, #gravity, #cluster, #multifactor, #regime, #magnito
//
// Production-quality multi-factor liquidation clustering indicator with
// composite scoring, z-score normalization, regime detection, color-coding,
// fill visualization, and shape-marker alerts. Maps forced liquidation
// clustering by price level; large clusters act as gravity wells that
// market makers hunt because liquidations create guaranteed forced market orders.
//
// Research papers underpinning this design:
//  1. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity":
//     liquidity spirals and funding constraints create self-reinforcing
//     deleveraging. Large liquidation clusters attract predatory flow.
//  2. Bian et al. (2023), "Deleveraging Commonality": documents systematic
//     deleveraging patterns across assets; liquidation clusters exhibit
//     cross-sectional commonality.
//  3. Mandelbrot (1963), "The Variation of Certain Speculative Prices":
//     fractal geometry of price paths. Heavy tails and self-similarity
//     imply that liquidation clusters concentrate at specific price levels
//     with scale-invariant distributions.
//  4. Kaufman (1995), "Smarter Trading": Efficiency Ratio measures price
//     path straightness. We use a momentum-efficiency composite to weight
//     liquidation intensity by trend quality.
//  5. Fama & French (1993), "Common Risk Factors": multi-factor model
//     construction. Composite scoring from heterogeneous proxies improves
//     signal robustness vs. any single indicator.
//  6. Peters (1994), "Fractal Market Analysis": heterogeneous investment
//     horizons create stable market structure. Crises occur when short-term
//     traders dominate; liquidation clusters signal this transition.
// ============================================================================

define(
    title="MAGNITO BY @MAGNUS_CAPITAL — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Cluster Configuration ---
var clusterLen = input(
    name="clusterLen",
    type="number",
    defaultValue=50,
    label="Cluster Lookback",
    constraints={min: 10, max: 200, step: 1},
    group="Cluster Configuration"
)
var binCount = input(
    name="binCount",
    type="number",
    defaultValue=20,
    label="Price Bin Count",
    constraints={min: 5, max: 100, step: 1},
    group="Cluster Configuration"
)
var liqThr = input(
    name="liqThr",
    type="number",
    defaultValue=1.5,
    label="Liquidation Threshold (sigma)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Cluster Configuration"
)

// --- Smoothing ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 50, step: 1},
    group="Smoothing"
)
var signalLen = input(
    name="signalLen",
    type="number",
    defaultValue=14,
    label="Signal SMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="Smoothing"
)

// --- Multi-Factor Weights ---
var weightIntensity = input(
    name="weightIntensity",
    type="number",
    defaultValue=0.4,
    label="Weight: Liquidation Intensity",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Multi-Factor Weights"
)
var weightMomentum = input(
    name="weightMomentum",
    type="number",
    defaultValue=0.3,
    label="Weight: Momentum Factor",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Multi-Factor Weights"
)
var weightVolatility = input(
    name="weightVolatility",
    type="number",
    defaultValue=0.3,
    label="Weight: Volatility Factor",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Multi-Factor Weights"
)

// --- Thresholds ---
var hotThresh = input(
    name="hotThresh",
    type="number",
    defaultValue=60.0,
    label="Hot Zone Threshold",
    constraints={min: 30.0, max: 90.0, step: 1.0},
    group="Thresholds"
)
var coldThresh = input(
    name="coldThresh",
    type="number",
    defaultValue=40.0,
    label="Cold Zone Threshold",
    constraints={min: 10.0, max: 50.0, step: 1.0},
    group="Thresholds"
)

// --- Display ---
var showGravity = input(
    name="showGravity",
    type="boolean",
    defaultValue=true,
    label="Show Gravity Score",
    group="Display"
)
var showFactors = input(
    name="showFactors",
    type="boolean",
    defaultValue=false,
    label="Show Individual Factor Lines",
    group="Display"
)
var showSignalFill = input(
    name="showSignalFill",
    type="boolean",
    defaultValue=true,
    label="Show Signal Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Shapes",
    group="Display"
)

// --- Colors ---
var hotColor = input(
    name="hotColor",
    type="color",
    defaultValue="#ef5350",
    label="Hot Zone (Gravity High) Color",
    group="Colors"
)
var coldColor = input(
    name="coldColor",
    type="color",
    defaultValue="#26a69a",
    label="Cold Zone (Gravity Low) 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 vol = bars.volume
timeseries rng = bars.high - bars.low

if (isnan(px[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. LIQUIDATION INTENSITY FACTOR
// -----------------------------------------------------------------------------
// Estimate liquidation intensity per bar as volume / range.
// High volume with low range = absorption / liquidation zone;
// high volume with wide range = climactic flow.

timeseries intensity = rng > 0 ? vol / rng : 0.0
timeseries intensityMean = sma(intensity, clusterLen)
timeseries intensityStd = stddev(intensity, clusterLen)
timeseries intensityZ = intensityStd > 0 ? (intensity - intensityMean) / intensityStd : 0.0

// Liquidation threshold crossing
timeseries liqThreshold = intensityMean + liqThr * intensityStd
timeseries isHot = intensity >= liqThreshold ? 1.0 : 0.0

// Raw gravity score (percentage of bars in lookback that exceed threshold)
timeseries rawGravity = sma(isHot, clusterLen) * 100.0

// -----------------------------------------------------------------------------
// 4. MOMENTUM FACTOR (Kaufman Efficiency Ratio)
// -----------------------------------------------------------------------------
// Per Kaufman (1995), ER measures price path efficiency. In a liquidation
// cluster, price often moves efficiently toward the cluster level (high ER).
// We use a short-term ER as a momentum confirmation factor.

var momLen = 10
timeseries momChange = math.abs(px - px[momLen])
timeseries momVol = 0.0
for (var i = 0; i < momLen; i = i + 1) {
    momVol = momVol + math.abs(px[i] - px[i + 1])
}
timeseries rawMomentum = momVol > 0 ? momChange / momVol : 0.0
timeseries momentum = math.max(0.0, math.min(1.0, rawMomentum)) * 100.0

// -----------------------------------------------------------------------------
// 5. VOLATILITY FACTOR
// -----------------------------------------------------------------------------
// Liquidation events coincide with volatility spikes. We use a normalized
// ATR relative to its rolling median to detect abnormal volatility.

timeseries atr = bars.high - bars.low
timeseries atrMean = sma(atr, clusterLen)
timeseries atrStd = stddev(atr, clusterLen)
timeseries volatilityZ = atrStd > 0 ? (atr - atrMean) / atrStd : 0.0
// Normalize to 0-100
timeseries volatilityFactor = math.max(0.0, math.min(100.0, (volatilityZ + 3.0) * 16.67))

// -----------------------------------------------------------------------------
// 6. MULTI-FACTOR COMPOSITE SCORE
// -----------------------------------------------------------------------------
// Per Fama & French (1993) multi-factor construction, we combine heterogeneous
// proxies into a single composite score. Each factor is normalized to [0, 100]
// before weighting.

timeseries normGravity = math.max(0.0, math.min(100.0, rawGravity))
timeseries normMomentum = math.max(0.0, math.min(100.0, momentum))
timeseries normVolatility = math.max(0.0, math.min(100.0, volatilityFactor))

// Weighted sum (weights sum to 1.0 by design)
timeseries rawComposite = weightIntensity * normGravity + weightMomentum * normMomentum + weightVolatility * normVolatility

// Normalize composite to 0-100 scale using a 20-bar rolling range
timeseries compositeMin = lowest(rawComposite, 20)
timeseries compositeMax = highest(rawComposite, 20)
timeseries compositeRange = compositeMax - compositeMin
timeseries composite = compositeRange > 0 ? (rawComposite - compositeMin) / compositeRange * 100.0 : 50.0

// Smooth
timeseries gravitySmooth = ema(composite, smoothLen)

// Signal SMA
timeseries signal = sma(gravitySmooth, signalLen)

// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Three-regime classification:
//   HOT ZONE:   gravity > hotThresh  (liquidation cluster gravity well active)
//   COLD ZONE:  gravity < coldThresh (low liquidation pressure)
//   NEUTRAL:    between thresholds

var regimeHot = gravitySmooth >= hotThresh
var regimeCold = gravitySmooth <= coldThresh
var regimeNeutral = !regimeHot && !regimeCold

var regimeColor = regimeHot ? hotColor : (regimeCold ? coldColor : neutralColor)

// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Tracks session gravity extremes, regime transitions, and hot/cold zone counts.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighGravity = -999999.0
static sessionLowGravity = 999999.0
static hotZoneCount = 0
static coldZoneCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (gravitySmooth > sessionHighGravity) {
        sessionHighGravity = gravitySmooth
    }
    if (gravitySmooth < sessionLowGravity) {
        sessionLowGravity = gravitySmooth
    }

    var currRegime = regimeHot ? 1 : (regimeCold ? -1 : 0)
    if (lastRegime != currRegime) {
        lastRegime = currRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (regimeHot) {
        hotZoneCount = hotZoneCount + 1
    } else if (regimeCold) {
        coldZoneCount = coldZoneCount + 1
    }
}

// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossovers of gravity vs. signal line; regime transitions; hot/cold entries.

var crossUp = gravitySmooth > signal && gravitySmooth[1] <= signal[1]
var crossDown = gravitySmooth < signal && gravitySmooth[1] >= signal[1]

var hotEnter = regimeHot && !regimeHot[1]
var coldEnter = regimeCold && !regimeCold[1]

var hotExit = !regimeHot && regimeHot[1]
var coldExit = !regimeCold && regimeCold[1]

// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------

// --- Midline ---
hline(value=50.0, color="#ffffff20", width=1)

// --- Threshold lines ---
hline(value=hotThresh, color=transparency(hotColor, 50), width=1)
hline(value=coldThresh, color=transparency(coldColor, 50), width=1)

// --- Gravity Score (regime-colored) ---
if (showGravity) {
    plotLine(
        value=gravitySmooth,
        width=2,
        colors=[regimeColor],
        label=["Gravity Score"],
        desc=["Multi-factor liquidation clustering gravity score (0-100). Hot = cluster gravity well active."]
    )
}

// --- Signal SMA ---
if (showGravity) {
    plotLine(
        value=signal,
        width=1,
        colors=[neutralColor],
        label=["Signal SMA"],
        desc=["SMA of gravity score for crossover detection (" + signalLen + ")"]
    )
}

// --- Signal Fill (gravity vs. signal) ---
if (showSignalFill && showGravity) {
    var gravBull = gravitySmooth > signal
    plotLine(
        value=[gravitySmooth, signal],
        width=1,
        colors=[transparency(hotColor, 20), transparency(coldColor, 20)],
        colorIndex=gravBull ? 0 : 1,
        fill=true,
        label=["Gravity", "Signal"],
        desc=["Fill between gravity score and signal SMA"]
    )
}

// --- Individual Factor Lines (optional) ---
if (showFactors) {
    plotLine(
        value=normGravity,
        width=1,
        colors=["#ffd700"],
        label=["Intensity"],
        desc=["Liquidation intensity factor (0-100)"]
    )
    plotLine(
        value=normMomentum,
        width=1,
        colors=["#00e5ff"],
        label=["Momentum"],
        desc=["Momentum efficiency factor (0-100)"]
    )
    plotLine(
        value=normVolatility,
        width=1,
        colors=["#ff9100"],
        label=["Volatility"],
        desc=["Volatility anomaly factor (0-100)"]
    )
}

// --- Shape Markers ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=gravitySmooth,
            shape="triangleup",
            color=hotColor,
            width=2,
            label=["Gravity Cross Up"],
            desc=["Gravity score crossed above signal SMA"]
        )
    }
    if (crossDown) {
        plotShape(
            value=gravitySmooth,
            shape="triangledown",
            color=coldColor,
            width=2,
            label=["Gravity Cross Down"],
            desc=["Gravity score crossed below signal SMA"]
        )
    }
    if (hotEnter) {
        plotShape(
            value=gravitySmooth,
            shape="diamond",
            color=hotColor,
            width=3,
            label=["Hot Zone Enter"],
            desc=["Entered hot zone: liquidation cluster gravity well active"]
        )
    }
    if (coldEnter) {
        plotShape(
            value=gravitySmooth,
            shape="diamond",
            color=coldColor,
            width=3,
            label=["Cold Zone Enter"],
            desc=["Entered cold zone: low liquidation pressure"]
        )
    }
    if (hotExit) {
        plotShape(
            value=gravitySmooth,
            shape="circle",
            color=neutralColor,
            width=2,
            label=["Hot Zone Exit"],
            desc=["Exited hot zone"]
        )
    }
    if (coldExit) {
        plotShape(
            value=gravitySmooth,
            shape="circle",
            color=neutralColor,
            width=2,
            label=["Cold Zone Exit"],
            desc=["Exited cold zone"]
        )
    }
}

// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeHot ? "HOT ZONE" : (regimeCold ? "COLD ZONE" : "NEUTRAL")
    var regimeTextColor = regimeHot ? hotColor : (regimeCold ? coldColor : neutralColor)

    plotTable(
        data=[
            ["MAGNITO — Perfected", regimeText],
            ["Gravity Score", gravitySmooth[0]],
            ["Signal SMA", signal[0]],
            ["Intensity", normGravity[0]],
            ["Momentum", normMomentum[0]],
            ["Volatility", normVolatility[0]],
            ["Session High", sessionHighGravity],
            ["Session Low", sessionLowGravity],
            ["Regime Changes", regimeChangeCount],
            ["Hot Zone Bars", hotZoneCount],
            ["Cold Zone Bars", coldZoneCount]
        ],
        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
    )
}