MM Flow
FlowScripts

Perfected FlowScript

Funding Rate Z-Score

Funding Rate Z-Score V2 is indexed as 116_funding_rate_z_score.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.9 KB

Lines

493

Native Signal Candidates

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

12/12 guarded

Zero Cross Up

line 373:9

Trigger

(showShapes) && (crossUpZero)

Value

zFinal

Deps

crossUpZero:var, showShapes:input

Zero Cross Down

line 383:9

Trigger

(showShapes) && (crossDnZero)

Value

zFinal

Deps

crossDnZero:var, showShapes:input

Crowded Long

line 393:9

Trigger

(showShapes) && (crossUp)

Value

zFinal

Deps

crossUp:var, showShapes:input

Crowded Short

line 403:9

Trigger

(showShapes) && (crossDn)

Value

zFinal

Deps

crossDn:var, showShapes:input

Extreme Long Crowding

line 413:9

Trigger

(showShapes) && (extremeUp)

Value

zFinal

Deps

extremeUp:var, showShapes:input

Extreme Short Crowding

line 423:9

Trigger

(showShapes) && (extremeDn)

Value

zFinal

Deps

extremeDn:var, showShapes:input

+1σ Touch

line 433:9

Trigger

(showShapes) && (touchBand1Hi)

Value

zFinal

Deps

showShapes:input, touchBand1Hi:var

-1σ Touch

line 443:9

Trigger

(showShapes) && (touchBand1Lo)

Value

zFinal

Deps

showShapes:input, touchBand1Lo:var

+2σ Touch

line 453:9

Trigger

(showShapes) && (touchBand2Hi)

Value

zFinal

Deps

showShapes:input, touchBand2Hi:var

-2σ Touch

line 463:9

Trigger

(showShapes) && (touchBand2Lo)

Value

zFinal

Deps

showShapes:input, touchBand2Lo:var

+3σ Touch

line 473:9

Trigger

(showShapes) && (touchBand3Hi)

Value

zFinal

Deps

showShapes:input, touchBand3Hi:var

-3σ Touch

line 483:9

Trigger

(showShapes) && (touchBand3Lo)

Value

zFinal

Deps

showShapes:input, touchBand3Lo:var

116_funding_rate_z_score.flowscript

source path: kscripts/perfected/116_funding_rate_z_score.flowscript · sha256:839a210cdcd4446f66cfa639dce2909a0498c768f04269c48063f8f7275497ee

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// Funding Rate Z-Score V2 — Multi-Venue Funding with ±1/2/3σ Bands & Regime Detection
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: FLOW, #funding, #perps, #zscore, #crowding, #contrarian, #basis
//
// Standardizes funding-rate dynamics across multiple perpetual venues into a
// rolling z-score with ±1/2/3σ bands, fill visualization, and regime detection.
// Two modes: Delta (per-bar change, captures inflections) and Level (cumulative
// vs. mean, captures sustained bias). Shape markers flag extremes and band
// touches for contrarian timing.
//
// FORMULA FOUNDATION:
// 1. Multi-Venue Aggregation: weighted average of funding rates across
//    Binance, Bybit, OKX, Deribit per Gornall & Strebulaev (2025) basis-risk
//    framework. Perpetual futures dominate crypto derivatives liquidity.
// 2. Z-Score: z = (FR − μ) / σ over rolling window. Zhao & Palomar (2018):
//    z-score event triggers for statistical arbitrage and mean-reversion.
// 3. Sigma Bands: ±1σ (~68%), ±2σ (~95%), ±3σ (~99.7%) for statistical
//    rarity assessment. Extreme z > +3σ or z < −3σ flags cascade risk.
// 4. Regime Detection: Positive z = long crowding (contrarian short bias);
//    Negative z = short crowding (contrarian long bias). CoinxSight (2026)
//    thresholds: >+0.05% FR = overcrowded long; <−0.05% = overcrowded short.
// 5. He & Manela (2022): past-return momentum explains futures-spot gap with
//    R² > 50%; high past returns → futures premium → positive funding.
//
// RESEARCH BASIS:
//  • He & Manela (2022), "Fundamentals of Perpetual Futures", J. Financial
//    Economics (forthcoming); arXiv:2212.06888. No-arbitrage bounds for
//    perpetual futures; momentum-funding relationship with R² > 50%.
//  • Kim & Park (2025), "Designing Funding Rates for Perpetual Futures",
//    arXiv:2506.08573. Path-dependent BSDE funding design; 8h-averaged
//    rates align perp prices with spot targets.
//  • Zhao & Palomar (2018), "Mean-Reversion Portfolio Optimization", IEEE.
//    Z-score event triggers as mean-reversion signals; statistical rarity
//    thresholds for contrarian positioning.
//  • CoinxSight (2026), "Funding Rate: The Cost of Being Crowded". Extreme
//    funding (>+0.05% or <−0.05%) is contrarian; funding is a "risk
//    temperature" gauge, not a precise timing tool.
//  • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
//    Rev. Financial Studies 22(6), 2201–2238. Liquidity spirals: funding stress
//    and extreme positioning amplify into systemic crises.
//  • Gornall & Strebulaev (2025), "Perpetual Futures and Basis Risk".
//    Perpetual futures have lower effective spreads than quarterly; superior
//    data source for real-time funding analysis.
// ============================================================================

define(
    title="Funding Rate Z-Score V2",
    position="offchart",
    axis=true
)

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

// --- Z-Score Window ---
var win = input(name="win", type="number", defaultValue=72, label="Rolling Window (bars)", constraints={min: 10, max: 500, step: 1}, group="Z-Score")
var mode = input(name="mode", type="select", defaultValue="Delta", label="Mode", options=["Delta", "Level"], group="Z-Score")
var smoothType = input(name="smoothType", type="select", defaultValue="EMA", label="Smoothing Type", options=["None", "SMA", "EMA"], group="Z-Score")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Z-Score")

// --- Bands ---
var showBand1 = input(name="showBand1", type="boolean", defaultValue=true, label="Show ±1σ Band", group="Bands")
var showBand2 = input(name="showBand2", type="boolean", defaultValue=true, label="Show ±2σ Band", group="Bands")
var showBand3 = input(name="showBand3", type="boolean", defaultValue=false, label="Show ±3σ Band", group="Bands")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Band Fills", group="Bands")

// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=1.0, label="Bullish Regime Threshold (σ)", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Regime Threshold (σ)", constraints={min: -3.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Threshold (σ)", constraints={min: 1.5, max: 4.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showRawLine = input(name="showRawLine", type="boolean", defaultValue=true, label="Show Raw Z-Score Line", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showZero = input(name="showZero", type="boolean", defaultValue=true, label="Show Zero Line", group="Display")
var showFundingCtx = input(name="showFundingCtx", type="boolean", defaultValue=false, label="Show Funding Rate Context", 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 ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Positive/Crowded Long Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Negative/Crowded Short 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 Positive Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Negative Color", group="Colors")
var band1Color = input(name="band1Color", type="color", defaultValue="#9e9e9e", label="±1σ Band Color", group="Colors")
var band2Color = input(name="band2Color", type="color", defaultValue="#757575", label="±2σ Band Color", group="Colors")
var band3Color = input(name="band3Color", type="color", defaultValue="#616161", label="±3σ Band Color", group="Colors")
var fundingCtxColor = input(name="fundingCtxColor", type="color", defaultValue="#ffa726", label="Funding Context Color", group="Colors")

// -----------------------------------------------------------------------------
// Data Sources — Multi-venue funding aggregation
// -----------------------------------------------------------------------------
// Pull funding rate from multiple perp venues and average (equal weights).
// Gornall & Strebulaev (2025): perpetual futures have superior liquidity
// characteristics vs. quarterly; multi-venue averaging reduces idiosyncratic noise.

timeseries f1 = funding_rate(symbol="BTCUSDT", exchange="BINANCE_FUTURES")
timeseries f2 = funding_rate(symbol="BTCUSDT", exchange="BYBIT")
timeseries f3 = funding_rate(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")
timeseries f4 = funding_rate(symbol="BTC-PERPETUAL", exchange="DERIBIT")

// NaN guard — prevent execution before data is loaded
if (isnan(f1[0]) || isnan(f2[0]) || isnan(f3[0]) || isnan(f4[0])) {
    return
}

// Equal-weighted composite funding rate across venues
timeseries funding = (f1 + f2 + f3 + f4) / 4.0

// -----------------------------------------------------------------------------
// Derived Series — Delta vs Level Mode
// -----------------------------------------------------------------------------
// Delta mode: per-bar change in funding (captures inflections / regime shifts)
// Level mode: cumulative funding vs. recent mean (captures sustained bias)

// Cumulative funding (Level mode)
static cumFunding = 0.0
cumFunding = nz(cumFunding) + funding

// Per-bar change (Delta mode)
timeseries dFunding = funding - nz(funding[1])

// Choose active series based on mode
timeseries baseSeries = (mode == "Delta") ? dFunding : cumFunding

// -----------------------------------------------------------------------------
// Z-Score Computation (Zhao & Palomar 2018)
// -----------------------------------------------------------------------------
// Rolling mean and standard deviation over 'win' bars.
// z = (x − μ) / σ, with zero-division guard.

timeseries mean = sma(baseSeries, win)
timeseries stdev = stdev(baseSeries, win)
timeseries zRaw = stdev > 1e-9 ? (baseSeries - mean) / stdev : 0.0

// Smoothing (None / SMA / EMA)
timeseries zFinal = zRaw
if (smoothType == "SMA") {
    zFinal = sma(zRaw, smoothLen)
} else if (smoothType == "EMA") {
    zFinal = ema(zRaw, smoothLen)
}

// -----------------------------------------------------------------------------
// Regime Detection (CoinxSight 2026 contrarian framework)
// -----------------------------------------------------------------------------
//   Positive z = long crowding (perp funding above average) → contrarian short
//   Negative z = short crowding (perp funding below average) → contrarian long
//   Neutral = within ±1σ → no strong signal
//
// Segmented into three regimes plus extreme flag:
//   Crowded Long:   z ≥ bullThresh
//   Crowded Short:  z ≤ bearThresh
//   Neutral:        bearThresh < z < bullThresh

var regime = 0      // 0 = neutral, 1 = crowded long, -1 = crowded short
var extremeRegime = 0  // 0 = normal, 1 = extreme long, -1 = extreme short

if (zFinal >= bullThresh) {
    regime = 1
} else if (zFinal <= bearThresh) {
    regime = -1
}

if (zFinal >= extremeThresh) {
    extremeRegime = 1
} else if (zFinal <= -extremeThresh) {
    extremeRegime = -1
}

// -----------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// -----------------------------------------------------------------------------
// Stateful computation for session extremes, regime transitions, and
// extreme-event counters. Tracks the statistical history of funding z-scores.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static sessionHighFunding = -999999.0
static sessionLowFunding = 999999.0
static extremeLongCount = 0
static extremeShortCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    // New bar — update session tracking
    lastBarIndex = currentBarIndex

    if (zFinal > sessionHighZ) {
        sessionHighZ = zFinal
    }
    if (zFinal < sessionLowZ) {
        sessionLowZ = zFinal
    }
    if (funding > sessionHighFunding) {
        sessionHighFunding = funding
    }
    if (funding < sessionLowFunding) {
        sessionLowFunding = funding
    }

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

    if (extremeRegime == 1) {
        extremeLongCount = extremeLongCount + 1
    } else if (extremeRegime == -1) {
        extremeShortCount = extremeShortCount + 1
    }
}

// -----------------------------------------------------------------------------
// Sigma Band Construction (Zhao & Palomar 2018 statistical thresholds)
// -----------------------------------------------------------------------------
// ±1σ, ±2σ, ±3σ bands for statistical rarity assessment.
// ~68.2% within ±1σ, ~95.4% within ±2σ, ~99.7% within ±3σ.

timeseries band1Hi = bullThresh
timeseries band1Lo = bearThresh
timeseries band2Hi = extremeThresh
timeseries band2Lo = -extremeThresh
timeseries band3Hi = extremeThresh + (extremeThresh - bullThresh)
timeseries band3Lo = -extremeThresh - (extremeThresh - bullThresh)

// Band touch detection for shape markers
var touchBand1Hi = zFinal >= band1Hi && !isnan(zFinal[1]) && zFinal[1] < band1Hi
var touchBand1Lo = zFinal <= band1Lo && !isnan(zFinal[1]) && zFinal[1] > band1Lo
var touchBand2Hi = zFinal >= band2Hi && !isnan(zFinal[1]) && zFinal[1] < band2Hi
var touchBand2Lo = zFinal <= band2Lo && !isnan(zFinal[1]) && zFinal[1] > band2Lo
var touchBand3Hi = zFinal >= band3Hi && !isnan(zFinal[1]) && zFinal[1] < band3Hi
var touchBand3Lo = zFinal <= band3Lo && !isnan(zFinal[1]) && zFinal[1] > band3Lo

// Cross zero detection
var crossUpZero = zFinal >= 0 && !isnan(zFinal[1]) && zFinal[1] < 0
var crossDnZero = zFinal <= 0 && !isnan(zFinal[1]) && zFinal[1] > 0

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

// Horizontal guide lines — zero line and threshold zones
if (showZero) {
    hline(value=0, color="#ffffff30", width=1)
}

hline(value=bullThresh, color=opacity(bullColor, 30), width=1)
hline(value=bearThresh, color=opacity(bearColor, 30), width=1)
hline(value=extremeThresh, color=opacity(extremeBullColor, 20), width=1)
hline(value=-extremeThresh, color=opacity(extremeBearColor, 20), width=1)

// --- Raw Z-Score Line (regime-colored) ---
if (showRawLine) {
    plotLine(
        value=zFinal,
        width=lineWidth,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        fill=true,
        label=["Funding Z"],
        desc=["Rolling z-score of funding rate. Regime: crowded long/short/neutral"]
    )
}

// --- Funding Rate Context (optional, raw funding rate scaled) ---
if (showFundingCtx) {
    // Scale funding rate to z-score axis for visual comparison
    timeseries fundingScaled = funding * 1000.0  // rough scale for visualization
    plotLine(
        value=fundingScaled,
        width=1,
        colors=[fundingCtxColor],
        label=["Funding Rate (×1000)"],
        desc=["Raw composite funding rate scaled to z-axis for context"]
    )
}

// --- ±1σ Band Fill & Lines ---
if (showBand1) {
    if (showFill) {
        plotLine(
            value=([band1Lo, band1Hi]),
            width=1,
            colors=[opacity(bullColor, 15), opacity(bearColor, 15)],
            colorIndex=regime == 1 ? 0 : 1,
            fill=true,
            label=["±1σ Fill"],
            desc=["±1σ band fill (regime-colored) — ~68% containment"]
        )
    }
    plotLine(
        value=band1Hi,
        width=1,
        colors=[band1Color],
        label=["+1σ"],
        desc=["Upper band at +1σ threshold"]
    )
    plotLine(
        value=band1Lo,
        width=1,
        colors=[band1Color],
        label=["-1σ"],
        desc=["Lower band at -1σ threshold"]
    )
}

// --- ±2σ Band Fill & Lines ---
if (showBand2) {
    if (showFill) {
        plotLine(
            value=([band2Lo, band2Hi]),
            width=1,
            colors=[opacity(bullColor, 10), opacity(bearColor, 10)],
            colorIndex=regime == 1 ? 0 : 1,
            fill=true,
            label=["±2σ Fill"],
            desc=["±2σ band fill (regime-colored) — ~95% containment"]
        )
    }
    plotLine(
        value=band2Hi,
        width=1,
        colors=[band2Color],
        label=["+2σ"],
        desc=["Upper band at +2σ extreme threshold"]
    )
    plotLine(
        value=band2Lo,
        width=1,
        colors=[band2Color],
        label=["-2σ"],
        desc=["Lower band at -2σ extreme threshold"]
    )
}

// --- ±3σ Band Lines ---
if (showBand3) {
    plotLine(
        value=band3Hi,
        width=1,
        colors=[band3Color],
        label=["+3σ"],
        desc=["Upper band at +3σ — statistical rarity ~99.7%"]
    )
    plotLine(
        value=band3Lo,
        width=1,
        colors=[band3Color],
        label=["-3σ"],
        desc=["Lower band at -3σ — statistical rarity ~99.7%"]
    )
}

// --- Regime Transition & Extreme Shapes ---
if (showShapes) {
    var crossUp = zFinal >= bullThresh && !isnan(zFinal[1]) && zFinal[1] < bullThresh
    var crossDn = zFinal <= bearThresh && !isnan(zFinal[1]) && zFinal[1] > bearThresh
    var extremeUp = zFinal >= extremeThresh && !isnan(zFinal[1]) && zFinal[1] < extremeThresh
    var extremeDn = zFinal <= -extremeThresh && !isnan(zFinal[1]) && zFinal[1] > -extremeThresh

    if (crossUpZero) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=bullColor,
            width=shapeSize,
            label=["Zero Cross Up"],
            desc=["Funding z-score crossed above zero — funding turning positive"]
        )
    }
    if (crossDnZero) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=bearColor,
            width=shapeSize,
            label=["Zero Cross Down"],
            desc=["Funding z-score crossed below zero — funding turning negative"]
        )
    }
    if (crossUp) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=extremeBullColor,
            width=shapeSize,
            label=["Crowded Long"],
            desc=["Funding z-score crossed into crowded-long regime — contrarian short bias"]
        )
    }
    if (crossDn) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=extremeBearColor,
            width=shapeSize,
            label=["Crowded Short"],
            desc=["Funding z-score crossed into crowded-short regime — contrarian long bias"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=zFinal,
            shape="diamond",
            color=extremeBullColor,
            width=shapeSize + 1,
            label=["Extreme Long Crowding"],
            desc=["Extreme funding z-score — severely overcrowded longs, high correction risk"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=zFinal,
            shape="diamond",
            color=extremeBearColor,
            width=shapeSize + 1,
            label=["Extreme Short Crowding"],
            desc=["Extreme funding z-score — severely overcrowded shorts, high squeeze risk"]
        )
    }
    if (touchBand1Hi) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=band1Color,
            width=shapeSize,
            label=["+1σ Touch"],
            desc=["Funding z-score touched +1σ band"]
        )
    }
    if (touchBand1Lo) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=band1Color,
            width=shapeSize,
            label=["-1σ Touch"],
            desc=["Funding z-score touched -1σ band"]
        )
    }
    if (touchBand2Hi) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=band2Color,
            width=shapeSize,
            label=["+2σ Touch"],
            desc=["Funding z-score touched +2σ band — statistical extreme"]
        )
    }
    if (touchBand2Lo) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=band2Color,
            width=shapeSize,
            label=["-2σ Touch"],
            desc=["Funding z-score touched -2σ band — statistical extreme"]
        )
    }
    if (touchBand3Hi) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=band3Color,
            width=shapeSize + 1,
            label=["+3σ Touch"],
            desc=["Funding z-score touched +3σ band — rare event, cascade risk"]
        )
    }
    if (touchBand3Lo) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=band3Color,
            width=shapeSize + 1,
            label=["-3σ Touch"],
            desc=["Funding z-score touched -3σ band — rare event, squeeze risk"]
        )
    }
}