feat: derivatives open-interest, flow & liquidation indicators (part 2 of 3) (#127)

* feat(derivatives): OIPriceDivergence indicator (core)

* feat(derivatives): OIWeighted indicator (core)

* feat(derivatives): LongShortRatio indicator (core)

* feat(derivatives): TakerBuySellRatio indicator (core)

* feat(derivatives): LiquidationFeatures multi-output indicator (core)

* feat(derivatives): Python, Node and WASM bindings for OI, flow & liquidation indicators

* test(derivatives): Python and Node tests for OI, flow & liquidation indicators

* fuzz(derivatives): drive OI, flow & liquidation indicators in derivatives target

* docs(derivatives): README row + counter 237->242, CHANGELOG part 2
This commit is contained in:
kingchenc
2026-06-01 21:50:35 +02:00
committed by GitHub
parent 5eb820a9c7
commit 8e5bfd07ce
20 changed files with 2078 additions and 27 deletions
@@ -1136,3 +1136,42 @@ test('derivatives reject bad input', () => {
assert.throws(() => new wickra.FundingRateZScore(0));
assert.throws(() => new wickra.FundingBasis().update(100, 0));
});
test('OI / flow / liquidation indicators reference values', () => {
// OI +10% while price flat -> divergence +0.1.
const div = new wickra.OIPriceDivergence(1);
assert.equal(div.update(1000, 100), null); // warming up
assert.ok(Math.abs(div.update(1100, 100) - 0.1) < 1e-12);
// OI-weighted: (100·10 + 110·30) / 40 = 107.5.
const oiw = new wickra.OIWeighted();
assert.equal(oiw.update(100, 10), 100);
assert.ok(Math.abs(oiw.update(110, 30) - 107.5) < 1e-12);
// Long/short ratio.
assert.ok(Math.abs(new wickra.LongShortRatio().update(600, 400) - 1.5) < 1e-12);
assert.equal(new wickra.LongShortRatio().update(600, 0), 0);
// Taker buy/sell ratio.
assert.ok(Math.abs(new wickra.TakerBuySellRatio().update(60, 40) - 1.5) < 1e-12);
assert.equal(new wickra.TakerBuySellRatio().update(60, 0), 0);
// Liquidation features object.
const liq = new wickra.LiquidationFeatures().update(30, 10);
assert.equal(liq.net, 20);
assert.equal(liq.total, 40);
assert.equal(liq.imbalance, 0.5);
});
test('liquidation features batch is flat n*5', () => {
const longLiq = [10, 0, 30];
const shortLiq = [5, 20, 0];
const batch = new wickra.LiquidationFeatures().batch(longLiq, shortLiq);
assert.equal(batch.length, 15);
// Row 0: long 10, short 5, net 5, total 15.
assert.equal(batch[0], 10);
assert.equal(batch[1], 5);
assert.equal(batch[2], 5);
assert.equal(batch[3], 15);
});
test('OI flow rejects bad input', () => {
assert.throws(() => new wickra.OIPriceDivergence(0));
assert.throws(() => new wickra.OIWeighted().update(0, 100));
});
+53
View File
@@ -292,6 +292,14 @@ export interface FootprintLevelValue {
bidVol: number
askVol: number
}
/** The liquidation feature vector for one tick. */
export interface LiquidationFeaturesValue {
long: number
short: number
net: number
total: number
imbalance: number
}
export type SmaNode = SMA
export declare class SMA {
constructor(period: number)
@@ -2364,6 +2372,51 @@ export declare class OpenInterestDelta {
isReady(): boolean
warmupPeriod(): number
}
export type OIPriceDivergenceNode = OIPriceDivergence
export declare class OIPriceDivergence {
constructor(window: number)
update(openInterest: number, markPrice: number): number | null
batch(openInterest: Array<number>, markPrice: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type OIWeightedNode = OIWeighted
export declare class OIWeighted {
constructor()
update(markPrice: number, openInterest: number): number | null
batch(markPrice: Array<number>, openInterest: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type LongShortRatioNode = LongShortRatio
export declare class LongShortRatio {
constructor()
update(longSize: number, shortSize: number): number | null
batch(longSize: Array<number>, shortSize: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type TakerBuySellRatioNode = TakerBuySellRatio
export declare class TakerBuySellRatio {
constructor()
update(takerBuyVolume: number, takerSellVolume: number): number | null
batch(takerBuyVolume: Array<number>, takerSellVolume: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type LiquidationFeaturesNode = LiquidationFeatures
export declare class LiquidationFeatures {
constructor()
update(longLiquidation: number, shortLiquidation: number): LiquidationFeaturesValue | null
batch(longLiquidation: Array<number>, shortLiquidation: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type SharpeRatioNode = SharpeRatio
export declare class SharpeRatio {
constructor(period: number, riskFree: number)
+6 -1
View File
@@ -310,7 +310,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, MOM, CMO, DPO, StdDev, UlcerIndex, VerticalHorizontalFilter, ZScore, McGinleyDynamic, FRAMA, SuperSmoother, FisherTransform, Decycler, CenterOfGravity, CyberneticCycle, InstantaneousTrendline, EhlersStochastic, RVIVolatility, Variance, CoefficientOfVariation, Skewness, Kurtosis, StandardError, DetrendedStdDev, RSquared, MedianAbsoluteDeviation, Autocorrelation, HurstExponent, PearsonCorrelation, Beta, PairwiseBeta, SpearmanCorrelation, PairSpreadZScore, LeadLagCrossCorrelation, Cointegration, RelativeStrengthAB, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, ADXR, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, RollingVWAP, AwesomeOscillator, Aroon, Inertia, ConnorsRSI, LaguerreRSI, SMI, KST, PGO, RVI, AwesomeOscillatorHistogram, STC, ElderImpulse, ZeroLagMACD, CFO, APO, KAMA, EVWMA, Alligator, JMA, VIDYA, ALMA, T3, TSI, PMO, TII, ADL, VolumePriceTrend, ChaikinMoneyFlow, ChaikinOscillator, ForceIndex, NVI, PVI, VolumeOscillator, KVO, WilliamsAD, AnchoredVWAP, DemandIndex, TSV, VZO, MarketFacilitationIndex, EaseOfMovement, SuperTrend, ChandelierExit, ChandeKrollStop, AtrTrailingStop, HiLoActivator, VoltyStop, YoyoExit, DonchianStop, PercentageTrailingStop, StepTrailingStop, RenkoTrailingStop, TypicalPrice, MedianPrice, WeightedClose, LinearRegression, LinRegSlope, AcceleratorOscillator, BalanceOfPower, ChoppinessIndex, TrueRange, ChaikinVolatility, YangZhangVolatility, RogersSatchellVolatility, GarmanKlassVolatility, ParkinsonVolatility, LinRegAngle, BollingerBandwidth, PercentB, NATR, HistoricalVolatility, AroonOscillator, WaveTrend, RWI, Vortex, MassIndex, StochRSI, UltimateOscillator, PPO, Coppock, VWMA, MaEnvelope, AccelerationBands, StarcBands, AtrBands, HurstChannel, LinRegChannel, StandardErrorBands, DoubleBollinger, TtmSqueeze, FractalChaosBands, VwapStdDevBands, ClassicPivots, FibonacciPivots, Camarilla, WoodiePivots, DemarkPivots, WilliamsFractals, ZigZag, TDSetup, TDSequential, TDDeMarker, TDREI, TDPressure, TDCombo, TDCountdown, TDLines, TDRangeProjection, TDDifferential, TDOpen, TDRiskLevel, InverseFisherTransform, DecyclerOscillator, RoofingFilter, EmpiricalModeDecomposition, HilbertDominantCycle, AdaptiveCycle, SineWave, MAMA, FAMA, Ichimoku, HeikinAshi, ValueArea, InitialBalance, OpeningRange, Doji, Hammer, InvertedHammer, HangingMan, ShootingStar, Engulfing, Harami, MorningEveningStar, ThreeSoldiersOrCrows, PiercingDarkCloud, Marubozu, Tweezer, SpinningTop, ThreeInside, ThreeOutside, OrderBookImbalanceTop1, OrderBookImbalanceFull, Microprice, QuotedSpread, DepthSlope, OrderBookImbalanceTopN, SignedVolume, CumulativeVolumeDelta, TradeImbalance, EffectiveSpread, RealizedSpread, KylesLambda, Footprint, FundingRate, FundingRateMean, FundingRateZScore, FundingBasis, OpenInterestDelta, SharpeRatio, SortinoRatio, CalmarRatio, OmegaRatio, MaxDrawdown, AverageDrawdown, DrawdownDuration, PainIndex, ValueAtRisk, ConditionalValueAtRisk, ProfitFactor, GainLossRatio, RecoveryFactor, KellyCriterion, TreynorRatio, InformationRatio, Alpha } = nativeBinding
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, MOM, CMO, DPO, StdDev, UlcerIndex, VerticalHorizontalFilter, ZScore, McGinleyDynamic, FRAMA, SuperSmoother, FisherTransform, Decycler, CenterOfGravity, CyberneticCycle, InstantaneousTrendline, EhlersStochastic, RVIVolatility, Variance, CoefficientOfVariation, Skewness, Kurtosis, StandardError, DetrendedStdDev, RSquared, MedianAbsoluteDeviation, Autocorrelation, HurstExponent, PearsonCorrelation, Beta, PairwiseBeta, SpearmanCorrelation, PairSpreadZScore, LeadLagCrossCorrelation, Cointegration, RelativeStrengthAB, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, ADXR, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, RollingVWAP, AwesomeOscillator, Aroon, Inertia, ConnorsRSI, LaguerreRSI, SMI, KST, PGO, RVI, AwesomeOscillatorHistogram, STC, ElderImpulse, ZeroLagMACD, CFO, APO, KAMA, EVWMA, Alligator, JMA, VIDYA, ALMA, T3, TSI, PMO, TII, ADL, VolumePriceTrend, ChaikinMoneyFlow, ChaikinOscillator, ForceIndex, NVI, PVI, VolumeOscillator, KVO, WilliamsAD, AnchoredVWAP, DemandIndex, TSV, VZO, MarketFacilitationIndex, EaseOfMovement, SuperTrend, ChandelierExit, ChandeKrollStop, AtrTrailingStop, HiLoActivator, VoltyStop, YoyoExit, DonchianStop, PercentageTrailingStop, StepTrailingStop, RenkoTrailingStop, TypicalPrice, MedianPrice, WeightedClose, LinearRegression, LinRegSlope, AcceleratorOscillator, BalanceOfPower, ChoppinessIndex, TrueRange, ChaikinVolatility, YangZhangVolatility, RogersSatchellVolatility, GarmanKlassVolatility, ParkinsonVolatility, LinRegAngle, BollingerBandwidth, PercentB, NATR, HistoricalVolatility, AroonOscillator, WaveTrend, RWI, Vortex, MassIndex, StochRSI, UltimateOscillator, PPO, Coppock, VWMA, MaEnvelope, AccelerationBands, StarcBands, AtrBands, HurstChannel, LinRegChannel, StandardErrorBands, DoubleBollinger, TtmSqueeze, FractalChaosBands, VwapStdDevBands, ClassicPivots, FibonacciPivots, Camarilla, WoodiePivots, DemarkPivots, WilliamsFractals, ZigZag, TDSetup, TDSequential, TDDeMarker, TDREI, TDPressure, TDCombo, TDCountdown, TDLines, TDRangeProjection, TDDifferential, TDOpen, TDRiskLevel, InverseFisherTransform, DecyclerOscillator, RoofingFilter, EmpiricalModeDecomposition, HilbertDominantCycle, AdaptiveCycle, SineWave, MAMA, FAMA, Ichimoku, HeikinAshi, ValueArea, InitialBalance, OpeningRange, Doji, Hammer, InvertedHammer, HangingMan, ShootingStar, Engulfing, Harami, MorningEveningStar, ThreeSoldiersOrCrows, PiercingDarkCloud, Marubozu, Tweezer, SpinningTop, ThreeInside, ThreeOutside, OrderBookImbalanceTop1, OrderBookImbalanceFull, Microprice, QuotedSpread, DepthSlope, OrderBookImbalanceTopN, SignedVolume, CumulativeVolumeDelta, TradeImbalance, EffectiveSpread, RealizedSpread, KylesLambda, Footprint, FundingRate, FundingRateMean, FundingRateZScore, FundingBasis, OpenInterestDelta, OIPriceDivergence, OIWeighted, LongShortRatio, TakerBuySellRatio, LiquidationFeatures, SharpeRatio, SortinoRatio, CalmarRatio, OmegaRatio, MaxDrawdown, AverageDrawdown, DrawdownDuration, PainIndex, ValueAtRisk, ConditionalValueAtRisk, ProfitFactor, GainLossRatio, RecoveryFactor, KellyCriterion, TreynorRatio, InformationRatio, Alpha } = nativeBinding
module.exports.version = version
module.exports.SMA = SMA
@@ -533,6 +533,11 @@ module.exports.FundingRateMean = FundingRateMean
module.exports.FundingRateZScore = FundingRateZScore
module.exports.FundingBasis = FundingBasis
module.exports.OpenInterestDelta = OpenInterestDelta
module.exports.OIPriceDivergence = OIPriceDivergence
module.exports.OIWeighted = OIWeighted
module.exports.LongShortRatio = LongShortRatio
module.exports.TakerBuySellRatio = TakerBuySellRatio
module.exports.LiquidationFeatures = LiquidationFeatures
module.exports.SharpeRatio = SharpeRatio
module.exports.SortinoRatio = SortinoRatio
module.exports.CalmarRatio = CalmarRatio
+380
View File
@@ -9413,6 +9413,70 @@ fn deriv_oi(open_interest: f64) -> napi::Result<wc::DerivativesTick> {
.map_err(map_err)
}
fn deriv_oi_mark(open_interest: f64, mark_price: f64) -> napi::Result<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
mark_price,
1.0,
1.0,
open_interest,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_long_short(long_size: f64, short_size: f64) -> napi::Result<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0, 1.0, 1.0, 1.0, 0.0, long_size, short_size, 0.0, 0.0, 0.0, 0.0, 0,
)
.map_err(map_err)
}
fn deriv_taker(taker_buy_volume: f64, taker_sell_volume: f64) -> napi::Result<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
taker_buy_volume,
taker_sell_volume,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_liquidation(
long_liquidation: f64,
short_liquidation: f64,
) -> napi::Result<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
long_liquidation,
short_liquidation,
0,
)
.map_err(map_err)
}
#[napi(js_name = "FundingRate")]
pub struct FundingRateNode {
inner: wc::FundingRate,
@@ -9635,6 +9699,322 @@ impl OpenInterestDeltaNode {
}
}
#[napi(js_name = "OIPriceDivergence")]
pub struct OIPriceDivergenceNode {
inner: wc::OIPriceDivergence,
}
#[napi]
impl OIPriceDivergenceNode {
#[napi(constructor)]
pub fn new(window: u32) -> napi::Result<Self> {
Ok(Self {
inner: wc::OIPriceDivergence::new(window as usize).map_err(map_err)?,
})
}
#[napi]
pub fn update(&mut self, open_interest: f64, mark_price: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?))
}
#[napi]
pub fn batch(
&mut self,
open_interest: Vec<f64>,
mark_price: Vec<f64>,
) -> napi::Result<Vec<f64>> {
if open_interest.len() != mark_price.len() {
return Err(NapiError::from_reason(
"open_interest and mark_price must be equal length".to_string(),
));
}
let mut out = Vec::with_capacity(open_interest.len());
for i in 0..open_interest.len() {
out.push(
self.inner
.update(deriv_oi_mark(open_interest[i], mark_price[i])?)
.unwrap_or(f64::NAN),
);
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
#[napi(js_name = "OIWeighted")]
pub struct OIWeightedNode {
inner: wc::OIWeighted,
}
impl Default for OIWeightedNode {
fn default() -> Self {
Self::new()
}
}
#[napi]
impl OIWeightedNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::OIWeighted::new(),
}
}
#[napi]
pub fn update(&mut self, mark_price: f64, open_interest: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?))
}
#[napi]
pub fn batch(
&mut self,
mark_price: Vec<f64>,
open_interest: Vec<f64>,
) -> napi::Result<Vec<f64>> {
if mark_price.len() != open_interest.len() {
return Err(NapiError::from_reason(
"mark_price and open_interest must be equal length".to_string(),
));
}
let mut out = Vec::with_capacity(mark_price.len());
for i in 0..mark_price.len() {
out.push(
self.inner
.update(deriv_oi_mark(open_interest[i], mark_price[i])?)
.unwrap_or(f64::NAN),
);
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
#[napi(js_name = "LongShortRatio")]
pub struct LongShortRatioNode {
inner: wc::LongShortRatio,
}
impl Default for LongShortRatioNode {
fn default() -> Self {
Self::new()
}
}
#[napi]
impl LongShortRatioNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::LongShortRatio::new(),
}
}
#[napi]
pub fn update(&mut self, long_size: f64, short_size: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(deriv_long_short(long_size, short_size)?))
}
#[napi]
pub fn batch(&mut self, long_size: Vec<f64>, short_size: Vec<f64>) -> napi::Result<Vec<f64>> {
if long_size.len() != short_size.len() {
return Err(NapiError::from_reason(
"long_size and short_size must be equal length".to_string(),
));
}
let mut out = Vec::with_capacity(long_size.len());
for i in 0..long_size.len() {
out.push(
self.inner
.update(deriv_long_short(long_size[i], short_size[i])?)
.unwrap_or(f64::NAN),
);
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
#[napi(js_name = "TakerBuySellRatio")]
pub struct TakerBuySellRatioNode {
inner: wc::TakerBuySellRatio,
}
impl Default for TakerBuySellRatioNode {
fn default() -> Self {
Self::new()
}
}
#[napi]
impl TakerBuySellRatioNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::TakerBuySellRatio::new(),
}
}
#[napi]
pub fn update(
&mut self,
taker_buy_volume: f64,
taker_sell_volume: f64,
) -> napi::Result<Option<f64>> {
Ok(self
.inner
.update(deriv_taker(taker_buy_volume, taker_sell_volume)?))
}
#[napi]
pub fn batch(
&mut self,
taker_buy_volume: Vec<f64>,
taker_sell_volume: Vec<f64>,
) -> napi::Result<Vec<f64>> {
if taker_buy_volume.len() != taker_sell_volume.len() {
return Err(NapiError::from_reason(
"taker_buy_volume and taker_sell_volume must be equal length".to_string(),
));
}
let mut out = Vec::with_capacity(taker_buy_volume.len());
for i in 0..taker_buy_volume.len() {
out.push(
self.inner
.update(deriv_taker(taker_buy_volume[i], taker_sell_volume[i])?)
.unwrap_or(f64::NAN),
);
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
/// The liquidation feature vector for one tick.
#[napi(object)]
pub struct LiquidationFeaturesValue {
pub long: f64,
pub short: f64,
pub net: f64,
pub total: f64,
pub imbalance: f64,
}
#[napi(js_name = "LiquidationFeatures")]
pub struct LiquidationFeaturesNode {
inner: wc::LiquidationFeatures,
}
impl Default for LiquidationFeaturesNode {
fn default() -> Self {
Self::new()
}
}
#[napi]
impl LiquidationFeaturesNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::LiquidationFeatures::new(),
}
}
#[napi]
pub fn update(
&mut self,
long_liquidation: f64,
short_liquidation: f64,
) -> napi::Result<Option<LiquidationFeaturesValue>> {
Ok(self
.inner
.update(deriv_liquidation(long_liquidation, short_liquidation)?)
.map(|o| LiquidationFeaturesValue {
long: o.long,
short: o.short,
net: o.net,
total: o.total,
imbalance: o.imbalance,
}))
}
#[napi]
pub fn batch(
&mut self,
long_liquidation: Vec<f64>,
short_liquidation: Vec<f64>,
) -> napi::Result<Vec<f64>> {
if long_liquidation.len() != short_liquidation.len() {
return Err(NapiError::from_reason(
"long_liquidation and short_liquidation must be equal length".to_string(),
));
}
let mut out = Vec::with_capacity(long_liquidation.len() * 5);
for i in 0..long_liquidation.len() {
let o = self
.inner
.update(deriv_liquidation(
long_liquidation[i],
short_liquidation[i],
)?)
.expect("liquidation features emit on every tick");
out.push(o.long);
out.push(o.short);
out.push(o.net);
out.push(o.total);
out.push(o.imbalance);
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
// ============================== Family 15: Risk / Performance ==============================
// Risk metrics with fallible `new` (most need `period >= 2`), so each wrapper