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
+10
View File
@@ -263,6 +263,11 @@ from ._wickra import (
FundingRateZScore,
FundingBasis,
OpenInterestDelta,
OIPriceDivergence,
OIWeighted,
LongShortRatio,
TakerBuySellRatio,
LiquidationFeatures,
# Risk / Performance
SharpeRatio,
SortinoRatio,
@@ -523,6 +528,11 @@ __all__ = [
"FundingRateZScore",
"FundingBasis",
"OpenInterestDelta",
"OIPriceDivergence",
"OIWeighted",
"LongShortRatio",
"TakerBuySellRatio",
"LiquidationFeatures",
# Risk / Performance
"SharpeRatio",
"SortinoRatio",
+375
View File
@@ -12244,6 +12244,70 @@ fn deriv_oi(open_interest: f64) -> PyResult<wc::DerivativesTick> {
.map_err(map_err)
}
fn deriv_oi_mark(open_interest: f64, mark_price: f64) -> PyResult<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) -> PyResult<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) -> PyResult<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,
) -> PyResult<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)
}
// FundingRate takes no parameters; streaming `update(funding_rate)`, `batch`
// over one funding-rate array.
#[pyclass(name = "FundingRate", module = "wickra._wickra", skip_from_py_object)]
@@ -12482,6 +12546,312 @@ impl PyOpenInterestDelta {
}
}
// OIPriceDivergence carries a `window` parameter; streaming
// `update(open_interest, mark_price)`.
#[pyclass(
name = "OIPriceDivergence",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyOIPriceDivergence {
inner: wc::OIPriceDivergence,
}
#[pymethods]
impl PyOIPriceDivergence {
#[new]
fn new(window: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::OIPriceDivergence::new(window).map_err(map_err)?,
})
}
fn update(&mut self, open_interest: f64, mark_price: f64) -> PyResult<Option<f64>> {
Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
open_interest: Vec<f64>,
mark_price: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if open_interest.len() != mark_price.len() {
return Err(PyValueError::new_err(
"open_interest and mark_price must be equal length",
));
}
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.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!("OIPriceDivergence(window={})", self.inner.window())
}
}
// OIWeighted takes no parameters; streaming `update(mark_price, open_interest)`.
#[pyclass(name = "OIWeighted", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyOIWeighted {
inner: wc::OIWeighted,
}
#[pymethods]
impl PyOIWeighted {
#[new]
fn new() -> Self {
Self {
inner: wc::OIWeighted::new(),
}
}
fn update(&mut self, mark_price: f64, open_interest: f64) -> PyResult<Option<f64>> {
Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
mark_price: Vec<f64>,
open_interest: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if mark_price.len() != open_interest.len() {
return Err(PyValueError::new_err(
"mark_price and open_interest must be equal length",
));
}
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.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"OIWeighted()".to_string()
}
}
// LongShortRatio takes no parameters; streaming `update(long_size, short_size)`.
#[pyclass(
name = "LongShortRatio",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyLongShortRatio {
inner: wc::LongShortRatio,
}
#[pymethods]
impl PyLongShortRatio {
#[new]
fn new() -> Self {
Self {
inner: wc::LongShortRatio::new(),
}
}
fn update(&mut self, long_size: f64, short_size: f64) -> PyResult<Option<f64>> {
Ok(self.inner.update(deriv_long_short(long_size, short_size)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
long_size: Vec<f64>,
short_size: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if long_size.len() != short_size.len() {
return Err(PyValueError::new_err(
"long_size and short_size must be equal length",
));
}
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.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"LongShortRatio()".to_string()
}
}
// TakerBuySellRatio takes no parameters; streaming
// `update(taker_buy_volume, taker_sell_volume)`.
#[pyclass(
name = "TakerBuySellRatio",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyTakerBuySellRatio {
inner: wc::TakerBuySellRatio,
}
#[pymethods]
impl PyTakerBuySellRatio {
#[new]
fn new() -> Self {
Self {
inner: wc::TakerBuySellRatio::new(),
}
}
fn update(&mut self, taker_buy_volume: f64, taker_sell_volume: f64) -> PyResult<Option<f64>> {
Ok(self
.inner
.update(deriv_taker(taker_buy_volume, taker_sell_volume)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
taker_buy_volume: Vec<f64>,
taker_sell_volume: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if taker_buy_volume.len() != taker_sell_volume.len() {
return Err(PyValueError::new_err(
"taker_buy_volume and taker_sell_volume must be equal length",
));
}
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.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"TakerBuySellRatio()".to_string()
}
}
// LiquidationFeatures is a multi-output indicator: streaming
// `update(long_liquidation, short_liquidation)` returns a 5-tuple
// `(long, short, net, total, imbalance)`; `batch` returns an `(n, 5)` array.
#[pyclass(
name = "LiquidationFeatures",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyLiquidationFeatures {
inner: wc::LiquidationFeatures,
}
#[pymethods]
impl PyLiquidationFeatures {
#[new]
fn new() -> Self {
Self {
inner: wc::LiquidationFeatures::new(),
}
}
/// Returns `(long, short, net, total, imbalance)` or None during warmup.
#[allow(clippy::type_complexity)]
fn update(
&mut self,
long_liquidation: f64,
short_liquidation: f64,
) -> PyResult<Option<(f64, f64, f64, f64, f64)>> {
Ok(self
.inner
.update(deriv_liquidation(long_liquidation, short_liquidation)?)
.map(|o| (o.long, o.short, o.net, o.total, o.imbalance)))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
long_liquidation: Vec<f64>,
short_liquidation: Vec<f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
if long_liquidation.len() != short_liquidation.len() {
return Err(PyValueError::new_err(
"long_liquidation and short_liquidation must be equal length",
));
}
let rows = long_liquidation.len();
let mut data = Vec::with_capacity(rows * 5);
for i in 0..rows {
let out = self
.inner
.update(deriv_liquidation(
long_liquidation[i],
short_liquidation[i],
)?)
.expect("liquidation features emit on every tick");
data.push(out.long);
data.push(out.short);
data.push(out.net);
data.push(out.total);
data.push(out.imbalance);
}
Ok(numpy::ndarray::Array2::from_shape_vec((rows, 5), data)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"LiquidationFeatures()".to_string()
}
}
// ============================== Family 15: Risk / Performance ==============================
#[pyclass(name = "SharpeRatio", module = "wickra._wickra", skip_from_py_object)]
@@ -13610,6 +13980,11 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyFundingRateZScore>()?;
m.add_class::<PyFundingBasis>()?;
m.add_class::<PyOpenInterestDelta>()?;
m.add_class::<PyOIPriceDivergence>()?;
m.add_class::<PyOIWeighted>()?;
m.add_class::<PyLongShortRatio>()?;
m.add_class::<PyTakerBuySellRatio>()?;
m.add_class::<PyLiquidationFeatures>()?;
// Family 15: Risk / Performance metrics.
m.add_class::<PySharpeRatio>()?;
m.add_class::<PySortinoRatio>()?;
@@ -258,3 +258,13 @@ def test_funding_basis_non_positive_index_raises():
def test_funding_rate_non_finite_raises():
with pytest.raises(ValueError):
ta.FundingRate().update(float("nan"))
def test_oi_price_divergence_zero_window_raises():
with pytest.raises(ValueError):
ta.OIPriceDivergence(0)
def test_oi_weighted_non_positive_mark_raises():
with pytest.raises(ValueError):
ta.OIWeighted().update(0.0, 100.0)
@@ -979,3 +979,37 @@ def test_open_interest_delta_reference_value():
assert oid.update(1000.0) is None # seeds the previous OI
assert oid.update(1250.0) == pytest.approx(250.0)
assert oid.update(1100.0) == pytest.approx(-150.0)
def test_oi_price_divergence_reference_value():
div = ta.OIPriceDivergence(1)
assert div.update(1000.0, 100.0) is None # warming up
# OI +10% while price flat -> divergence +0.1.
assert div.update(1100.0, 100.0) == pytest.approx(0.1)
def test_oi_weighted_reference_value():
oiw = ta.OIWeighted()
assert oiw.update(100.0, 10.0) == pytest.approx(100.0)
# (100·10 + 110·30) / 40 = 107.5.
assert oiw.update(110.0, 30.0) == pytest.approx(107.5)
def test_long_short_ratio_reference_value():
# 600 longs vs 400 shorts -> 1.5.
assert ta.LongShortRatio().update(600.0, 400.0) == pytest.approx(1.5)
# No short side -> 0.0.
assert ta.LongShortRatio().update(600.0, 0.0) == pytest.approx(0.0)
def test_taker_buy_sell_ratio_reference_value():
# 60 taker buys vs 40 taker sells -> 1.5.
assert ta.TakerBuySellRatio().update(60.0, 40.0) == pytest.approx(1.5)
# No taker sell volume -> 0.0.
assert ta.TakerBuySellRatio().update(60.0, 0.0) == pytest.approx(0.0)
def test_liquidation_features_reference_value():
# 30 long vs 10 short: (long, short, net, total, imbalance).
out = ta.LiquidationFeatures().update(30.0, 10.0)
assert out == pytest.approx((30.0, 10.0, 20.0, 40.0, 0.5))
@@ -1994,3 +1994,56 @@ def test_open_interest_delta_streaming_equals_batch():
streamed = np.array([streamer.update(oi[i]) for i in range(n)], dtype=np.float64)
assert batch.shape == (n,)
assert _eq_nan(batch, streamed)
def test_oi_flow_indicators_streaming_equals_batch():
n = 40
oi = np.array([1000.0 + 50.0 * math.sin(i * 0.2) for i in range(n)], dtype=np.float64)
mark = np.array([100.0 + math.cos(i * 0.3) for i in range(n)], dtype=np.float64)
long_sz = np.array([500.0 + 20.0 * math.sin(i * 0.25) for i in range(n)], dtype=np.float64)
short_sz = np.array([400.0 + 20.0 * math.cos(i * 0.25) for i in range(n)], dtype=np.float64)
# OIPriceDivergence carries a window; update(open_interest, mark_price).
batch = ta.OIPriceDivergence(5).batch(oi, mark)
streamer = ta.OIPriceDivergence(5)
streamed = np.array(
[streamer.update(oi[i], mark[i]) for i in range(n)], dtype=np.float64
)
assert batch.shape == (n,)
assert _eq_nan(batch, streamed)
# OIWeighted; update(mark_price, open_interest).
batch = ta.OIWeighted().batch(mark, oi)
streamer = ta.OIWeighted()
streamed = np.array(
[streamer.update(mark[i], oi[i]) for i in range(n)], dtype=np.float64
)
assert _eq_nan(batch, streamed)
# LongShortRatio; update(long_size, short_size).
batch = ta.LongShortRatio().batch(long_sz, short_sz)
streamer = ta.LongShortRatio()
streamed = np.array(
[streamer.update(long_sz[i], short_sz[i]) for i in range(n)], dtype=np.float64
)
assert _eq_nan(batch, streamed)
# TakerBuySellRatio; update(taker_buy_volume, taker_sell_volume).
batch = ta.TakerBuySellRatio().batch(long_sz, short_sz)
streamer = ta.TakerBuySellRatio()
streamed = np.array(
[streamer.update(long_sz[i], short_sz[i]) for i in range(n)], dtype=np.float64
)
assert _eq_nan(batch, streamed)
def test_liquidation_features_streaming_equals_batch():
n = 30
long_liq = np.array([abs(50.0 * math.sin(i * 0.4)) for i in range(n)], dtype=np.float64)
short_liq = np.array([abs(40.0 * math.cos(i * 0.3)) for i in range(n)], dtype=np.float64)
batch = ta.LiquidationFeatures().batch(long_liq, short_liq)
streamer = ta.LiquidationFeatures()
assert batch.shape == (n, 5)
for i in range(n):
row = streamer.update(long_liq[i], short_liq[i])
assert tuple(batch[i]) == pytest.approx(row)
+256
View File
@@ -6972,6 +6972,262 @@ impl WasmOpenInterestDelta {
}
}
fn deriv_oi_mark(open_interest: f64, mark_price: f64) -> Result<wc::DerivativesTick, JsError> {
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) -> Result<wc::DerivativesTick, JsError> {
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,
) -> Result<wc::DerivativesTick, JsError> {
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,
) -> Result<wc::DerivativesTick, JsError> {
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)
}
#[wasm_bindgen(js_name = OIPriceDivergence)]
pub struct WasmOIPriceDivergence {
inner: wc::OIPriceDivergence,
}
#[wasm_bindgen(js_class = OIPriceDivergence)]
impl WasmOIPriceDivergence {
#[wasm_bindgen(constructor)]
pub fn new(window: usize) -> Result<WasmOIPriceDivergence, JsError> {
Ok(Self {
inner: wc::OIPriceDivergence::new(window).map_err(map_err)?,
})
}
pub fn update(&mut self, open_interest: f64, mark_price: f64) -> Result<Option<f64>, JsError> {
Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = OIWeighted)]
pub struct WasmOIWeighted {
inner: wc::OIWeighted,
}
impl Default for WasmOIWeighted {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = OIWeighted)]
impl WasmOIWeighted {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmOIWeighted {
Self {
inner: wc::OIWeighted::new(),
}
}
pub fn update(&mut self, mark_price: f64, open_interest: f64) -> Result<Option<f64>, JsError> {
Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = LongShortRatio)]
pub struct WasmLongShortRatio {
inner: wc::LongShortRatio,
}
impl Default for WasmLongShortRatio {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = LongShortRatio)]
impl WasmLongShortRatio {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmLongShortRatio {
Self {
inner: wc::LongShortRatio::new(),
}
}
pub fn update(&mut self, long_size: f64, short_size: f64) -> Result<Option<f64>, JsError> {
Ok(self.inner.update(deriv_long_short(long_size, short_size)?))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = TakerBuySellRatio)]
pub struct WasmTakerBuySellRatio {
inner: wc::TakerBuySellRatio,
}
impl Default for WasmTakerBuySellRatio {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = TakerBuySellRatio)]
impl WasmTakerBuySellRatio {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmTakerBuySellRatio {
Self {
inner: wc::TakerBuySellRatio::new(),
}
}
pub fn update(
&mut self,
taker_buy_volume: f64,
taker_sell_volume: f64,
) -> Result<Option<f64>, JsError> {
Ok(self
.inner
.update(deriv_taker(taker_buy_volume, taker_sell_volume)?))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = LiquidationFeatures)]
pub struct WasmLiquidationFeatures {
inner: wc::LiquidationFeatures,
}
impl Default for WasmLiquidationFeatures {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = LiquidationFeatures)]
impl WasmLiquidationFeatures {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmLiquidationFeatures {
Self {
inner: wc::LiquidationFeatures::new(),
}
}
pub fn update(
&mut self,
long_liquidation: f64,
short_liquidation: f64,
) -> Result<JsValue, JsError> {
let out = self
.inner
.update(deriv_liquidation(long_liquidation, short_liquidation)?)
.expect("liquidation features emit on every tick");
let obj = Object::new();
Reflect::set(&obj, &"long".into(), &out.long.into()).ok();
Reflect::set(&obj, &"short".into(), &out.short.into()).ok();
Reflect::set(&obj, &"net".into(), &out.net.into()).ok();
Reflect::set(&obj, &"total".into(), &out.total.into()).ok();
Reflect::set(&obj, &"imbalance".into(), &out.imbalance.into()).ok();
Ok(obj.into())
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[cfg(test)]
mod tests {
use super::*;