MM Flow
FlowScripts

Perfected FlowScript

BTC Market Manipulation Detection Indicator

BTC Market Manipulation Detection V2 is indexed as 164_btc_market_manipulation_detection.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

19.7 KB

Lines

418

Native Signal Candidates

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

7/7 guarded

Suspicious

line 346:9

Trigger

(showShapes) && (crossSuspicious)

Value

smoothedZ

Deps

crossSuspicious:var, showShapes:input

Manipulation

line 356:9

Trigger

(showShapes) && (crossManipulation)

Value

smoothedZ

Deps

crossManipulation:var, showShapes:input

Extreme

line 366:9

Trigger

(showShapes) && (crossExtreme)

Value

smoothedZ

Deps

crossExtreme:var, showShapes:input

Spoofing

line 378:9

Trigger

(showShapes) && (spoofSignal)

Value

smoothedZ

Deps

showShapes:input, spoofSignal:var

Wash

line 388:9

Trigger

(showShapes) && (washSignal)

Value

smoothedZ

Deps

showShapes:input, washSignal:var

Pump/Dump

line 398:9

Trigger

(showShapes) && (pumpSignal)

Value

smoothedZ

Deps

pumpSignal:var, showShapes:input

Stop Hunt

line 408:9

Trigger

(showShapes) && (stopHuntSignal)

Value

smoothedZ

Deps

showShapes:input, stopHuntSignal:var

164_btc_market_manipulation_detection.flowscript

source path: kscripts/perfected/164_btc_market_manipulation_detection.flowscript · sha256:ff98f55fe693e1036e13e88400da22195cdef1e9028d19c8623bd384490be602

hash verified
//@version=2

// ============================================================================
// BTC Market Manipulation Detection V2 — Multi-Scheme Anomaly Scorer with Z-Score
// Author: L (@leader56) | Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, SPECIALIZED, #manipulation, #spoofing, #washtrading, #pumpdump
//
// Statistical manipulation detector combining four orthogonal manipulation
// signatures: spoofing (order book layer-and-cancel proxy), wash trading
// (volume anomaly with near-zero price impact), pump/dump (coordinated price
// spike + volume burst + wick rejection), and stop-hunting (wick beyond recent
// range + immediate reversal). Each component is z-standardised, weighted, and
// composited into a 0-100 anomaly score with regime-coded visualisation.
//
// FORMULA FOUNDATION:
// 1. Spoofing Score: measures rapid volume oscillation (volume spike followed by
//    immediate collapse) as a proxy for layered order placement and cancellation.
//    High cancel-to-trade ratio correlates with spoofing behaviour.
// 2. Wash Trading Score: volume anomaly Z > 2 combined with price impact/volume
//    ratio below threshold (large volume, minimal price movement). Fake volume
//    generates wash without moving the market.
// 3. Pump/Dump Score: price velocity Z > spikeThresh + volume anomaly + wick
//    rejection > wickRatio. Coordinated pump produces sharp spike with long wick
//    and immediate pullback (Li et al. 2019).
// 4. Stop Hunt Score: wick beyond ATR channel (wickZ > 2) + close back inside
//    range + volume spike. Engineered liquidity sweep targeting stop clusters.
//
// RESEARCH BASIS:
//  • Zhang et al. (2023), "Agent-based modeling of cooperative manipulation between
//    futures market and spot market", Physica A 615, 128562. Manipulation is a
//    rational, profitable strategy for large players; collusion increases profits.
//    DOI: 10.1016/j.physa.2023.128562
//  • Li, Shin & Wang (2019), "Cryptocurrency Pump-and-Dump Schemes", SSRN.
//    Pump-and-dump is organised via social media; price rises 65% in 5 minutes
//    on average, followed by 46% collapse within 24 hours.
//  • Cong, Li, Wang & Zhang (2018), "Crypto Wash Trading", SSRN. ~70% of reported
//    crypto volume on unregulated exchanges is fake; wash trading inflates prices
//    by 18.6% on average. DOI: 10.2139/ssrn.3539225
//  • Comerton-Forde & Putniņš (2011), "Measuring and Deterring Manipulation",
//    J. Financial Markets 14(3), 175-199. Trade-based manipulation metrics:
//    price deviation, volume distortion, and reversal patterns. Manipulation
//    leaves detectable statistical footprints in all three dimensions.
//    DOI: 10.1016/j.finmar.2011.03.002
//  • Kyle & Viswanathan (2008), "How to Define Illegal Price Manipulation",
//    American Economic Review 98(2), 274-279. Manipulation = actions that
//    would not be profitable absent the price effect on other traders.
// ============================================================================

define(
    title="BTC Market Manipulation Detection V2",
    position="offchart",
    axis=true
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Spoofing ---
var spoofVolOscThresh = input(name="spoofVolOscThresh", type="number", defaultValue=2.0, label="Spoofing Volume Oscillation Threshold (Z)", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Spoofing")
var spoofLookback = input(name="spoofLookback", type="number", defaultValue=10.0, label="Spoofing Lookback (bars)", constraints={min: 5.0, max: 50.0, step: 5.0}, group="Spoofing")

// --- Wash Trading ---
var washVolZThresh = input(name="washVolZThresh", type="number", defaultValue=2.0, label="Wash Volume Z Threshold", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Wash Trading")
var washImpactThresh = input(name="washImpactThresh", type="number", defaultValue=0.3, label="Wash Impact Ratio Threshold", constraints={min: 0.1, max: 1.0, step: 0.05}, group="Wash Trading")

// --- Pump/Dump ---
var pumpRetZThresh = input(name="pumpRetZThresh", type="number", defaultValue=2.5, label="Pump/Dump Return Z Threshold", constraints={min: 1.5, max: 5.0, step: 0.5}, group="Pump/Dump")
var pumpWickThresh = input(name="pumpWickThresh", type="number", defaultValue=0.6, label="Pump/Dump Wick Ratio Threshold", constraints={min: 0.3, max: 0.9, step: 0.05}, group="Pump/Dump")

// --- Stop Hunt ---
var stopHuntWickZThresh = input(name="stopHuntWickZThresh", type="number", defaultValue=2.0, label="Stop Hunt Wick Z Threshold", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Stop Hunt")
var stopHuntVolZThresh = input(name="stopHuntVolZThresh", type="number", defaultValue=1.5, label="Stop Hunt Volume Z Threshold", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Stop Hunt")

// --- Z-Score & Smoothing ---
var zWindow = input(name="zWindow", type="number", defaultValue=50.0, label="Z-Score Window (bars)", constraints={min: 20.0, max: 200.0, step: 5.0}, group="Z-Score")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5.0, label="Composite Smooth Length", constraints={min: 1.0, max: 20.0, step: 1.0}, group="Z-Score")

// --- Weights ---
var wSpoof = input(name="wSpoof", type="number", defaultValue=0.25, label="Weight: Spoofing", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var wWash = input(name="wWash", type="number", defaultValue=0.25, label="Weight: Wash Trading", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var wPump = input(name="wPump", type="number", defaultValue=0.25, label="Weight: Pump/Dump", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var wStop = input(name="wStop", type="number", defaultValue=0.25, label="Weight: Stop Hunt", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")

// --- Thresholds & Regime ---
var suspiciousThresh = input(name="suspiciousThresh", type="number", defaultValue=40.0, label="Suspicious Threshold", constraints={min: 20.0, max: 60.0, step: 5.0}, group="Thresholds")
var manipulationThresh = input(name="manipulationThresh", type="number", defaultValue=70.0, label="Manipulation Threshold", constraints={min: 50.0, max: 90.0, step: 5.0}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=85.0, label="Extreme Threshold", constraints={min: 70.0, max: 95.0, step: 5.0}, group="Thresholds")

// --- Display ---
var showRawScore = input(name="showRawScore", type="boolean", defaultValue=true, label="Show Raw Score Bar", group="Display")
var showZLine = input(name="showZLine", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showComponents = input(name="showComponents", type="boolean", defaultValue=false, label="Show Component Lines", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Manipulation Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")

// --- Colors ---
var normalColor = input(name="normalColor", type="color", defaultValue="#78909c", label="Normal Color", group="Colors")
var suspiciousColor = input(name="suspiciousColor", type="color", defaultValue="#ffa726", label="Suspicious Color", group="Colors")
var manipulationColor = input(name="manipulationColor", type="color", defaultValue="#ff5252", label="Manipulation Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#d50000", label="Extreme Color", group="Colors")
var lineColor = input(name="lineColor", type="color", defaultValue="#42a5f5", label="Z-Line Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = priceBars.close
timeseries open = priceBars.open
timeseries high = priceBars.high
timeseries low = priceBars.low
timeseries volume = priceBars.volume

// NaN guard — prevent execution before data is loaded
if (isnan(close[0]) || isnan(volume[0])) {
    return
}

// ------------------------------------------------------------------------------
// Component 1: Spoofing Detection (Layer-and-Cancel Proxy)
// ------------------------------------------------------------------------------
// Spoofing manifests as rapid order placement and cancellation. We approximate
// this via volume oscillation: a volume spike followed by an immediate collapse
// (volume today >> volume yesterday, then volume tomorrow << volume today).
// Comerton-Forde & Putniņš (2011): manipulators distort volume patterns.
timeseries volChange = math.abs(volume - volume[1]) / math.max(volume[1], 1.0)
timeseries volOscMean = sma(volChange, spoofLookback)
timeseries volOscStd = stdev(volChange, spoofLookback)
timeseries volOscZ = (volOscStd > 0) ? (volChange - volOscMean) / volOscStd : 0.0
var spoofSignal = volOscZ > spoofVolOscThresh && volume > volume[1] && volume[1] < volume[2]
timeseries spoofScore = spoofSignal ? math.min(volOscZ * 20.0, 50.0) : 0.0

// ------------------------------------------------------------------------------
// Component 2: Wash Trading Detection (Fake Volume with Low Price Impact)
// ------------------------------------------------------------------------------
// Cong et al. (2018): ~70% of crypto volume is fake; wash trading produces
// volume without moving price. Detected by volume Z > threshold combined with
// abnormally low price impact per unit volume.
timeseries volMean = sma(volume, zWindow)
timeseries volStd = stdev(volume, zWindow)
timeseries volZ = (volStd > 0) ? (volume - volMean) / volStd : 0.0

timeseries barRange = high - low
timeseries impactPerVol = barRange / math.max(volume, 1.0)
timeseries impactMean = sma(impactPerVol, zWindow)
timeseries impactStd = stdev(impactPerVol, zWindow)
timeseries impactZ = (impactStd > 0) ? (impactPerVol - impactMean) / impactStd : 0.0

var washSignal = volZ > washVolZThresh && impactPerVol < washImpactThresh * impactMean
timeseries washScore = washSignal ? math.min(volZ * 15.0 + math.abs(impactZ) * 10.0, 50.0) : 0.0

// ------------------------------------------------------------------------------
// Component 3: Pump/Dump Detection (Coordinated Spike + Wick + Volume)
// ------------------------------------------------------------------------------
// Li et al. (2019): pumps produce 65% price rise in 5 minutes followed by 46%
// collapse. Detected by return Z > threshold, volume spike, and wick rejection.
timeseries ret1 = (close - close[1]) / math.max(close[1], 0.0001)
timeseries retMean = sma(ret1, zWindow)
timeseries retStd = stdev(ret1, zWindow)
timeseries retZ = (retStd > 0) ? (ret1 - retMean) / retStd : 0.0

timeseries rng = math.max(high - low, 0.0001)
timeseries upperWick = high - math.max(close, open)
timeseries lowerWick = math.min(close, open) - low
timeseries maxWick = math.max(upperWick, lowerWick)
timeseries wickRatio = maxWick / rng

var pumpSignal = math.abs(retZ) > pumpRetZThresh && volZ > 1.0 && wickRatio > pumpWickThresh
timeseries pumpScore = pumpSignal ? math.min(math.abs(retZ) * 15.0 + volZ * 10.0 + wickRatio * 10.0, 50.0) : 0.0

// ------------------------------------------------------------------------------
// Component 4: Stop Hunt Detection (Wick Beyond Range + Reversal + Volume)
// ------------------------------------------------------------------------------
// Zhang et al. (2023): stop-loss exploitation is a rational profitable strategy.
// Engineered wick beyond recent ATR channel, immediate close back inside, with
// volume spike — classic stop-hunt fingerprint.
timeseries atrVal = atr(14)
timeseries upperChannel = close[1] + 2.0 * atrVal
timeseries lowerChannel = close[1] - 2.0 * atrVal

timeseries wickBeyond = math.max(high - upperChannel, lowerChannel - low)
timeseries wickBeyondMean = sma(wickBeyond, zWindow)
timeseries wickBeyondStd = stdev(wickBeyond, zWindow)
timeseries wickZ = (wickBeyondStd > 0) ? (wickBeyond - wickBeyondMean) / wickBeyondStd : 0.0

var stopHuntSignal = wickZ > stopHuntWickZThresh && volZ > stopHuntVolZThresh && close > low && close < high
timeseries stopScore = stopHuntSignal ? math.min(wickZ * 15.0 + volZ * 10.0, 50.0) : 0.0

// ------------------------------------------------------------------------------
// Composite Anomaly Score (0-100)
// ------------------------------------------------------------------------------
timeseries rawScore = wSpoof * spoofScore + wWash * washScore + wPump * pumpScore + wStop * stopScore
timeseries score = ema(rawScore, smoothLen)
timeseries finalScore = math.min(math.max(score, 0.0), 100.0)

// ------------------------------------------------------------------------------
// Z-Score Normalisation of Composite Score
// ------------------------------------------------------------------------------
timeseries scoreMean = sma(finalScore, zWindow)
timeseries scoreStd = stdev(finalScore, zWindow)
timeseries scoreZ = (scoreStd > 0) ? (finalScore - scoreMean) / scoreStd : 0.0
timeseries smoothedZ = ema(scoreZ, smoothLen)

// ------------------------------------------------------------------------------
// Regime Detection (four-segment: normal / suspicious / manipulation / extreme)
// ------------------------------------------------------------------------------
var regime = 0      // 0 = normal, 1 = suspicious, -1 = manipulation
var extremeRegime = 0  // 0 = normal, 1 = extreme manipulation

if (finalScore >= manipulationThresh) {
    regime = -1
} else if (finalScore >= suspiciousThresh) {
    regime = 1
}

if (finalScore >= extremeThresh) {
    extremeRegime = 1
}

// ------------------------------------------------------------------------------
// Static State Tracking — Manipulation Event Persistence
// ------------------------------------------------------------------------------
// Tracks manipulation event counts, session extremes, and scheme-specific counters
// for forensic context and session-level anomaly reporting.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighScore = -999999.0
static sessionLowScore = 999999.0
static extremeCount = 0
static spoofCount = 0
static washCount = 0
static pumpCount = 0
static stopHuntCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (finalScore > sessionHighScore) {
        sessionHighScore = finalScore
    }
    if (finalScore < sessionLowScore) {
        sessionLowScore = finalScore
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (extremeRegime == 1) {
        extremeCount = extremeCount + 1
    }
    if (spoofSignal) {
        spoofCount = spoofCount + 1
    }
    if (washSignal) {
        washCount = washCount + 1
    }
    if (pumpSignal) {
        pumpCount = pumpCount + 1
    }
    if (stopHuntSignal) {
        stopHuntCount = stopHuntCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, HLine)
// ------------------------------------------------------------------------------

// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)

if (showGuides) {
    hline(value=suspiciousThresh, color=opacity(suspiciousColor, 30), width=1)
    hline(value=manipulationThresh, color=opacity(manipulationColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(extremeColor, 20), width=1)
}

// Raw composite score as histogram bars (0-100 scale)
if (showRawScore) {
    plotBar(
        value=finalScore,
        colors=[normalColor, suspiciousColor, manipulationColor],
        width=1,
        label=["Anomaly Score"],
        desc=["Composite manipulation probability (0-100); higher = more suspicious"]
    )
}

// Z-score line with regime-coded fill area
if (showZLine) {
    plotLine(
        value=smoothedZ,
        width=2,
        colors=[normalColor, suspiciousColor, manipulationColor, extremeColor],
        colorIndex=extremeRegime == 1 ? 3 : (regime == -1 ? 2 : (regime == 1 ? 1 : 0)),
        label=["Anomaly Z-Score"],
        desc=["Z-standardised manipulation score; regime-coded: normal/suspicious/manipulation/extreme"],
        fill=true
    )
}

// Optional component lines (diagnostic)
if (showComponents) {
    plotLine(
        value=spoofScore,
        width=1,
        colors=["#9c27b0"],
        label=["Spoofing"],
        desc=["Spoofing component score — rapid volume oscillation proxy"]
    )
    plotLine(
        value=washScore,
        width=1,
        colors=["#00bcd4"],
        label=["Wash Trading"],
        desc=["Wash trading component score — high volume, low impact"]
    )
    plotLine(
        value=pumpScore,
        width=1,
        colors=["#ff9800"],
        label=["Pump/Dump"],
        desc=["Pump/dump component score — coordinated spike + wick"]
    )
    plotLine(
        value=stopScore,
        width=1,
        colors=["#e91e63"],
        label=["Stop Hunt"],
        desc=["Stop hunt component score — wick beyond range + reversal"]
    )
}

// Manipulation event shapes — scheme-specific markers
if (showShapes) {
    var crossSuspicious = finalScore >= suspiciousThresh && !isnan(finalScore[1]) && finalScore[1] < suspiciousThresh
    var crossManipulation = finalScore >= manipulationThresh && !isnan(finalScore[1]) && finalScore[1] < manipulationThresh
    var crossExtreme = finalScore >= extremeThresh && !isnan(finalScore[1]) && finalScore[1] < extremeThresh

    if (crossSuspicious) {
        plotShape(
            value=smoothedZ,
            shape="triangleup",
            color=suspiciousColor,
            width=3,
            label=["Suspicious"],
            desc=["Score crossed into suspicious regime — one or more manipulation signatures detected"]
        )
    }
    if (crossManipulation) {
        plotShape(
            value=smoothedZ,
            shape="triangledown",
            color=manipulationColor,
            width=3,
            label=["Manipulation"],
            desc=["Score crossed into manipulation regime — strong statistical anomaly detected"]
        )
    }
    if (crossExtreme) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremeColor,
            width=4,
            label=["Extreme"],
            desc=["Extreme manipulation event — multiple coincident signatures (Comerton-Forde 2011)"]
        )
    }

    // Scheme-specific shape markers at the event bar
    if (spoofSignal) {
        plotShape(
            value=smoothedZ,
            shape="circle",
            color="#9c27b0",
            width=3,
            label=["Spoofing"],
            desc=["Spoofing signature: rapid volume oscillation suggesting layer-and-cancel"]
        )
    }
    if (washSignal) {
        plotShape(
            value=smoothedZ,
            shape="circle",
            color="#00bcd4",
            width=3,
            label=["Wash"],
            desc=["Wash trading signature: high volume with abnormally low price impact (Cong et al. 2018)"]
        )
    }
    if (pumpSignal) {
        plotShape(
            value=smoothedZ,
            shape="circle",
            color="#ff9800",
            width=3,
            label=["Pump/Dump"],
            desc=["Pump/dump signature: coordinated spike + wick rejection (Li et al. 2019)"]
        )
    }
    if (stopHuntSignal) {
        plotShape(
            value=smoothedZ,
            shape="circle",
            color="#e91e63",
            width=3,
            label=["Stop Hunt"],
            desc=["Stop hunt signature: engineered wick beyond ATR channel + immediate reversal"]
        )
    }
}