MM Flow
FlowScripts

Perfected FlowScript

Detrend Aggr Open Interest Delta

BTC Agg OI Delta detrend is indexed as 278_detrend_aggr_open_interest_delta.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

9.0 KB

Lines

246

Native Signal Candidates

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

0/2 guarded

Agg OI Delta cross up buy

line 155:1

Trigger

coreRaw > ma && coreRaw[1] <= ma[1]

Value

coreRaw

Deps

coreRaw:timeseries, ma:timeseries

Agg OI Delta cross down sell

line 155:1

Trigger

coreRaw < ma && coreRaw[1] >= ma[1]

Value

coreRaw

Deps

coreRaw:timeseries, ma:timeseries

278_detrend_aggr_open_interest_delta.flowscript

source path: kscripts/perfected/278_detrend_aggr_open_interest_delta.flowscript · sha256:a19d314bbeefe86f71bb5609ef9d797f8a70b88d59617759854793c444ee9ba0

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original)
define("BTC Agg OI Delta detrend", "offchart", true)
// engine from © BackQuant

var maLen = input("maLen", "number", 14, "MA length")
var smoothMA = input("smoothMA", "boolean", true, "Smooth MA line")
var useEMA = input("useEMA", "boolean", false, "Use EMA (off=SMA)")
var maColor = input("maColor", "color", "#ffffff", "Moving Average Color")
var upColor = input("upColor", "color", "#00ff00", "Up color")
var dnColor = input("dnColor", "color", "#ff0000", "Down color")

// Anchoring
var useAnchored = input("useAnchored", "boolean", false, "Anchor over session window")
var detrend = input("detrend", "boolean", false, "Detrend OI delta")
var plotBars = input("traces", "boolean", false, "Show traces")
var plotDiv = input("only Divergence traces", "boolean", false, "Only divergence traces")
var colorCandles = input("color candles", "boolean", true, "Color candles")

var sessionBars = input("sessionBars", "number", 48, "Bars per session (anchor window)")


var aggMode = input(name="aggMode", type="select", defaultValue="Sum", label="Aggregation Mode", options=["Sum", "Weighted"]);
var unitMode = input(name="unitMode", type="select", defaultValue="Native", label="Unit Mode", options=["Native", "USD Notional"]);

// Includes
var incBybit = input("incBybit", "boolean", true, "Include Bybit")
// var incBinFut = input("incBinFut", "boolean", true, "Include Binance Futures")
// var incDeribit = input("incDeribit", "boolean", true, "Include Deribit")
// var incHyper = input("incHyper", "boolean", true, "Include Hyperliquid")
var incOKX = input("incOKX", "boolean", true, "Include OKX Swap")
// var incBitfinex = input("incBitfinex", "boolean", true, "Include Bitfinex Derivs")
// var incBitMEX = input("incBitMEX", "boolean", true, "Include BitMEX")

// Weights
var wBybit = input("wBybit", "number", 1.0, "Weight Bybit")
// var wBinFut = input("wBinFut", "number", 1.0, "Weight Binance Fut")
// var wDeribit = input("wDeribit", "number", 1.0, "Weight Deribit")
// var wHyper = input("wHyper", "number", 1.0, "Weight Hyperliquid")
var wOKX = input("wOKX", "number", 1.0, "Weight OKX")
// var wBitfinex = input("wBitfinex", "number", 1.0, "Weight Bitfinex")
// var wBitMEX = input("wBitMEX", "number", 1.0, "Weight BitMEX")

// USD notional conversion
var useChartPrice = input("useChartPrice", "boolean", true, "Use chart price for USD notional")

// Static state tracking
static lastRegime = 0
static regimeChangeCount = 0
static barCount = 0
static lastBarIndex = 0

timeseries oiBybit = open_interest("BTCUSDT", "BYBIT")
if (isnan(oiBybit.close[0])) {
    return
}
// timeseries oiBinFut = open_interest("BTCUSDT", "BINANCE_FUTURES")
// timeseries oiDeribit = open_interest("BTC-PERPETUAL", "DERIBIT")
// timeseries oiHyper = open_interest("BTC", "HYPERLIQUID_FUTURES")
timeseries oiOKX = open_interest("BTC-USDT-SWAP", "OKEX_SWAP")
// timeseries oiBitfinex = open_interest("BTCF0:USTF0" ,"BITFINEX_DERIVATIVES")
// timeseries oiBitMEX = open_interest("XBTUSD", "BITMEX")

timeseries ohlcvTS = ohlcv(currentSymbol, currentExchange)
timeseries px = ohlcvTS.close

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

// Per-venue ΔOI
timeseries dBybit = oiBybit.close - oiBybit.close[1]
// timeseries dBinFut = oiBinFut.close - oiBinFut.close[1]
// timeseries dDeribit = oiDeribit.close - oiDeribit.close[1]
// timeseries dHyper = oiHyper.close - oiHyper.close[1]
timeseries dOKX = oiOKX.close - oiOKX.close[1]
// timeseries dBitfinex = oiBitfinex.close - oiBitfinex.close[1]
// timeseries dBitMEX = oiBitMEX.close - oiBitMEX.close[1]

// Optional USD notional
timeseries conv = (unitMode == "USD Notional") ? px : 1.0

timeseries dBybitN = dBybit * conv
// timeseries dBinFutN = dBinFut * conv
// timeseries dDeribitN = dDeribit * conv
// timeseries dHyperN = dHyper * conv
timeseries dOKXN = dOKX * conv
// timeseries dBitfinexN = dBitfinex * conv
// timeseries dBitMEXN = dBitMEX * conv

// Apply includes
timeseries sBybit = incBybit ? dBybitN : 0
// timeseries sBinFut = incBinFut ? dBinFutN : 0
// timeseries sDeribit = incDeribit ? dDeribitN : 0
// timeseries sHyper = incHyper ? dHyperN : 0
timeseries sOKX = incOKX ? dOKXN : 0
// timeseries sBitfinex = incBitfinex ? dBitfinexN : 0
// timeseries sBitMEX = incBitMEX ? dBitMEXN : 0

// Sum weights of included
var wSum = 0.0
wSum = wSum + (incBybit ? wBybit : 0.0)
// wSum = wSum + (incBinFut ? wBinFut : 0.0)
// wSum = wSum + (incDeribit ? wDeribit : 0.0)
// wSum = wSum + (incHyper ? wHyper : 0.0)
wSum = wSum + (incOKX ? wOKX : 0.0)
// wSum = wSum + (incBitfinex ? wBitfinex : 0.0)
// wSum = wSum + (incBitMEX ? wBitMEX : 0.0)

// Aggregate core (Sum or Weighted)
timeseries coreSum = sBybit  + sOKX //+ sBitfinex + sBitMEX + sBinFut + sDeribit + sHyper

timeseries coreWgtNum = sBybit * wBybit
// coreWgtNum = coreWgtNum + sBinFut * wBinFut
// coreWgtNum = coreWgtNum + sDeribit * wDeribit
// coreWgtNum = coreWgtNum + sHyper * wHyper
coreWgtNum = coreWgtNum + sOKX * wOKX
// coreWgtNum = coreWgtNum + sBitfinex * wBitfinex
// coreWgtNum = coreWgtNum + sBitMEX * wBitMEX

timeseries coreAgg = (aggMode == "Weighted" && wSum > 0.0) ? (coreWgtNum / wSum) : coreSum

// Anchored or per-bar
timeseries coreRaw = useAnchored ? sum(coreAgg, sessionBars) : coreAgg

// MA
timeseries maSMA = sma(coreRaw, maLen)
timeseries maEMA = ema(coreRaw, maLen)
timeseries ma = smoothMA ? (useEMA ? maEMA : maSMA) : coreRaw


//net long short
timeseries lsr_ = long_short_ratio(symbol="BTCUSDT", exchange="BYBIT");
timeseries oi_ = open_interest(symbol="BTCUSDT", exchange="BYBIT");
timeseries ohlcvData = ohlcv(symbol="BTCUSDT", exchange="BYBIT");
timeseries prc=ohlcvData.close;
timeseries lsr= isnum(lsr_.total_account)?lsr_.total_account:(isnum(lsr[1])?lsr[1]:1);
timeseries oi=oi_.close/prc;
timeseries longs=lsr*oi/(lsr+1);
timeseries shorts=oi/(lsr+1);
timeseries long = longs-sma(longs,7)
timeseries short = shorts-sma(shorts,7)

// Regime tracking
var currentRegime = long > short ? 1 : -1
barCount = barCount + 1
if (lastRegime != 0 && currentRegime != lastRegime) {
    regimeChangeCount = regimeChangeCount + 1
}
lastRegime = currentRegime

// timeseries longs_=[lsr*oi_.open/(lsr+1)/prc,lsr*oi_.high/(lsr+1)/prc,lsr*oi_.low/(lsr+1)/prc,lsr*oi_.close/(lsr+1)/prc]
timeseries shorts_=[oi_.open/(lsr+1)/prc,oi_.high/(lsr+1)/prc,oi_.low/(lsr+1)/prc,oi_.close/(lsr+1)/prc]
// timeseries ratio = longs-shorts
plotLine(
    value=([coreRaw, ma]),
    width=1,
    colors=[upColor,"blue",dnColor, "white", opacity("gray",50)],
    colorIndex=coreRaw<ma? 4: long>short ? 0:2,
    fill=true,//"momentum_fill",
    smooth=false,
    label=["Anchored CVD"],
    desc=["Session-anchored cumul: ative delta (smoothed if MA>0)"],
      showPriceDisplay=false
  );

hline(0)

// plotCandle(value=shorts_, width=1, colors=["olive", "purple"], label=["Shorts_o","Shorts_h","Sorts_l","Shorts_c"], desc=["Shorts_o","Shorts_h","Sorts_l","Shorts_c"]);
//  plotBar(longs-shorts,colors=["green","red"],label=["Net exposure"],desc=["Net exposure"])
// timeseries px = ohlcv(currentSymbol, currentExchange)
var c = px
timeseries cros = cross(coreRaw,ma)? c : cros[1]

// Fill colors
var upFill = opacity(upColor, 60);
var dnFill = opacity(dnColor, 60);

// Plots
var colIdx = coreRaw >= ma ? 0 : 1;
    colIdx = coreRaw<ma? 0: long>short ? 0:1// (colIdx ==1 && c>cros) || (colIdx ==0 && c<cros)? 2:colIdx
if (plotBars) {
  
  plotLine(
value=[cros,cros],
    width=3,
    colors=[plotDiv?transparency("white",100):upColor , plotDiv?transparency("white",100):dnColor,"yellow"],
    colorIndex=colIdx,
    showPriceDisplay=false,
    label=["Anchored CVD",""],
    desc=["Session-anchored cumulative delta (smoothed if MA>0)",""],
    forceOnChart=true,
      fill="mommentum_fill"
  );
}

if ( colorCandles) {
    // && !colIdx==0
    plotCandle(
       value=ohlcvTS,
        // colors=ratioCum10 < 0 && isAskWall10? redColorIndex : ratioCum10 > 0 && isBidWall10?greenColorIndex:["gray", "white"],
    colors=[plotDiv?transparency("white",100):upColor , plotDiv?transparency("white",100):dnColor,"yellow"],
        
        label= ["l","l","l","l"] ,
        colorIndex= cros>0? 2: long>short ? 0:1,//colIdx,
        desc=["Candles colored by Orderbook","Candles colored by Orderbook","Candles colored by Orderbook","Candles colored by Orderbook"],
        // width=1,
        forceOnChart=true
    )
}


// plot(
//     value=detrend?coreRaw-ma:coreRaw,
//     plotType="bar",
//     colors=[upColor, dnColor],
//     width=1,
//     fill=true,
//     smooth=false,
//     showPriceDisplay=true,
//     label=["Agg OIΔ"],
//     desc=["Aggregated Open Interest Delta (BTC, unit per Unit Mode)"]
// )
// if(detrend==false){
//     plotLine(
//     ma,
//     [maColor],
//      2,
//      false,
//      false,
//      label=["Agg OIΔ MA"],
//      desc=["Moving average of aggregated OIΔ"]
// )
//     }

if (isLastBar) {
    plotTable(
        rows=[
            ["Regime", lastRegime > 0 ? "Long" : lastRegime < 0 ? "Short" : "None"],
            ["Regime Changes", tostring(regimeChangeCount)],
            ["Bar Count", tostring(barCount)]
        ],
        position="bottom_right"
    )
}