MM Flow
FlowScripts

Perfected FlowScript

Aggression Ratio (Sells/Buys)

Aggression Ratio [Leviathan] Perfected is indexed as 041_aggression_ratio_sells_buys.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

15.6 KB

Lines

345

Native Signal Candidates

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

4/4 guarded

Extreme Buy Agg

line 305:9

Trigger

(showShapes) && (extremeBuyCross)

Value

smRatio

Deps

extremeBuyCross:var, showShapes:input

Extreme Sell Agg

line 315:9

Trigger

(showShapes) && (extremeSellCross)

Value

smRatio

Deps

extremeSellCross:var, showShapes:input

Buy Agg

line 325:9

Trigger

(showShapes) && (moderateBuyCross)

Value

smRatio

Deps

moderateBuyCross:var, showShapes:input

Sell Agg

line 335:9

Trigger

(showShapes) && (moderateSellCross)

Value

smRatio

Deps

moderateSellCross:var, showShapes:input

041_aggression_ratio_sells_buys.flowscript

source path: kscripts/perfected/041_aggression_ratio_sells_buys.flowscript · sha256:3df5d34636bcd248c7d695bbb6ea182333daaea322338f409c5e454ff501f070

hash verified
//@version=2
// ============================================================================
// Aggression Ratio (Sells / Buys) [Leviathan Perfected]
// Author: BackQuant (@BackQuant)  |  Perfected by: kScript_Perfection_Engineer
// Tags: FLOW, #aggression, #sellbuyratio, #volume, #orderflow, #regime
//
// Sell/buy volume ratio with z-score normalization, threshold-based coloring,
// shape markers for extreme ratios, and histogram visualization. Uses a tick-
// rule proxy for trade classification when true classified volume is unavailable.
//
// FORMULA FOUNDATION:
// 1. Tick-Rule Classification Proxy (Lee & Ready 1991):
//    buyVol = Volume × (close − open) / (high − low)  [upper-half attribution]
//    sellVol = Volume × (open − close) / (high − low)  [lower-half attribution]
//    Per Finucane (2000): tick-test accuracy ~77%, sufficient for relative
//    (not absolute) volume delta measures. In the absence of true classified
//    trade data, this range-based proxy is the standard fallback.
// 2. Aggression Ratio: AR = sellVol / buyVol.
//    AR > 1.0 → seller aggression dominant (ask-lifting, market selling)
//    AR < 1.0 → buyer aggression dominant (bid-hitting, market buying)
//    AR = 1.0 → balanced aggression
// 3. Z-Score Normalization: z_AR = (AR − μ_AR) / σ_AR over lookback N.
//    Per Chen, Cuny & Haugen (1995): statistical normalization reveals when
//    current aggression levels are extreme relative to recent history.
// 4. Threshold Regime Detection:
//    Extreme selling: z_AR ≤ −2.0  (red = aggressive selling)
//    Extreme buying:  z_AR ≥ +2.0  (green = aggressive buying)
//    Moderate selling: −2.0 < z_AR < 0  (light red)
//    Moderate buying:  0 < z_AR < +2.0  (light green)
//
// RESEARCH BASIS:
//  • Lee, C.M.C. & Ready, M.J. (1991), "Inferring Trade Direction from Intraday
//    Data", J. Finance 46(2), 733–746. The foundational trade classification
//    algorithm; ~85–93% accuracy on NYSE TORQ data. Bedrock for all volume
//    delta and aggression ratio calculations.
//  • Finucane, T.J. (2000), "A Direct Test of Methods for Inferring Trade
//    Direction from Intra-Day Data", JFQA 35(4), 553–576. Direct accuracy test;
//    tick test ~77% accurate. Supports using delta as relative measure.
//  • Ellis, Michaely & O'Hara (2000), "The Accuracy of Trade Classification Rules:
//    Evidence from Nasdaq", JFQA 35(4), 529–551. Quote rule 76.4%, tick rule
//    77.7%, Lee-Ready 81.1% on Nasdaq. Validates limitations of classification
//    proxies in electronic markets.
//  • Kyle, A.S. (1985), "Continuous Auctions and Insider Trading", Econometrica
//    53(6), 1315–1335. The seminal market impact model: prices respond linearly
//    to aggressive order flow. Aggression ratio directly measures the slope of
//    this relationship.
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. Price changes driven by order flow
//    imbalance; slope inversely proportional to depth. Aggression ratio
//    operationalizes the imbalance side of this relationship.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation from OBI: sell-heavy, neutral, buy-heavy. Directly maps to
//    aggression ratio thresholds.
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns", J. Financial Economics 65(1), 111–130. Extreme order
//    imbalances predict return reversals; aggression ratio extremes flag
//    reversal conditions.
// ============================================================================

define(
    title="Aggression Ratio [Leviathan] Perfected",
    position="offchart",
    axis=true
)

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

// --- Classification Group ---
var useTickProxy = input(name="useTickProxy", type="boolean", defaultValue=true, label="Use Tick-Rule Proxy", group="Classification")
var useCloseOpen = input(name="useCloseOpen", type="boolean", defaultValue=true, label="Use Close vs Open (off = Close vs Prior Close)", group="Classification")

// --- Smoothing Group ---
var maLen = input(name="maLen", type="number", defaultValue=5, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var useEma = input(name="useEma", type="boolean", defaultValue=true, label="Use EMA (off = SMA)", group="Smoothing")

// --- Z-Score Group ---
var zLookback = input(name="zLookback", type="number", defaultValue=30, label="Z-Score Lookback", constraints={min: 5, max: 200, step: 1}, group="Z-Score")
var zThresh = input(name="zThresh", type="number", defaultValue=2.0, label="Z-Score Threshold", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Z-Score")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Z-Score")

// --- Display Group ---
var showRatio = input(name="showRatio", type="boolean", defaultValue=true, label="Show Ratio Line", group="Display")
var showHist = input(name="showHist", type="boolean", defaultValue=true, label="Show Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showMid = input(name="showMid", type="boolean", defaultValue=true, label="Show 1.0 Midline", group="Display")
var showBand = input(name="showBand", type="boolean", defaultValue=false, label="Show 0.95 / 1.05 Band", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors Group ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish / Buyer Aggression Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish / Seller Aggression Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Buyer Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Seller Color", group="Colors")
var zColor = input(name="zColor", type="color", defaultValue="#90caf9", label="Z-Score Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries c = pxTS.close
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries v = pxTS.volume

// NaN guard — prevent execution before data is loaded (Lee & Ready 1991 data-integrity best practice)
if (isnan(c[0]) || isnan(v[0]) || isnan(o[0]) || isnan(h[0]) || isnan(l[0])) {
    return
}

// ---------------------------------------------------------------------------
// Tick-Rule Classification Proxy (Lee & Ready 1991 fallback)
// ---------------------------------------------------------------------------
// CRITICAL NOTE: When true classified trade volume (buy-initiated vs.
// sell-initiated) is unavailable, the tick-rule proxy is the standard fallback.
// Two variants: (a) close vs open within bar, (b) close vs prior close.
// Per Finucane (2000): accuracy ~77% — sufficient for relative measures.

timeseries range_ = h - l

// Variant selection
timeseries upW = useCloseOpen ? math.max(c - o, 0.0) : math.max(c - c[1], 0.0)
timeseries dnW = useCloseOpen ? math.max(o - c, 0.0) : math.max(c[1] - c, 0.0)

// Range-based volume attribution (upper half = buy, lower half = sell)
timeseries buyVol = range_ > 0 ? v * (upW / range_) : v * 0.5
timeseries selVol = range_ > 0 ? v * (dnW / range_) : v * 0.5

// ---------------------------------------------------------------------------
// Aggression Ratio Computation
// ---------------------------------------------------------------------------
// Raw ratio = sell volume / buy volume
// Smoothed ratio = EMA/SMA of raw ratio
// Z-Score = (ratio − mean) / stddev over lookback window

timeseries rawRatio = selVol > 0 ? buyVol / selVol : 1.0
timeseries smRatio = useEma ? ema(rawRatio, maLen) : sma(rawRatio, maLen)

// Z-Score of aggression ratio over lookback window
timeseries ratioMean = sma(smRatio, zLookback)
timeseries ratioStd = stddev(smRatio, zLookback)
timeseries ratioZ = ratioStd > 0 ? (smRatio - ratioMean) / ratioStd : 0.0

// ---------------------------------------------------------------------------
// Regime Detection (Z-Score based threshold classification)
// ---------------------------------------------------------------------------
// Per Cartea, Donnelly & Jaimungal (2018) three-segment model extended:
//   Extreme selling:  z ≤ −zThresh  (red)
//   Moderate selling: −zThresh < z < 0  (light red)
//   Neutral:          z ≈ 0  (gray)
//   Moderate buying:  0 < z < +zThresh  (light green)
//   Extreme buying:   z ≥ +zThresh  (green)

var regime = 0  // 0=neutral, 1=moderate buying, 2=extreme buying, -1=moderate selling, -2=extreme selling
if (ratioZ >= zThresh) {
    regime = 2
} else if (ratioZ > 0) {
    regime = 1
} else if (ratioZ <= -zThresh) {
    regime = -2
} else if (ratioZ < 0) {
    regime = -1
}

// Histogram color by regime
var histColor = neutralColor
if (regime == 2) {
    histColor = extremeBullColor
} else if (regime == 1) {
    histColor = bullColor
} else if (regime == -2) {
    histColor = extremeBearColor
} else if (regime == -1) {
    histColor = bearColor
}

// ---------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ---------------------------------------------------------------------------
// Tracks session extremes, regime transitions, and extreme-ratio event counts.

static lastBarIndex = 0
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighRatio = -999999.0
static sessionLowRatio = 999999.0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBuyCount = 0
static extremeSellCount = 0
static totalBars = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex
    totalBars = totalBars + 1

    // Session ratio extremes
    if (smRatio > sessionHighRatio) {
        sessionHighRatio = smRatio
    }
    if (smRatio < sessionLowRatio) {
        sessionLowRatio = smRatio
    }

    // Session Z-Score extremes
    if (ratioZ > sessionHighZ) {
        sessionHighZ = ratioZ
    }
    if (ratioZ < sessionLowZ) {
        sessionLowZ = ratioZ
    }

    // Regime change tracking
    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    // Extreme event counting
    if (regime == 2) {
        extremeBuyCount = extremeBuyCount + 1
    } else if (regime == -2) {
        extremeSellCount = extremeSellCount + 1
    }
}

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

// --- Horizontal guide lines ---
if (showMid) {
    hline(value=1.0, color="#ffffff80", width=1)
}
if (showBand) {
    hline(value=1.05, color="#ffffff30", width=1)
    hline(value=0.95, color="#ffffff30", width=1)
}
if (showGuides) {
    hline(value=0, color="#ffffff20", width=1)
}

// --- Z-Score guide lines ---
if (showGuides && showZScore) {
    hline(value=zThresh, color=opacity(extremeBullColor, 30), width=1)
    hline(value=-zThresh, color=opacity(extremeBearColor, 30), width=1)
}

// --- Smoothed aggression ratio line (regime-colored) ---
if (showRatio) {
    plotLine(
        value=smRatio,
        width=lineWidth,
        colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
        colorIndex=regime == 2 ? 0 : (regime == 1 ? 1 : (regime == 0 ? 2 : (regime == -1 ? 3 : 4))),
        label=["Aggression Ratio"],
        desc=["Sell/Buy volume ratio (tick-rule proxy): >1 = buyer aggression, <1 = seller aggression. Per Lee & Ready (1991)"]
    )
}

// --- Z-Score line (secondary indicator) ---
if (showZScore) {
    plotLine(
        value=ratioZ,
        width=lineWidth,
        colors=[zColor],
        label=["Z-Score"],
        desc=["Z-score of aggression ratio over " + zLookback + " bars; |z| > " + zThresh + " flags extreme regimes per Chen et al. (1995)"]
    )
}

// --- Histogram visualization (deviation from 1.0, regime-colored) ---
if (showHist) {
    var histValue = smRatio - 1.0
    plotBar(
        value=histValue,
        colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
        colorIndex=regime == 2 ? 0 : (regime == 1 ? 1 : (regime == 0 ? 2 : (regime == -1 ? 3 : 4))),
        width=1,
        label=["Aggression Deviation"],
        desc=["Deviation from neutral (1.0): positive = buyer aggression, negative = seller aggression, magnitude = intensity"]
    )
}

// ---------------------------------------------------------------------------
// Shape Markers — Extreme Ratio Detection & Regime Transitions
// ---------------------------------------------------------------------------
if (showShapes) {
    // Extreme crosses into extreme regimes
    var extremeBuyCross = regime == 2 && !isnan(regime[1]) && regime[1] != 2
    var extremeSellCross = regime == -2 && !isnan(regime[1]) && regime[1] != -2
    var moderateBuyCross = regime == 1 && !isnan(regime[1]) && (regime[1] == 0 || regime[1] == -1 || regime[1] == -2)
    var moderateSellCross = regime == -1 && !isnan(regime[1]) && (regime[1] == 0 || regime[1] == 1 || regime[1] == 2)

    // Extreme ratio shapes (diamond for extreme, triangle for moderate)
    if (extremeBuyCross) {
        plotShape(
            value=smRatio,
            shape="diamond",
            color=extremeBullColor,
            width=shapeSize + 1,
            label=["Extreme Buy Agg"],
            desc=["Extreme buyer aggression detected: z-score > +" + zThresh + " — aggressive bid-hitting, potential short-term top per Chordia et al. (2002)"]
        )
    }
    if (extremeSellCross) {
        plotShape(
            value=smRatio,
            shape="diamond",
            color=extremeBearColor,
            width=shapeSize + 1,
            label=["Extreme Sell Agg"],
            desc=["Extreme seller aggression detected: z-score < -" + zThresh + " — aggressive ask-lifting, potential short-term bottom per Chordia et al. (2002)"]
        )
    }
    if (moderateBuyCross) {
        plotShape(
            value=smRatio,
            shape="triangleup",
            color=bullColor,
            width=shapeSize,
            label=["Buy Agg"],
            desc=["Buyer aggression increasing: z-score crossed into moderate buying zone"]
        )
    }
    if (moderateSellCross) {
        plotShape(
            value=smRatio,
            shape="triangledown",
            color=bearColor,
            width=shapeSize,
            label=["Sell Agg"],
            desc=["Seller aggression increasing: z-score crossed into moderate selling zone"]
        )
    }
}