From 8e5bfd07cea10cd0b2904bc333e38027305b774e Mon Sep 17 00:00:00 2001 From: kingchenc Date: Mon, 1 Jun 2026 21:50:35 +0200 Subject: [PATCH] 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 --- CHANGELOG.md | 9 + README.md | 10 +- bindings/node/__tests__/indicators.test.js | 39 ++ bindings/node/index.d.ts | 53 +++ bindings/node/index.js | 7 +- bindings/node/src/lib.rs | 380 ++++++++++++++++++ bindings/python/python/wickra/__init__.py | 10 + bindings/python/src/lib.rs | 375 +++++++++++++++++ .../python/tests/test_input_validation.py | 10 + bindings/python/tests/test_known_values.py | 34 ++ bindings/python/tests/test_new_indicators.py | 53 +++ bindings/wasm/src/lib.rs | 256 ++++++++++++ .../src/indicators/liquidation_features.rs | 179 +++++++++ .../src/indicators/long_short_ratio.rs | 138 +++++++ crates/wickra-core/src/indicators/mod.rs | 17 +- .../src/indicators/oi_price_divergence.rs | 193 +++++++++ .../wickra-core/src/indicators/oi_weighted.rs | 151 +++++++ .../src/indicators/taker_buy_sell_ratio.rs | 137 +++++++ crates/wickra-core/src/lib.rs | 40 +- .../indicator_update_derivatives.rs | 14 +- 20 files changed, 2078 insertions(+), 27 deletions(-) create mode 100644 crates/wickra-core/src/indicators/liquidation_features.rs create mode 100644 crates/wickra-core/src/indicators/long_short_ratio.rs create mode 100644 crates/wickra-core/src/indicators/oi_price_divergence.rs create mode 100644 crates/wickra-core/src/indicators/oi_weighted.rs create mode 100644 crates/wickra-core/src/indicators/taker_buy_sell_ratio.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 855a9313..49d5266b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Funding Basis** — the perpetual's relative premium to spot, `(markPrice − indexPrice) / indexPrice`. - **Open-Interest Delta** — the tick-over-tick change in open interest. +- **Derivatives family — open interest, flow & liquidations (part 2).** More + indicators over the same `DerivativesTick` feed: + - **OI / Price Divergence** — relative open-interest change minus relative + price change over a window, the positioning-vs-price gap. + - **OI-Weighted Price** — the cumulative mark price weighted by open interest. + - **Long/Short Ratio** — aggregate long size over short size. + - **Taker Buy/Sell Ratio** — taker buy volume over taker sell volume. + - **Liquidation Features** — a multi-output breakdown of long/short + liquidation notional into net, total and a bounded imbalance. ## [0.4.3] - 2026-06-01 diff --git a/README.md b/README.md index aa34f5a3..d3299afb 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- Wickra — streaming-first technical indicators + Wickra — streaming-first technical indicators

[![CI](https://github.com/wickra-lib/wickra/actions/workflows/ci.yml/badge.svg)](https://github.com/wickra-lib/wickra/actions/workflows/ci.yml) @@ -47,7 +47,7 @@ Full documentation lives at **[docs.wickra.org](https://docs.wickra.org)**: [Node](https://docs.wickra.org/Quickstart-Node), [WASM](https://docs.wickra.org/Quickstart-WASM). - **Indicators** — a per-indicator deep dive (formula, parameters, warmup) for - every one of the 237 indicators; start at the + every one of the 242 indicators; start at the [indicators overview](https://docs.wickra.org/Indicators-Overview). - **Reference** — [warmup periods](https://docs.wickra.org/Warmup-Periods), [streaming vs batch](https://docs.wickra.org/Streaming-vs-Batch), @@ -135,7 +135,7 @@ python -m benchmarks.compare_libraries ## Indicators -237 streaming-first indicators across eighteen families. Every one passes the +242 streaming-first indicators across eighteen families. Every one passes the `batch == streaming` equivalence test, reference-value tests, and reset semantics tests. Each has a per-indicator deep dive (formula, parameters, warmup) at [docs.wickra.org](https://docs.wickra.org/Indicators-Overview). @@ -157,7 +157,7 @@ warmup) at [docs.wickra.org](https://docs.wickra.org/Indicators-Overview). | Ichimoku & Charts | Ichimoku Kinko Hyo (Tenkan, Kijun, Senkou A/B, Chikou), Heikin-Ashi | | Candlestick Patterns | Doji, Hammer, Inverted Hammer, Hanging Man, Shooting Star, Engulfing, Harami, Morning/Evening Star, Three White Soldiers/Black Crows, Piercing Line/Dark Cloud Cover, Marubozu, Tweezer, Spinning Top, Three Inside Up/Down, Three Outside Up/Down | | Microstructure | Order-Book Imbalance (Top-1 / Top-N / Full), Microprice, Quoted Spread, Depth Slope, Signed Volume, Cumulative Volume Delta, Trade Imbalance, Effective Spread, Realized Spread, Kyle's Lambda, Footprint | -| Derivatives | Funding Rate, Funding Rate Mean, Funding Rate Z-Score, Funding Basis, Open-Interest Delta | +| Derivatives | Funding Rate, Funding Rate Mean, Funding Rate Z-Score, Funding Basis, Open-Interest Delta, OI / Price Divergence, OI-Weighted Price, Long/Short Ratio, Taker Buy/Sell Ratio, Liquidation Features | | Market Profile | Value Area (POC / VAH / VAL), Initial Balance, Opening Range | | Risk / Performance | Sharpe Ratio, Sortino Ratio, Calmar Ratio, Omega Ratio, Max Drawdown, Average Drawdown, Drawdown Duration, Pain Index, Value at Risk, Conditional Value at Risk (CVaR), Profit Factor, Gain/Loss Ratio, Recovery Factor, Kelly Criterion, Treynor Ratio, Information Ratio, Alpha (Jensen) | @@ -238,7 +238,7 @@ A Python live-trading example using the public `websockets` package lives at ``` wickra/ ├── crates/ -│ ├── wickra-core/ core engine + all 237 indicators +│ ├── wickra-core/ core engine + all 242 indicators │ ├── wickra/ top-level facade crate (publishes on crates.io) + benches/ │ └── wickra-data/ CSV reader, tick aggregator, live exchange feeds ├── bindings/ diff --git a/bindings/node/__tests__/indicators.test.js b/bindings/node/__tests__/indicators.test.js index 4cd0012b..e16d9de9 100644 --- a/bindings/node/__tests__/indicators.test.js +++ b/bindings/node/__tests__/indicators.test.js @@ -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)); +}); diff --git a/bindings/node/index.d.ts b/bindings/node/index.d.ts index 0a6869c8..5ca64cad 100644 --- a/bindings/node/index.d.ts +++ b/bindings/node/index.d.ts @@ -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, markPrice: Array): Array + 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, openInterest: Array): Array + 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, shortSize: Array): Array + 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, takerSellVolume: Array): Array + 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, shortLiquidation: Array): Array + reset(): void + isReady(): boolean + warmupPeriod(): number +} export type SharpeRatioNode = SharpeRatio export declare class SharpeRatio { constructor(period: number, riskFree: number) diff --git a/bindings/node/index.js b/bindings/node/index.js index f79e5578..05a97f88 100644 --- a/bindings/node/index.js +++ b/bindings/node/index.js @@ -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 diff --git a/bindings/node/src/lib.rs b/bindings/node/src/lib.rs index 1c5eb4b6..98dc070f 100644 --- a/bindings/node/src/lib.rs +++ b/bindings/node/src/lib.rs @@ -9413,6 +9413,70 @@ fn deriv_oi(open_interest: f64) -> napi::Result { .map_err(map_err) } +fn deriv_oi_mark(open_interest: f64, mark_price: f64) -> napi::Result { + 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::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::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::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 { + 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> { + Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?)) + } + #[napi] + pub fn batch( + &mut self, + open_interest: Vec, + mark_price: Vec, + ) -> napi::Result> { + 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> { + Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?)) + } + #[napi] + pub fn batch( + &mut self, + mark_price: Vec, + open_interest: Vec, + ) -> napi::Result> { + 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> { + Ok(self.inner.update(deriv_long_short(long_size, short_size)?)) + } + #[napi] + pub fn batch(&mut self, long_size: Vec, short_size: Vec) -> napi::Result> { + 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> { + Ok(self + .inner + .update(deriv_taker(taker_buy_volume, taker_sell_volume)?)) + } + #[napi] + pub fn batch( + &mut self, + taker_buy_volume: Vec, + taker_sell_volume: Vec, + ) -> napi::Result> { + 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> { + 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, + short_liquidation: Vec, + ) -> napi::Result> { + 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 diff --git a/bindings/python/python/wickra/__init__.py b/bindings/python/python/wickra/__init__.py index ad022311..68d6e0fd 100644 --- a/bindings/python/python/wickra/__init__.py +++ b/bindings/python/python/wickra/__init__.py @@ -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", diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index f738b489..11f634e4 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -12244,6 +12244,70 @@ fn deriv_oi(open_interest: f64) -> PyResult { .map_err(map_err) } +fn deriv_oi_mark(open_interest: f64, mark_price: f64) -> PyResult { + 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::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::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::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 { + Ok(Self { + inner: wc::OIPriceDivergence::new(window).map_err(map_err)?, + }) + } + fn update(&mut self, open_interest: f64, mark_price: f64) -> PyResult> { + Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?)) + } + fn batch<'py>( + &mut self, + py: Python<'py>, + open_interest: Vec, + mark_price: Vec, + ) -> PyResult>> { + 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> { + Ok(self.inner.update(deriv_oi_mark(open_interest, mark_price)?)) + } + fn batch<'py>( + &mut self, + py: Python<'py>, + mark_price: Vec, + open_interest: Vec, + ) -> PyResult>> { + 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> { + Ok(self.inner.update(deriv_long_short(long_size, short_size)?)) + } + fn batch<'py>( + &mut self, + py: Python<'py>, + long_size: Vec, + short_size: Vec, + ) -> PyResult>> { + 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> { + Ok(self + .inner + .update(deriv_taker(taker_buy_volume, taker_sell_volume)?)) + } + fn batch<'py>( + &mut self, + py: Python<'py>, + taker_buy_volume: Vec, + taker_sell_volume: Vec, + ) -> PyResult>> { + 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> { + 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, + short_liquidation: Vec, + ) -> PyResult>> { + 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::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; // Family 15: Risk / Performance metrics. m.add_class::()?; m.add_class::()?; diff --git a/bindings/python/tests/test_input_validation.py b/bindings/python/tests/test_input_validation.py index 7e372e58..3ed99b96 100644 --- a/bindings/python/tests/test_input_validation.py +++ b/bindings/python/tests/test_input_validation.py @@ -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) diff --git a/bindings/python/tests/test_known_values.py b/bindings/python/tests/test_known_values.py index 098e81a5..d350f17d 100644 --- a/bindings/python/tests/test_known_values.py +++ b/bindings/python/tests/test_known_values.py @@ -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)) diff --git a/bindings/python/tests/test_new_indicators.py b/bindings/python/tests/test_new_indicators.py index 1d02290c..07146951 100644 --- a/bindings/python/tests/test_new_indicators.py +++ b/bindings/python/tests/test_new_indicators.py @@ -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) diff --git a/bindings/wasm/src/lib.rs b/bindings/wasm/src/lib.rs index ed2d4c00..eb3f69fa 100644 --- a/bindings/wasm/src/lib.rs +++ b/bindings/wasm/src/lib.rs @@ -6972,6 +6972,262 @@ impl WasmOpenInterestDelta { } } +fn deriv_oi_mark(open_interest: f64, mark_price: f64) -> Result { + 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::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::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::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 { + Ok(Self { + inner: wc::OIPriceDivergence::new(window).map_err(map_err)?, + }) + } + pub fn update(&mut self, open_interest: f64, mark_price: f64) -> Result, 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, 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, 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, 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 { + 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::*; diff --git a/crates/wickra-core/src/indicators/liquidation_features.rs b/crates/wickra-core/src/indicators/liquidation_features.rs new file mode 100644 index 00000000..24d10d0b --- /dev/null +++ b/crates/wickra-core/src/indicators/liquidation_features.rs @@ -0,0 +1,179 @@ +//! Liquidation Features — per-tick long/short liquidation breakdown. + +use crate::derivatives::DerivativesTick; +use crate::traits::Indicator; + +/// The liquidation feature vector emitted by [`LiquidationFeatures`] for one +/// tick. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct LiquidationFeaturesOutput { + /// Long-side liquidation notional on this tick. + pub long: f64, + /// Short-side liquidation notional on this tick. + pub short: f64, + /// Net liquidation `long − short` (positive = longs being liquidated). + pub net: f64, + /// Total liquidation `long + short`. + pub total: f64, + /// Liquidation imbalance `(long − short) / (long + short)`, in `[−1, +1]`; + /// `0.0` when there is no liquidation. + pub imbalance: f64, +} + +/// Liquidation Features — decomposes the long- and short-side liquidation +/// notional carried by each tick into a small feature vector. +/// +/// ```text +/// net = longLiquidation − shortLiquidation +/// total = longLiquidation + shortLiquidation +/// imbalance = net / total (0 when total == 0) +/// ``` +/// +/// Liquidation cascades are a perpetual-market-specific tail risk: a wave of +/// long liquidations forces market sells that beget more liquidations. Splitting +/// the flow into net, total and a bounded imbalance turns the raw venue feed +/// into model-ready features — `total` sizes the stress, `imbalance` (and its +/// sign) says which side is being flushed. A positive imbalance means longs are +/// being liquidated (downside cascade), a negative one shorts (upside squeeze). +/// +/// `Input = DerivativesTick`, `Output = LiquidationFeaturesOutput`. Stateless; +/// ready after the first tick. +/// +/// # Example +/// +/// ``` +/// use wickra_core::{DerivativesTick, Indicator, LiquidationFeatures}; +/// +/// fn tick(long_liq: f64, short_liq: f64) -> DerivativesTick { +/// DerivativesTick::new( +/// 0.0, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, long_liq, short_liq, 0, +/// ) +/// .unwrap() +/// } +/// +/// let mut liq = LiquidationFeatures::new(); +/// // 30 long vs 10 short liquidated: net 20, total 40, imbalance 0.5. +/// let out = liq.update(tick(30.0, 10.0)).unwrap(); +/// assert_eq!(out.net, 20.0); +/// assert_eq!(out.total, 40.0); +/// assert_eq!(out.imbalance, 0.5); +/// ``` +#[derive(Debug, Clone, Default)] +pub struct LiquidationFeatures { + has_emitted: bool, +} + +impl LiquidationFeatures { + /// Construct a new liquidation-features indicator. + #[must_use] + pub const fn new() -> Self { + Self { has_emitted: false } + } +} + +impl Indicator for LiquidationFeatures { + type Input = DerivativesTick; + type Output = LiquidationFeaturesOutput; + + fn update(&mut self, tick: DerivativesTick) -> Option { + self.has_emitted = true; + let long = tick.long_liquidation; + let short = tick.short_liquidation; + let net = long - short; + let total = long + short; + let imbalance = if total == 0.0 { 0.0 } else { net / total }; + Some(LiquidationFeaturesOutput { + long, + short, + net, + total, + imbalance, + }) + } + + fn reset(&mut self) { + self.has_emitted = false; + } + + fn warmup_period(&self) -> usize { + 1 + } + + fn is_ready(&self) -> bool { + self.has_emitted + } + + fn name(&self) -> &'static str { + "LiquidationFeatures" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::traits::BatchExt; + + fn tick(long_liq: f64, short_liq: f64) -> DerivativesTick { + DerivativesTick::new_unchecked( + 0.0, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, long_liq, short_liq, 0, + ) + } + + #[test] + fn accessors_and_metadata() { + let liq = LiquidationFeatures::new(); + assert_eq!(liq.name(), "LiquidationFeatures"); + assert_eq!(liq.warmup_period(), 1); + assert!(!liq.is_ready()); + } + + #[test] + fn decomposes_liquidations() { + let mut liq = LiquidationFeatures::new(); + let out = liq.update(tick(30.0, 10.0)).unwrap(); + assert_eq!(out.long, 30.0); + assert_eq!(out.short, 10.0); + assert_eq!(out.net, 20.0); + assert_eq!(out.total, 40.0); + assert_eq!(out.imbalance, 0.5); + assert!(liq.is_ready()); + } + + #[test] + fn short_cascade_is_negative_imbalance() { + let mut liq = LiquidationFeatures::new(); + let out = liq.update(tick(0.0, 50.0)).unwrap(); + assert_eq!(out.net, -50.0); + assert_eq!(out.imbalance, -1.0); + } + + #[test] + fn no_liquidation_is_zero_imbalance() { + let mut liq = LiquidationFeatures::new(); + let out = liq.update(tick(0.0, 0.0)).unwrap(); + assert_eq!(out.total, 0.0); + assert_eq!(out.imbalance, 0.0); + } + + #[test] + fn batch_equals_streaming() { + let ticks: Vec = (0..20) + .map(|i| tick(f64::from(i % 5) * 10.0, f64::from(i % 3) * 10.0)) + .collect(); + let mut a = LiquidationFeatures::new(); + let mut b = LiquidationFeatures::new(); + assert_eq!( + a.batch(&ticks), + ticks.iter().map(|x| b.update(*x)).collect::>() + ); + } + + #[test] + fn reset_clears_state() { + let mut liq = LiquidationFeatures::new(); + liq.update(tick(30.0, 10.0)); + assert!(liq.is_ready()); + liq.reset(); + assert!(!liq.is_ready()); + } +} diff --git a/crates/wickra-core/src/indicators/long_short_ratio.rs b/crates/wickra-core/src/indicators/long_short_ratio.rs new file mode 100644 index 00000000..01367859 --- /dev/null +++ b/crates/wickra-core/src/indicators/long_short_ratio.rs @@ -0,0 +1,138 @@ +//! Long/Short Ratio — aggregate long size relative to short size. + +use crate::derivatives::DerivativesTick; +use crate::traits::Indicator; + +/// Long/Short Ratio — the aggregate long size divided by the aggregate short +/// size carried by each tick. +/// +/// ```text +/// longShortRatio = longSize / shortSize +/// ``` +/// +/// Exchanges publish the long/short account (or position) ratio as a crowd +/// positioning gauge: a ratio above `1` means longs outweigh shorts, below `1` +/// the reverse. Extremes are a contrarian signal — an overwhelmingly long crowd +/// is fuel for a long squeeze. When the short side is zero the ratio is +/// undefined and the indicator reports `0.0`. +/// +/// `Input = DerivativesTick`, `Output = f64`. Stateless; ready after the first +/// tick. +/// +/// # Example +/// +/// ``` +/// use wickra_core::{DerivativesTick, Indicator, LongShortRatio}; +/// +/// fn tick(long: f64, short: f64) -> DerivativesTick { +/// DerivativesTick::new(0.0, 100.0, 100.0, 100.0, 0.0, long, short, 0.0, 0.0, 0.0, 0.0, 0) +/// .unwrap() +/// } +/// +/// let mut lsr = LongShortRatio::new(); +/// // 600 longs vs 400 shorts -> 1.5. +/// assert_eq!(lsr.update(tick(600.0, 400.0)), Some(1.5)); +/// ``` +#[derive(Debug, Clone, Default)] +pub struct LongShortRatio { + has_emitted: bool, +} + +impl LongShortRatio { + /// Construct a new long/short ratio indicator. + #[must_use] + pub const fn new() -> Self { + Self { has_emitted: false } + } +} + +impl Indicator for LongShortRatio { + type Input = DerivativesTick; + type Output = f64; + + fn update(&mut self, tick: DerivativesTick) -> Option { + self.has_emitted = true; + if tick.short_size == 0.0 { + // No short side to divide by: the ratio is undefined. + return Some(0.0); + } + Some(tick.long_size / tick.short_size) + } + + fn reset(&mut self) { + self.has_emitted = false; + } + + fn warmup_period(&self) -> usize { + 1 + } + + fn is_ready(&self) -> bool { + self.has_emitted + } + + fn name(&self) -> &'static str { + "LongShortRatio" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::traits::BatchExt; + + fn tick(long: f64, short: f64) -> DerivativesTick { + DerivativesTick::new_unchecked( + 0.0, 100.0, 100.0, 100.0, 0.0, long, short, 0.0, 0.0, 0.0, 0.0, 0, + ) + } + + #[test] + fn accessors_and_metadata() { + let lsr = LongShortRatio::new(); + assert_eq!(lsr.name(), "LongShortRatio"); + assert_eq!(lsr.warmup_period(), 1); + assert!(!lsr.is_ready()); + } + + #[test] + fn divides_long_by_short() { + let mut lsr = LongShortRatio::new(); + assert_eq!(lsr.update(tick(600.0, 400.0)), Some(1.5)); + assert_eq!(lsr.update(tick(400.0, 800.0)), Some(0.5)); + assert!(lsr.is_ready()); + } + + #[test] + fn zero_short_is_zero() { + let mut lsr = LongShortRatio::new(); + assert_eq!(lsr.update(tick(600.0, 0.0)), Some(0.0)); + } + + #[test] + fn batch_equals_streaming() { + let ticks: Vec = (0..20) + .map(|i| { + tick( + 500.0 + f64::from(i % 5) * 10.0, + 400.0 + f64::from(i % 3) * 10.0, + ) + }) + .collect(); + let mut a = LongShortRatio::new(); + let mut b = LongShortRatio::new(); + assert_eq!( + a.batch(&ticks), + ticks.iter().map(|x| b.update(*x)).collect::>() + ); + } + + #[test] + fn reset_clears_state() { + let mut lsr = LongShortRatio::new(); + lsr.update(tick(600.0, 400.0)); + assert!(lsr.is_ready()); + lsr.reset(); + assert!(!lsr.is_ready()); + } +} diff --git a/crates/wickra-core/src/indicators/mod.rs b/crates/wickra-core/src/indicators/mod.rs index 820a414b..b975b9d7 100644 --- a/crates/wickra-core/src/indicators/mod.rs +++ b/crates/wickra-core/src/indicators/mod.rs @@ -114,6 +114,8 @@ mod linreg; mod linreg_angle; mod linreg_channel; mod linreg_slope; +mod liquidation_features; +mod long_short_ratio; mod ma_envelope; mod macd; mod mama; @@ -135,6 +137,8 @@ mod ob_imbalance_top1; mod ob_imbalance_topn; mod obv; mod oi_delta; +mod oi_price_divergence; +mod oi_weighted; mod omega_ratio; mod opening_range; mod pain_index; @@ -186,6 +190,7 @@ mod stochastic; mod super_smoother; mod super_trend; mod t3; +mod taker_buy_sell_ratio; mod td_combo; mod td_countdown; mod td_demarker; @@ -351,6 +356,8 @@ pub use linreg::LinearRegression; pub use linreg_angle::LinRegAngle; pub use linreg_channel::{LinRegChannel, LinRegChannelOutput}; pub use linreg_slope::LinRegSlope; +pub use liquidation_features::{LiquidationFeatures, LiquidationFeaturesOutput}; +pub use long_short_ratio::LongShortRatio; pub use ma_envelope::{MaEnvelope, MaEnvelopeOutput}; pub use macd::{MacdIndicator, MacdOutput}; pub use mama::{Mama, MamaOutput}; @@ -372,6 +379,8 @@ pub use ob_imbalance_top1::OrderBookImbalanceTop1; pub use ob_imbalance_topn::OrderBookImbalanceTopN; pub use obv::Obv; pub use oi_delta::OpenInterestDelta; +pub use oi_price_divergence::OIPriceDivergence; +pub use oi_weighted::OIWeighted; pub use omega_ratio::OmegaRatio; pub use opening_range::{OpeningRange, OpeningRangeOutput}; pub use pain_index::PainIndex; @@ -423,6 +432,7 @@ pub use stochastic::{Stochastic, StochasticOutput}; pub use super_smoother::SuperSmoother; pub use super_trend::{SuperTrend, SuperTrendOutput}; pub use t3::T3; +pub use taker_buy_sell_ratio::TakerBuySellRatio; pub use td_combo::TdCombo; pub use td_countdown::TdCountdown; pub use td_demarker::TdDeMarker; @@ -769,6 +779,11 @@ pub const FAMILIES: &[(&str, &[&str])] = &[ "FundingRateZScore", "FundingBasis", "OpenInterestDelta", + "OIPriceDivergence", + "OIWeighted", + "LongShortRatio", + "TakerBuySellRatio", + "LiquidationFeatures", ], ), ( @@ -825,6 +840,6 @@ mod family_tests { // the actual indicator count is the early-warning signal that an // indicator was added without being assigned a family. let total: usize = FAMILIES.iter().map(|(_, ns)| ns.len()).sum(); - assert_eq!(total, 232, "FAMILIES total drifted from indicator count"); + assert_eq!(total, 237, "FAMILIES total drifted from indicator count"); } } diff --git a/crates/wickra-core/src/indicators/oi_price_divergence.rs b/crates/wickra-core/src/indicators/oi_price_divergence.rs new file mode 100644 index 00000000..08e0d47d --- /dev/null +++ b/crates/wickra-core/src/indicators/oi_price_divergence.rs @@ -0,0 +1,193 @@ +//! Open-Interest / Price Divergence — relative OI change minus relative price +//! change over a window. + +use std::collections::VecDeque; + +use crate::derivatives::DerivativesTick; +use crate::error::{Error, Result}; +use crate::traits::Indicator; + +/// Open-Interest / Price Divergence — the gap between how fast open interest and +/// the mark price have moved over the trailing window of `window` ticks. +/// +/// ```text +/// oiChange = (openInterestₜ − openInterestₜ₋ₙ) / openInterestₜ₋ₙ +/// priceChange = (markPriceₜ − markPriceₜ₋ₙ) / markPriceₜ₋ₙ +/// divergence = oiChange − priceChange (n = window) +/// ``` +/// +/// Reading the two together is a classic positioning signal: open interest +/// rising while price falls (a positive divergence) marks fresh shorts piling +/// in; open interest falling while price rises marks a short squeeze / unwind. +/// A value near zero means OI and price moved in step. If the reference open +/// interest is zero, the OI term contributes zero (no base to grow from). +/// +/// The indicator warms up for `window + 1` ticks — `update` returns `None` until +/// the window spans a full `window`-tick lookback — then emits the divergence, +/// maintained in O(1) per tick via a ring buffer. +/// +/// `Input = DerivativesTick`, `Output = f64`. +/// +/// # Example +/// +/// ``` +/// use wickra_core::{DerivativesTick, Indicator, OIPriceDivergence}; +/// +/// fn tick(oi: f64, mark: f64) -> DerivativesTick { +/// DerivativesTick::new(0.0, mark, mark, mark, oi, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0) +/// .unwrap() +/// } +/// +/// let mut div = OIPriceDivergence::new(1).unwrap(); +/// assert_eq!(div.update(tick(1_000.0, 100.0)), None); +/// // OI +10% while price flat -> divergence +0.1. +/// assert!((div.update(tick(1_100.0, 100.0)).unwrap() - 0.1).abs() < 1e-12); +/// ``` +#[derive(Debug, Clone)] +pub struct OIPriceDivergence { + window: usize, + history: VecDeque<(f64, f64)>, +} + +impl OIPriceDivergence { + /// Construct an OI / price divergence over a window of `window` ticks. + /// + /// # Errors + /// + /// Returns [`Error::PeriodZero`] if `window` is zero. + pub fn new(window: usize) -> Result { + if window == 0 { + return Err(Error::PeriodZero); + } + Ok(Self { + window, + history: VecDeque::with_capacity(window + 1), + }) + } + + /// The configured window length, in ticks. + #[must_use] + pub fn window(&self) -> usize { + self.window + } +} + +impl Indicator for OIPriceDivergence { + type Input = DerivativesTick; + type Output = f64; + + fn update(&mut self, tick: DerivativesTick) -> Option { + self.history + .push_back((tick.open_interest, tick.mark_price)); + if self.history.len() > self.window + 1 { + self.history.pop_front(); + } + if self.history.len() < self.window + 1 { + return None; + } + let (old_oi, old_mark) = *self.history.front().expect("len == window + 1"); + let (cur_oi, cur_mark) = *self.history.back().expect("len == window + 1"); + // Open interest can legitimately be zero; with no base there is no + // relative change to report from it. + let oi_change = if old_oi == 0.0 { + 0.0 + } else { + (cur_oi - old_oi) / old_oi + }; + // The mark price is finite and positive by `DerivativesTick` + // construction, so the denominator is always well-defined. + let price_change = (cur_mark - old_mark) / old_mark; + Some(oi_change - price_change) + } + + fn reset(&mut self) { + self.history.clear(); + } + + fn warmup_period(&self) -> usize { + self.window + 1 + } + + fn is_ready(&self) -> bool { + self.history.len() == self.window + 1 + } + + fn name(&self) -> &'static str { + "OIPriceDivergence" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::traits::BatchExt; + + fn tick(oi: f64, mark: f64) -> DerivativesTick { + DerivativesTick::new_unchecked(0.0, mark, mark, mark, oi, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0) + } + + #[test] + fn rejects_zero_window() { + assert!(matches!(OIPriceDivergence::new(0), Err(Error::PeriodZero))); + } + + #[test] + fn accessors_and_metadata() { + let div = OIPriceDivergence::new(5).unwrap(); + assert_eq!(div.name(), "OIPriceDivergence"); + assert_eq!(div.warmup_period(), 6); + assert_eq!(div.window(), 5); + assert!(!div.is_ready()); + } + + #[test] + fn oi_up_price_flat_is_positive() { + let mut div = OIPriceDivergence::new(1).unwrap(); + assert_eq!(div.update(tick(1_000.0, 100.0)), None); + let out = div.update(tick(1_100.0, 100.0)).unwrap(); + assert!((out - 0.1).abs() < 1e-12); + assert!(div.is_ready()); + } + + #[test] + fn oi_flat_price_up_is_negative() { + let mut div = OIPriceDivergence::new(1).unwrap(); + div.update(tick(1_000.0, 100.0)); + // OI flat, price +10% -> divergence -0.1. + let out = div.update(tick(1_000.0, 110.0)).unwrap(); + assert!((out + 0.1).abs() < 1e-12); + } + + #[test] + fn zero_reference_oi_drops_oi_term() { + let mut div = OIPriceDivergence::new(1).unwrap(); + div.update(tick(0.0, 100.0)); + // Reference OI is zero -> only the price term contributes: -(110-100)/100. + let out = div.update(tick(500.0, 110.0)).unwrap(); + assert!((out + 0.1).abs() < 1e-12); + } + + #[test] + fn batch_equals_streaming() { + let ticks: Vec = (0..30) + .map(|i| tick(1_000.0 + f64::from(i % 7) * 10.0, 100.0 + f64::from(i % 5))) + .collect(); + let mut a = OIPriceDivergence::new(4).unwrap(); + let mut b = OIPriceDivergence::new(4).unwrap(); + assert_eq!( + a.batch(&ticks), + ticks.iter().map(|x| b.update(*x)).collect::>() + ); + } + + #[test] + fn reset_clears_state() { + let mut div = OIPriceDivergence::new(1).unwrap(); + div.update(tick(1_000.0, 100.0)); + div.update(tick(1_100.0, 100.0)); + assert!(div.is_ready()); + div.reset(); + assert!(!div.is_ready()); + assert_eq!(div.update(tick(1_000.0, 100.0)), None); + } +} diff --git a/crates/wickra-core/src/indicators/oi_weighted.rs b/crates/wickra-core/src/indicators/oi_weighted.rs new file mode 100644 index 00000000..635f59bf --- /dev/null +++ b/crates/wickra-core/src/indicators/oi_weighted.rs @@ -0,0 +1,151 @@ +//! Open-Interest-Weighted Price — cumulative mark price weighted by open +//! interest. + +use crate::derivatives::DerivativesTick; +use crate::traits::Indicator; + +/// Open-Interest-Weighted Price — the running mean mark price, weighting each +/// tick by its open interest. +/// +/// ```text +/// oiWeighted = Σ(markPrice · openInterest) / Σ openInterest +/// ``` +/// +/// Where a plain mean treats every tick equally, the OI-weighted price pulls +/// toward the levels at which the most contracts were actually outstanding — the +/// price the bulk of open positioning sits around, a fair-value anchor for +/// liquidations and mean-reversion. The accumulation runs from construction; +/// call [`reset`] at each session boundary to re-anchor. Until any open interest +/// has accrued the indicator returns the current mark price. +/// +/// `Input = DerivativesTick`, `Output = f64`. Ready after the first tick. +/// +/// [`reset`]: crate::Indicator::reset +/// +/// # Example +/// +/// ``` +/// use wickra_core::{DerivativesTick, Indicator, OIWeighted}; +/// +/// fn tick(mark: f64, oi: f64) -> DerivativesTick { +/// DerivativesTick::new(0.0, mark, mark, mark, oi, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0) +/// .unwrap() +/// } +/// +/// let mut oiw = OIWeighted::new(); +/// assert_eq!(oiw.update(tick(100.0, 10.0)), Some(100.0)); +/// // (100·10 + 110·30) / (10 + 30) = 4300 / 40 = 107.5. +/// assert_eq!(oiw.update(tick(110.0, 30.0)), Some(107.5)); +/// ``` +#[derive(Debug, Clone, Default)] +pub struct OIWeighted { + sum_weighted: f64, + sum_oi: f64, + has_emitted: bool, +} + +impl OIWeighted { + /// Construct a new OI-weighted price indicator. + #[must_use] + pub const fn new() -> Self { + Self { + sum_weighted: 0.0, + sum_oi: 0.0, + has_emitted: false, + } + } +} + +impl Indicator for OIWeighted { + type Input = DerivativesTick; + type Output = f64; + + fn update(&mut self, tick: DerivativesTick) -> Option { + self.has_emitted = true; + self.sum_weighted += tick.mark_price * tick.open_interest; + self.sum_oi += tick.open_interest; + if self.sum_oi == 0.0 { + // No open interest has accrued yet: fall back to the mark price. + return Some(tick.mark_price); + } + Some(self.sum_weighted / self.sum_oi) + } + + fn reset(&mut self) { + self.sum_weighted = 0.0; + self.sum_oi = 0.0; + self.has_emitted = false; + } + + fn warmup_period(&self) -> usize { + 1 + } + + fn is_ready(&self) -> bool { + self.has_emitted + } + + fn name(&self) -> &'static str { + "OIWeighted" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::traits::BatchExt; + + fn tick(mark: f64, oi: f64) -> DerivativesTick { + DerivativesTick::new_unchecked(0.0, mark, mark, mark, oi, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0) + } + + #[test] + fn accessors_and_metadata() { + let oiw = OIWeighted::new(); + assert_eq!(oiw.name(), "OIWeighted"); + assert_eq!(oiw.warmup_period(), 1); + assert!(!oiw.is_ready()); + } + + #[test] + fn weights_by_open_interest() { + let mut oiw = OIWeighted::new(); + assert_eq!(oiw.update(tick(100.0, 10.0)), Some(100.0)); + // (100·10 + 110·30) / 40 = 107.5. + assert_eq!(oiw.update(tick(110.0, 30.0)), Some(107.5)); + assert!(oiw.is_ready()); + } + + #[test] + fn zero_open_interest_falls_back_to_mark() { + let mut oiw = OIWeighted::new(); + assert_eq!(oiw.update(tick(123.0, 0.0)), Some(123.0)); + // Still no OI on the second zero-OI tick. + assert_eq!(oiw.update(tick(125.0, 0.0)), Some(125.0)); + } + + #[test] + fn batch_equals_streaming() { + let ticks: Vec = (0..20) + .map(|i| tick(100.0 + f64::from(i % 5), 1.0 + f64::from(i % 4))) + .collect(); + let mut a = OIWeighted::new(); + let mut b = OIWeighted::new(); + assert_eq!( + a.batch(&ticks), + ticks.iter().map(|x| b.update(*x)).collect::>() + ); + } + + #[test] + fn reset_re_anchors() { + let mut oiw = OIWeighted::new(); + oiw.update(tick(100.0, 10.0)); + oiw.update(tick(110.0, 30.0)); + assert!(oiw.is_ready()); + oiw.reset(); + assert!(!oiw.is_ready()); + // After reset the accumulation starts again from the next tick. + assert_eq!(oiw.update(tick(200.0, 5.0)), Some(200.0)); + } +} diff --git a/crates/wickra-core/src/indicators/taker_buy_sell_ratio.rs b/crates/wickra-core/src/indicators/taker_buy_sell_ratio.rs new file mode 100644 index 00000000..5df80105 --- /dev/null +++ b/crates/wickra-core/src/indicators/taker_buy_sell_ratio.rs @@ -0,0 +1,137 @@ +//! Taker Buy/Sell Ratio — aggressive buy volume relative to aggressive sell +//! volume. + +use crate::derivatives::DerivativesTick; +use crate::traits::Indicator; + +/// Taker Buy/Sell Ratio — the taker (market-order) buy volume divided by the +/// taker sell volume carried by each tick. +/// +/// ```text +/// takerBuySellRatio = takerBuyVolume / takerSellVolume +/// ``` +/// +/// Taker volume is the volume that crossed the spread — the aggressive flow that +/// moves price. A ratio above `1` means buyers are lifting offers faster than +/// sellers are hitting bids (net aggressive buying); below `1` the reverse. It +/// is the perpetual-feed analogue of [trade imbalance], read straight off the +/// venue's taker-volume fields. When taker sell volume is zero the ratio is +/// undefined and the indicator reports `0.0`. +/// +/// `Input = DerivativesTick`, `Output = f64`. Stateless; ready after the first +/// tick. +/// +/// [trade imbalance]: crate::TradeImbalance +/// +/// # Example +/// +/// ``` +/// use wickra_core::{DerivativesTick, Indicator, TakerBuySellRatio}; +/// +/// fn tick(buy: f64, sell: f64) -> DerivativesTick { +/// DerivativesTick::new(0.0, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, buy, sell, 0.0, 0.0, 0) +/// .unwrap() +/// } +/// +/// let mut tbs = TakerBuySellRatio::new(); +/// // 60 taker buys vs 40 taker sells -> 1.5. +/// assert_eq!(tbs.update(tick(60.0, 40.0)), Some(1.5)); +/// ``` +#[derive(Debug, Clone, Default)] +pub struct TakerBuySellRatio { + has_emitted: bool, +} + +impl TakerBuySellRatio { + /// Construct a new taker buy/sell ratio indicator. + #[must_use] + pub const fn new() -> Self { + Self { has_emitted: false } + } +} + +impl Indicator for TakerBuySellRatio { + type Input = DerivativesTick; + type Output = f64; + + fn update(&mut self, tick: DerivativesTick) -> Option { + self.has_emitted = true; + if tick.taker_sell_volume == 0.0 { + // No taker sell volume to divide by: the ratio is undefined. + return Some(0.0); + } + Some(tick.taker_buy_volume / tick.taker_sell_volume) + } + + fn reset(&mut self) { + self.has_emitted = false; + } + + fn warmup_period(&self) -> usize { + 1 + } + + fn is_ready(&self) -> bool { + self.has_emitted + } + + fn name(&self) -> &'static str { + "TakerBuySellRatio" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::traits::BatchExt; + + fn tick(buy: f64, sell: f64) -> DerivativesTick { + DerivativesTick::new_unchecked( + 0.0, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, buy, sell, 0.0, 0.0, 0, + ) + } + + #[test] + fn accessors_and_metadata() { + let tbs = TakerBuySellRatio::new(); + assert_eq!(tbs.name(), "TakerBuySellRatio"); + assert_eq!(tbs.warmup_period(), 1); + assert!(!tbs.is_ready()); + } + + #[test] + fn divides_buy_by_sell() { + let mut tbs = TakerBuySellRatio::new(); + assert_eq!(tbs.update(tick(60.0, 40.0)), Some(1.5)); + assert_eq!(tbs.update(tick(20.0, 80.0)), Some(0.25)); + assert!(tbs.is_ready()); + } + + #[test] + fn zero_sell_is_zero() { + let mut tbs = TakerBuySellRatio::new(); + assert_eq!(tbs.update(tick(60.0, 0.0)), Some(0.0)); + } + + #[test] + fn batch_equals_streaming() { + let ticks: Vec = (0..20) + .map(|i| tick(50.0 + f64::from(i % 5) * 5.0, 40.0 + f64::from(i % 3) * 5.0)) + .collect(); + let mut a = TakerBuySellRatio::new(); + let mut b = TakerBuySellRatio::new(); + assert_eq!( + a.batch(&ticks), + ticks.iter().map(|x| b.update(*x)).collect::>() + ); + } + + #[test] + fn reset_clears_state() { + let mut tbs = TakerBuySellRatio::new(); + tbs.update(tick(60.0, 40.0)); + assert!(tbs.is_ready()); + tbs.reset(); + assert!(!tbs.is_ready()); + } +} diff --git a/crates/wickra-core/src/lib.rs b/crates/wickra-core/src/lib.rs index 65d62e1c..c861e49f 100644 --- a/crates/wickra-core/src/lib.rs +++ b/crates/wickra-core/src/lib.rs @@ -69,25 +69,27 @@ pub use indicators::{ InitialBalance, InitialBalanceOutput, InstantaneousTrendline, InverseFisherTransform, InvertedHammer, Jma, Kama, KellyCriterion, Keltner, KeltnerOutput, Kst, KstOutput, Kurtosis, Kvo, KylesLambda, LaguerreRsi, LeadLagCrossCorrelation, LeadLagCrossCorrelationOutput, - LinRegAngle, LinRegChannel, LinRegChannelOutput, LinRegSlope, LinearRegression, MaEnvelope, - MaEnvelopeOutput, MacdIndicator, MacdOutput, Mama, MamaOutput, MarketFacilitationIndex, - Marubozu, MassIndex, MaxDrawdown, McGinleyDynamic, MedianAbsoluteDeviation, MedianPrice, Mfi, - Microprice, Mom, MorningEveningStar, Natr, Nvi, Obv, OmegaRatio, OpenInterestDelta, - OpeningRange, OpeningRangeOutput, OrderBookImbalanceFull, OrderBookImbalanceTop1, - OrderBookImbalanceTopN, PainIndex, PairSpreadZScore, PairwiseBeta, ParkinsonVolatility, - PearsonCorrelation, PercentB, PercentageTrailingStop, Pgo, PiercingDarkCloud, Pmo, Ppo, - ProfitFactor, Psar, Pvi, QuotedSpread, RSquared, RealizedSpread, RecoveryFactor, - RelativeStrengthAB, RelativeStrengthOutput, RenkoTrailingStop, Roc, RogersSatchellVolatility, - RollingVwap, RoofingFilter, Rsi, Rvi, RviVolatility, Rwi, RwiOutput, SharpeRatio, ShootingStar, - SignedVolume, SineWave, Skewness, Sma, Smi, Smma, SortinoRatio, SpearmanCorrelation, - SpinningTop, StandardError, StandardErrorBands, StandardErrorBandsOutput, StarcBands, - StarcBandsOutput, Stc, StdDev, StepTrailingStop, StochRsi, Stochastic, StochasticOutput, - SuperSmoother, SuperTrend, SuperTrendOutput, TdCombo, TdCountdown, TdDeMarker, TdDifferential, - TdLines, TdLinesOutput, TdOpen, TdPressure, TdRangeProjection, TdRangeProjectionOutput, TdRei, - TdRiskLevel, TdRiskLevelOutput, TdSequential, TdSequentialOutput, TdSetup, Tema, ThreeInside, - ThreeOutside, ThreeSoldiersOrCrows, Tii, TradeImbalance, TreynorRatio, Trima, Trix, TrueRange, - Tsi, Tsv, TtmSqueeze, TtmSqueezeOutput, Tweezer, TypicalPrice, UlcerIndex, UltimateOscillator, - ValueArea, ValueAreaOutput, ValueAtRisk, Variance, VerticalHorizontalFilter, Vidya, VoltyStop, + LinRegAngle, LinRegChannel, LinRegChannelOutput, LinRegSlope, LinearRegression, + LiquidationFeatures, LiquidationFeaturesOutput, LongShortRatio, MaEnvelope, MaEnvelopeOutput, + MacdIndicator, MacdOutput, Mama, MamaOutput, MarketFacilitationIndex, Marubozu, MassIndex, + MaxDrawdown, McGinleyDynamic, MedianAbsoluteDeviation, MedianPrice, Mfi, Microprice, Mom, + MorningEveningStar, Natr, Nvi, OIPriceDivergence, OIWeighted, Obv, OmegaRatio, + OpenInterestDelta, OpeningRange, OpeningRangeOutput, OrderBookImbalanceFull, + OrderBookImbalanceTop1, OrderBookImbalanceTopN, PainIndex, PairSpreadZScore, PairwiseBeta, + ParkinsonVolatility, PearsonCorrelation, PercentB, PercentageTrailingStop, Pgo, + PiercingDarkCloud, Pmo, Ppo, ProfitFactor, Psar, Pvi, QuotedSpread, RSquared, RealizedSpread, + RecoveryFactor, RelativeStrengthAB, RelativeStrengthOutput, RenkoTrailingStop, Roc, + RogersSatchellVolatility, RollingVwap, RoofingFilter, Rsi, Rvi, RviVolatility, Rwi, RwiOutput, + SharpeRatio, ShootingStar, SignedVolume, SineWave, Skewness, Sma, Smi, Smma, SortinoRatio, + SpearmanCorrelation, SpinningTop, StandardError, StandardErrorBands, StandardErrorBandsOutput, + StarcBands, StarcBandsOutput, Stc, StdDev, StepTrailingStop, StochRsi, Stochastic, + StochasticOutput, SuperSmoother, SuperTrend, SuperTrendOutput, TakerBuySellRatio, TdCombo, + TdCountdown, TdDeMarker, TdDifferential, TdLines, TdLinesOutput, TdOpen, TdPressure, + TdRangeProjection, TdRangeProjectionOutput, TdRei, TdRiskLevel, TdRiskLevelOutput, + TdSequential, TdSequentialOutput, TdSetup, Tema, ThreeInside, ThreeOutside, + ThreeSoldiersOrCrows, Tii, TradeImbalance, TreynorRatio, Trima, Trix, TrueRange, Tsi, Tsv, + TtmSqueeze, TtmSqueezeOutput, Tweezer, TypicalPrice, UlcerIndex, UltimateOscillator, ValueArea, + ValueAreaOutput, ValueAtRisk, Variance, VerticalHorizontalFilter, Vidya, VoltyStop, VolumeOscillator, VolumePriceTrend, Vortex, VortexOutput, Vwap, VwapStdDevBands, VwapStdDevBandsOutput, Vwma, Vzo, WaveTrend, WaveTrendOutput, WeightedClose, WilliamsFractals, WilliamsFractalsOutput, WilliamsR, Wma, WoodiePivots, WoodiePivotsOutput, YangZhangVolatility, diff --git a/fuzz/fuzz_targets/indicator_update_derivatives.rs b/fuzz/fuzz_targets/indicator_update_derivatives.rs index 5271feb4..ed4a86dc 100644 --- a/fuzz/fuzz_targets/indicator_update_derivatives.rs +++ b/fuzz/fuzz_targets/indicator_update_derivatives.rs @@ -12,7 +12,8 @@ use libfuzzer_sys::fuzz_target; use wickra_core::{ BatchExt, DerivativesTick, FundingBasis, FundingRate, FundingRateMean, FundingRateZScore, - Indicator, OpenInterestDelta, + Indicator, LiquidationFeatures, LongShortRatio, OIPriceDivergence, OIWeighted, + OpenInterestDelta, TakerBuySellRatio, }; #[inline(never)] @@ -46,4 +47,15 @@ fuzz_target!(|data: &[u8]| { drive(|| FundingRateZScore::new(5).unwrap(), &ticks); drive(FundingBasis::new, &ticks); drive(OpenInterestDelta::new, &ticks); + drive(|| OIPriceDivergence::new(5).unwrap(), &ticks); + drive(OIWeighted::new, &ticks); + drive(LongShortRatio::new, &ticks); + drive(TakerBuySellRatio::new, &ticks); + + // LiquidationFeatures emits a struct, not an f64, so drive it directly. + let mut liq = LiquidationFeatures::new(); + for &tick in &ticks { + let _ = liq.update(tick); + } + let _ = LiquidationFeatures::new().batch(&ticks); });