MM Flow
FlowScripts

Perfected FlowScript

Funding Momentum

Funding Momentum — Perfected is indexed as 229_funding_momentum.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

12.4 KB

Lines

411

Native Signal Candidates

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

2/2 guarded

Extreme Long Crowding

line 350:5

Trigger

(showShapes && extremeLong)

Value

fundingExtreme

Deps

extremeLong:var, showShapes:input

Extreme Short Crowding

line 360:5

Trigger

(showShapes && extremeShort)

Value

-fundingExtreme

Deps

extremeShort:var, showShapes:input

229_funding_momentum.flowscript

source path: kscripts/perfected/229_funding_momentum.flowscript · sha256:d008e3e57555ac0cba769fd6a60694c099ff55c615e8424fc944d036494be1a7

hash verified
//@version=2
// ============================================================================
// Funding Momentum — Perfected Edition
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #funding, #momentum, #zscore, #regime, #perp
//
// Computes the rate of change in perpetual-futures funding rate, standardizes
// it via rolling z-score, and creates a momentum-style signal that detects
// positioning inflections before extremes appear in the raw rate. Funding
// momentum > 0 indicates widening long premium; < 0 indicates short premium
// building. Extremes flag crowdedness and potential reversions.
//
// Academic foundation:
//  1. He & Manela (2022/2024), "Fundamentals of Perpetual Futures", JFE
//     forthcoming, arXiv:2212.06888. First rigorous no-arbitrage analysis of
//     perp pricing; past-return momentum explains the futures-spot gap with
//     R² > 50%. Validates funding-rate momentum as a predictor of spot
//     returns and positioning pressure.
//
//  2. Kim & Park (2025), "Designing Funding Rates for Perpetual Futures in
//     Cryptocurrency Markets", arXiv:2506.08573. Path-dependent BSDE framework
//     for funding-rate design; motivates the smoothed-rate-of-change signal.
//
//  3. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications", Journal of Financial Economics, 22(1), 27–59. Mean-reversion
//     intensity varies with volatility; supports dynamic z-score thresholds.
//
//  4. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     JFEC 12(1), 47–88. [Formula] Δp_t = λ·OFI_t + ε_t. Funding momentum is
//     the perpetual-market analogue of order-flow imbalance: it proxies
//     taker-initiated net positioning.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  5. Sornette & Cauwels (2015), "Financial bubbles: mechanisms and diagnostics",
//     Swiss Finance Institute Research Paper No. 15-28. Extreme deviations from
//     historical norms (z-score > 2) as crash/flush indicators; maps directly to
//     funding-momentum extremes.
// ============================================================================

define(
    title="Funding Momentum — Perfected",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Data Sources --
var exchange = input(
    name="exchange",
    type="select",
    defaultValue="BINANCE_FUTURES",
    label="Exchange",
    options=["BINANCE_FUTURES", "BYBIT", "OKEX_SWAP", "DERIBIT", "HYPERLIQUID_FUTURES"],
    group="Data Sources"
)
var symbol = input(
    name="symbol",
    type="string",
    defaultValue="BTCUSDT",
    label="Symbol",
    group="Data Sources"
)

// -- Computation --
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=8,
    label="Funding Smooth Length",
    constraints={min: 1, max: 50, step: 1},
    group="Computation"
)
var momLen = input(
    name="momLen",
    type="number",
    defaultValue=1,
    label="Momentum Lookback",
    constraints={min: 1, max: 10, step: 1},
    group="Computation"
)
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Window",
    constraints={min: 20, max: 200, step: 5},
    group="Computation"
)
var momSmooth = input(
    name="momSmooth",
    type="number",
    defaultValue=3,
    label="Momentum EMA Smooth",
    constraints={min: 1, max: 20, step: 1},
    group="Computation"
)

// -- Thresholds --
var fundingExtreme = input(
    name="fundingExtreme",
    type="number",
    defaultValue=2.0,
    label="Extreme Z-Score Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.25},
    group="Thresholds"
)
var crowdedThreshold = input(
    name="crowdedThreshold",
    type="number",
    defaultValue=1.5,
    label="Crowded Threshold",
    constraints={min: 0.5, max: 3.0, step: 0.25},
    group="Thresholds"
)

// -- Display --
var showRaw = input(
    name="showRaw",
    type="boolean",
    defaultValue=false,
    label="Show Raw Funding",
    group="Display"
)
var showSmoothed = input(
    name="showSmoothed",
    type="boolean",
    defaultValue=false,
    label="Show Smoothed Funding",
    group="Display"
)
var showMomentum = input(
    name="showMomentum",
    type="boolean",
    defaultValue=true,
    label="Show Funding Momentum",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Funding Z-Score",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Shape Markers",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Fill Areas",
    group="Display"
)

// -- Colors --
var posColor = input(
    name="posColor",
    type="color",
    defaultValue="#26a69a",
    label="Positive Color",
    group="Colors"
)
var negColor = input(
    name="negColor",
    type="color",
    defaultValue="#ef5350",
    label="Negative Color",
    group="Colors"
)
var rawColor = input(
    name="rawColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Raw Funding Color",
    group="Colors"
)
var zColor = input(
    name="zColor",
    type="color",
    defaultValue="#42a5f5",
    label="Z-Score Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------

timeseries funding = source("funding_rate", symbol, exchange)

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

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Smoothed funding (SMA of raw funding rate) --
timeseries sm = sma(source=funding, period=smoothLen)

// -- 3.2 Momentum = change in smoothed funding (rate of change) --
// Positive momentum = funding is rising (longs getting more crowded / longs paying more).
// Negative momentum = funding is falling (shorts getting more crowded / shorts paying more).
timeseries momRaw = sm[0] - sm[momLen]
timeseries mom = ema(source=momRaw, period=momSmooth)

// -- 3.3 Z-score normalisation of funding rate (denominator guarded) --
// Z_t = (funding_t − μ_t) / σ_t; μ_t = SMA(funding, W), σ_t = StDev(funding, W).
timeseries fundMean = sma(source=funding, period=zWindow)
timeseries fundStd = stdev(source=funding, period=zWindow)
timeseries fundZ = (fundStd > 0) ? (funding - fundMean) / fundStd : 0

// -- 3.4 Momentum z-score (standardized momentum for regime classification) --
timeseries momMean = sma(source=mom, period=zWindow)
timeseries momStd = stdev(source=mom, period=zWindow)
timeseries momZ = (momStd > 0) ? (mom - momMean) / momStd : 0

// -- 3.5 Regime detection (multi-layer thresholds) --
// Funding regime: what is the funding rate doing on an absolute basis?
var fundBull = fundZ > crowdedThreshold       // longs crowded / funding very positive
var fundBear = fundZ < -crowdedThreshold      // shorts crowded / funding very negative
var fundNeutral = !fundBull && !fundBear

// Momentum regime: is the funding rate accelerating or decelerating?
var momBull = mom > 0   // funding momentum rising
var momBear = mom < 0   // funding momentum falling

// Extreme regime: extreme z-score divergence
var extremeLong = fundZ > fundingExtreme
var extremeShort = fundZ < -fundingExtreme

// -- 3.6 Zero line and histogram --
timeseries zeroLine = 0
timeseries hist = mom

// -- 3.7 Static regime tracking (consecutive bars) --
static lastMomRegime = 0
static momBullBars = 0
static momBearBars = 0
static lastFundRegime = 0
static fundBullBars = 0
static fundBearBars = 0

if (momBull) {
    momBullBars = momBullBars + 1
    momBearBars = 0
    lastMomRegime = 1
} else {
    momBearBars = momBearBars + 1
    momBullBars = 0
    lastMomRegime = -1
}

if (fundBull) {
    fundBullBars = fundBullBars + 1
    fundBearBars = 0
    lastFundRegime = 1
} else if (fundBear) {
    fundBearBars = fundBearBars + 1
    fundBullBars = 0
    lastFundRegime = -1
} else {
    fundBullBars = 0
    fundBearBars = 0
    lastFundRegime = 0
}

// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------

// 4.1 Raw funding (optional, for context)
if (showRaw) {
    plotLine(
        value=funding,
        colors=[rawColor],
        width=1,
        label=["Raw Funding"],
        desc=["Raw perpetual futures funding rate"]
    )
}

// 4.2 Smoothed funding (optional)
if (showSmoothed) {
    plotLine(
        value=sm,
        colors=[transparency(rawColor, 40)],
        width=1,
        label=["Smoothed Funding"],
        desc=["SMA(" + smoothLen + ") of raw funding rate"]
    )
}

// 4.3 Funding momentum (plotLine with color-coded fill)
if (showMomentum) {
    timeseries momColorIdx = momBull ? 0 : 1
    plotLine(
        value=([mom, zeroLine]),
        width=2,
        colors=[transparency(posColor, 40), transparency(negColor, 40)],
        colorIndex=momColorIdx,
        label=["Funding Momentum"],
        desc=["Rate of change in smoothed funding rate; rising = long premium building"],
        fill=showFill
    )
}

// 4.4 Funding z-score (plotLine)
if (showZScore) {
    plotLine(
        value=fundZ,
        colors=[zColor],
        width=2,
        label=["Funding Z-Score"],
        desc=["Z-score of funding rate over " + zWindow + " bars; ±" + fundingExtreme + " = extreme"]
    )
}

// 4.5 Momentum histogram (plotBar with sign-based color)
if (showHistogram) {
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(posColor, 60), transparency(negColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Momentum Histogram"],
        desc=["Funding momentum histogram; positive bars = rising funding / long crowding"]
    )
}

// 4.6 Extreme funding shapes (plotShape)
if (showShapes && extremeLong) {
    plotShape(
        value=fundingExtreme,
        shape="triangledown",
        colorIndex=negColor,
        width=3,
        label=["Extreme Long Crowding"],
        desc=["Funding z-score > +" + fundingExtreme + "; very positive funding = longs crowded; contrarian bearish"]
    )
}
if (showShapes && extremeShort) {
    plotShape(
        value=-fundingExtreme,
        shape="triangleup",
        colorIndex=posColor,
        width=3,
        label=["Extreme Short Crowding"],
        desc=["Funding z-score < -" + fundingExtreme + "; very negative funding = shorts crowded; contrarian bullish"]
    )
}

// 4.7 Reference lines
hline(value=0, color="#ffffff30", width=1)
if (showZScore) {
    hline(value=crowdedThreshold, color=transparency(posColor, 50), width=1)
    hline(value=-crowdedThreshold, color=transparency(negColor, 50), width=1)
    hline(value=fundingExtreme, color=transparency(posColor, 30), width=1)
    hline(value=-fundingExtreme, color=transparency(negColor, 30), width=1)
}

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var fundRegimeText = fundBull ? "LONGS CROWDED" : (fundBear ? "SHORTS CROWDED" : "NEUTRAL")
    var fundRegimeColor = fundBull ? negColor : (fundBear ? posColor : "#78909c")
    var momRegimeText = momBull ? "RISING" : "FALLING"
    var momRegimeColor = momBull ? posColor : negColor

    plotTable(
        data=[
            ["Funding Momentum — Perfected", fundRegimeText],
            ["Funding Z", fundZ[0]],
            ["Momentum", mom[0]],
            ["Mom Z", momZ[0]],
            ["Mom Regime", momRegimeText],
            ["Bull Bars", momBullBars],
            ["Bear Bars", momBearBars]
        ],
        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
    )
}