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:
@@ -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,
|
- **Funding Basis** — the perpetual's relative premium to spot,
|
||||||
`(markPrice − indexPrice) / indexPrice`.
|
`(markPrice − indexPrice) / indexPrice`.
|
||||||
- **Open-Interest Delta** — the tick-over-tick change in open interest.
|
- **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
|
## [0.4.3] - 2026-06-01
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://wickra.org"><img src="https://raw.githubusercontent.com/wickra-lib/.github/main/profile/wickra-banner.webp?v=237" alt="Wickra — streaming-first technical indicators" width="100%"></a>
|
<a href="https://wickra.org"><img src="https://raw.githubusercontent.com/wickra-lib/.github/main/profile/wickra-banner.webp?v=242" alt="Wickra — streaming-first technical indicators" width="100%"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
[](https://github.com/wickra-lib/wickra/actions/workflows/ci.yml)
|
[](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),
|
[Node](https://docs.wickra.org/Quickstart-Node),
|
||||||
[WASM](https://docs.wickra.org/Quickstart-WASM).
|
[WASM](https://docs.wickra.org/Quickstart-WASM).
|
||||||
- **Indicators** — a per-indicator deep dive (formula, parameters, warmup) for
|
- **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).
|
[indicators overview](https://docs.wickra.org/Indicators-Overview).
|
||||||
- **Reference** — [warmup periods](https://docs.wickra.org/Warmup-Periods),
|
- **Reference** — [warmup periods](https://docs.wickra.org/Warmup-Periods),
|
||||||
[streaming vs batch](https://docs.wickra.org/Streaming-vs-Batch),
|
[streaming vs batch](https://docs.wickra.org/Streaming-vs-Batch),
|
||||||
@@ -135,7 +135,7 @@ python -m benchmarks.compare_libraries
|
|||||||
|
|
||||||
## Indicators
|
## 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
|
`batch == streaming` equivalence test, reference-value tests, and reset
|
||||||
semantics tests. Each has a per-indicator deep dive (formula, parameters,
|
semantics tests. Each has a per-indicator deep dive (formula, parameters,
|
||||||
warmup) at [docs.wickra.org](https://docs.wickra.org/Indicators-Overview).
|
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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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) |
|
| 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/
|
wickra/
|
||||||
├── crates/
|
├── 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/ top-level facade crate (publishes on crates.io) + benches/
|
||||||
│ └── wickra-data/ CSV reader, tick aggregator, live exchange feeds
|
│ └── wickra-data/ CSV reader, tick aggregator, live exchange feeds
|
||||||
├── bindings/
|
├── bindings/
|
||||||
|
|||||||
@@ -1136,3 +1136,42 @@ test('derivatives reject bad input', () => {
|
|||||||
assert.throws(() => new wickra.FundingRateZScore(0));
|
assert.throws(() => new wickra.FundingRateZScore(0));
|
||||||
assert.throws(() => new wickra.FundingBasis().update(100, 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));
|
||||||
|
});
|
||||||
|
|||||||
Vendored
+53
@@ -292,6 +292,14 @@ export interface FootprintLevelValue {
|
|||||||
bidVol: number
|
bidVol: number
|
||||||
askVol: 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 type SmaNode = SMA
|
||||||
export declare class SMA {
|
export declare class SMA {
|
||||||
constructor(period: number)
|
constructor(period: number)
|
||||||
@@ -2364,6 +2372,51 @@ export declare class OpenInterestDelta {
|
|||||||
isReady(): boolean
|
isReady(): boolean
|
||||||
warmupPeriod(): number
|
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 type SharpeRatioNode = SharpeRatio
|
||||||
export declare class SharpeRatio {
|
export declare class SharpeRatio {
|
||||||
constructor(period: number, riskFree: number)
|
constructor(period: number, riskFree: number)
|
||||||
|
|||||||
@@ -310,7 +310,7 @@ if (!nativeBinding) {
|
|||||||
throw new Error(`Failed to load native binding`)
|
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.version = version
|
||||||
module.exports.SMA = SMA
|
module.exports.SMA = SMA
|
||||||
@@ -533,6 +533,11 @@ module.exports.FundingRateMean = FundingRateMean
|
|||||||
module.exports.FundingRateZScore = FundingRateZScore
|
module.exports.FundingRateZScore = FundingRateZScore
|
||||||
module.exports.FundingBasis = FundingBasis
|
module.exports.FundingBasis = FundingBasis
|
||||||
module.exports.OpenInterestDelta = OpenInterestDelta
|
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.SharpeRatio = SharpeRatio
|
||||||
module.exports.SortinoRatio = SortinoRatio
|
module.exports.SortinoRatio = SortinoRatio
|
||||||
module.exports.CalmarRatio = CalmarRatio
|
module.exports.CalmarRatio = CalmarRatio
|
||||||
|
|||||||
@@ -9413,6 +9413,70 @@ fn deriv_oi(open_interest: f64) -> napi::Result<wc::DerivativesTick> {
|
|||||||
.map_err(map_err)
|
.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")]
|
#[napi(js_name = "FundingRate")]
|
||||||
pub struct FundingRateNode {
|
pub struct FundingRateNode {
|
||||||
inner: wc::FundingRate,
|
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 ==============================
|
// ============================== Family 15: Risk / Performance ==============================
|
||||||
|
|
||||||
// Risk metrics with fallible `new` (most need `period >= 2`), so each wrapper
|
// Risk metrics with fallible `new` (most need `period >= 2`), so each wrapper
|
||||||
|
|||||||
@@ -263,6 +263,11 @@ from ._wickra import (
|
|||||||
FundingRateZScore,
|
FundingRateZScore,
|
||||||
FundingBasis,
|
FundingBasis,
|
||||||
OpenInterestDelta,
|
OpenInterestDelta,
|
||||||
|
OIPriceDivergence,
|
||||||
|
OIWeighted,
|
||||||
|
LongShortRatio,
|
||||||
|
TakerBuySellRatio,
|
||||||
|
LiquidationFeatures,
|
||||||
# Risk / Performance
|
# Risk / Performance
|
||||||
SharpeRatio,
|
SharpeRatio,
|
||||||
SortinoRatio,
|
SortinoRatio,
|
||||||
@@ -523,6 +528,11 @@ __all__ = [
|
|||||||
"FundingRateZScore",
|
"FundingRateZScore",
|
||||||
"FundingBasis",
|
"FundingBasis",
|
||||||
"OpenInterestDelta",
|
"OpenInterestDelta",
|
||||||
|
"OIPriceDivergence",
|
||||||
|
"OIWeighted",
|
||||||
|
"LongShortRatio",
|
||||||
|
"TakerBuySellRatio",
|
||||||
|
"LiquidationFeatures",
|
||||||
# Risk / Performance
|
# Risk / Performance
|
||||||
"SharpeRatio",
|
"SharpeRatio",
|
||||||
"SortinoRatio",
|
"SortinoRatio",
|
||||||
|
|||||||
@@ -12244,6 +12244,70 @@ fn deriv_oi(open_interest: f64) -> PyResult<wc::DerivativesTick> {
|
|||||||
.map_err(map_err)
|
.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`
|
// FundingRate takes no parameters; streaming `update(funding_rate)`, `batch`
|
||||||
// over one funding-rate array.
|
// over one funding-rate array.
|
||||||
#[pyclass(name = "FundingRate", module = "wickra._wickra", skip_from_py_object)]
|
#[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 ==============================
|
// ============================== Family 15: Risk / Performance ==============================
|
||||||
|
|
||||||
#[pyclass(name = "SharpeRatio", module = "wickra._wickra", skip_from_py_object)]
|
#[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::<PyFundingRateZScore>()?;
|
||||||
m.add_class::<PyFundingBasis>()?;
|
m.add_class::<PyFundingBasis>()?;
|
||||||
m.add_class::<PyOpenInterestDelta>()?;
|
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.
|
// Family 15: Risk / Performance metrics.
|
||||||
m.add_class::<PySharpeRatio>()?;
|
m.add_class::<PySharpeRatio>()?;
|
||||||
m.add_class::<PySortinoRatio>()?;
|
m.add_class::<PySortinoRatio>()?;
|
||||||
|
|||||||
@@ -258,3 +258,13 @@ def test_funding_basis_non_positive_index_raises():
|
|||||||
def test_funding_rate_non_finite_raises():
|
def test_funding_rate_non_finite_raises():
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
ta.FundingRate().update(float("nan"))
|
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(1000.0) is None # seeds the previous OI
|
||||||
assert oid.update(1250.0) == pytest.approx(250.0)
|
assert oid.update(1250.0) == pytest.approx(250.0)
|
||||||
assert oid.update(1100.0) == pytest.approx(-150.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)
|
streamed = np.array([streamer.update(oi[i]) for i in range(n)], dtype=np.float64)
|
||||||
assert batch.shape == (n,)
|
assert batch.shape == (n,)
|
||||||
assert _eq_nan(batch, streamed)
|
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)
|
||||||
|
|||||||
@@ -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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -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<LiquidationFeaturesOutput> {
|
||||||
|
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<DerivativesTick> = (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::<Vec<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<f64> {
|
||||||
|
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<DerivativesTick> = (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::<Vec<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -114,6 +114,8 @@ mod linreg;
|
|||||||
mod linreg_angle;
|
mod linreg_angle;
|
||||||
mod linreg_channel;
|
mod linreg_channel;
|
||||||
mod linreg_slope;
|
mod linreg_slope;
|
||||||
|
mod liquidation_features;
|
||||||
|
mod long_short_ratio;
|
||||||
mod ma_envelope;
|
mod ma_envelope;
|
||||||
mod macd;
|
mod macd;
|
||||||
mod mama;
|
mod mama;
|
||||||
@@ -135,6 +137,8 @@ mod ob_imbalance_top1;
|
|||||||
mod ob_imbalance_topn;
|
mod ob_imbalance_topn;
|
||||||
mod obv;
|
mod obv;
|
||||||
mod oi_delta;
|
mod oi_delta;
|
||||||
|
mod oi_price_divergence;
|
||||||
|
mod oi_weighted;
|
||||||
mod omega_ratio;
|
mod omega_ratio;
|
||||||
mod opening_range;
|
mod opening_range;
|
||||||
mod pain_index;
|
mod pain_index;
|
||||||
@@ -186,6 +190,7 @@ mod stochastic;
|
|||||||
mod super_smoother;
|
mod super_smoother;
|
||||||
mod super_trend;
|
mod super_trend;
|
||||||
mod t3;
|
mod t3;
|
||||||
|
mod taker_buy_sell_ratio;
|
||||||
mod td_combo;
|
mod td_combo;
|
||||||
mod td_countdown;
|
mod td_countdown;
|
||||||
mod td_demarker;
|
mod td_demarker;
|
||||||
@@ -351,6 +356,8 @@ pub use linreg::LinearRegression;
|
|||||||
pub use linreg_angle::LinRegAngle;
|
pub use linreg_angle::LinRegAngle;
|
||||||
pub use linreg_channel::{LinRegChannel, LinRegChannelOutput};
|
pub use linreg_channel::{LinRegChannel, LinRegChannelOutput};
|
||||||
pub use linreg_slope::LinRegSlope;
|
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 ma_envelope::{MaEnvelope, MaEnvelopeOutput};
|
||||||
pub use macd::{MacdIndicator, MacdOutput};
|
pub use macd::{MacdIndicator, MacdOutput};
|
||||||
pub use mama::{Mama, MamaOutput};
|
pub use mama::{Mama, MamaOutput};
|
||||||
@@ -372,6 +379,8 @@ pub use ob_imbalance_top1::OrderBookImbalanceTop1;
|
|||||||
pub use ob_imbalance_topn::OrderBookImbalanceTopN;
|
pub use ob_imbalance_topn::OrderBookImbalanceTopN;
|
||||||
pub use obv::Obv;
|
pub use obv::Obv;
|
||||||
pub use oi_delta::OpenInterestDelta;
|
pub use oi_delta::OpenInterestDelta;
|
||||||
|
pub use oi_price_divergence::OIPriceDivergence;
|
||||||
|
pub use oi_weighted::OIWeighted;
|
||||||
pub use omega_ratio::OmegaRatio;
|
pub use omega_ratio::OmegaRatio;
|
||||||
pub use opening_range::{OpeningRange, OpeningRangeOutput};
|
pub use opening_range::{OpeningRange, OpeningRangeOutput};
|
||||||
pub use pain_index::PainIndex;
|
pub use pain_index::PainIndex;
|
||||||
@@ -423,6 +432,7 @@ pub use stochastic::{Stochastic, StochasticOutput};
|
|||||||
pub use super_smoother::SuperSmoother;
|
pub use super_smoother::SuperSmoother;
|
||||||
pub use super_trend::{SuperTrend, SuperTrendOutput};
|
pub use super_trend::{SuperTrend, SuperTrendOutput};
|
||||||
pub use t3::T3;
|
pub use t3::T3;
|
||||||
|
pub use taker_buy_sell_ratio::TakerBuySellRatio;
|
||||||
pub use td_combo::TdCombo;
|
pub use td_combo::TdCombo;
|
||||||
pub use td_countdown::TdCountdown;
|
pub use td_countdown::TdCountdown;
|
||||||
pub use td_demarker::TdDeMarker;
|
pub use td_demarker::TdDeMarker;
|
||||||
@@ -769,6 +779,11 @@ pub const FAMILIES: &[(&str, &[&str])] = &[
|
|||||||
"FundingRateZScore",
|
"FundingRateZScore",
|
||||||
"FundingBasis",
|
"FundingBasis",
|
||||||
"OpenInterestDelta",
|
"OpenInterestDelta",
|
||||||
|
"OIPriceDivergence",
|
||||||
|
"OIWeighted",
|
||||||
|
"LongShortRatio",
|
||||||
|
"TakerBuySellRatio",
|
||||||
|
"LiquidationFeatures",
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
@@ -825,6 +840,6 @@ mod family_tests {
|
|||||||
// the actual indicator count is the early-warning signal that an
|
// the actual indicator count is the early-warning signal that an
|
||||||
// indicator was added without being assigned a family.
|
// indicator was added without being assigned a family.
|
||||||
let total: usize = FAMILIES.iter().map(|(_, ns)| ns.len()).sum();
|
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");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<Self> {
|
||||||
|
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<f64> {
|
||||||
|
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<DerivativesTick> = (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::<Vec<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<f64> {
|
||||||
|
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<DerivativesTick> = (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::<Vec<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<f64> {
|
||||||
|
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<DerivativesTick> = (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::<Vec<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,25 +69,27 @@ pub use indicators::{
|
|||||||
InitialBalance, InitialBalanceOutput, InstantaneousTrendline, InverseFisherTransform,
|
InitialBalance, InitialBalanceOutput, InstantaneousTrendline, InverseFisherTransform,
|
||||||
InvertedHammer, Jma, Kama, KellyCriterion, Keltner, KeltnerOutput, Kst, KstOutput, Kurtosis,
|
InvertedHammer, Jma, Kama, KellyCriterion, Keltner, KeltnerOutput, Kst, KstOutput, Kurtosis,
|
||||||
Kvo, KylesLambda, LaguerreRsi, LeadLagCrossCorrelation, LeadLagCrossCorrelationOutput,
|
Kvo, KylesLambda, LaguerreRsi, LeadLagCrossCorrelation, LeadLagCrossCorrelationOutput,
|
||||||
LinRegAngle, LinRegChannel, LinRegChannelOutput, LinRegSlope, LinearRegression, MaEnvelope,
|
LinRegAngle, LinRegChannel, LinRegChannelOutput, LinRegSlope, LinearRegression,
|
||||||
MaEnvelopeOutput, MacdIndicator, MacdOutput, Mama, MamaOutput, MarketFacilitationIndex,
|
LiquidationFeatures, LiquidationFeaturesOutput, LongShortRatio, MaEnvelope, MaEnvelopeOutput,
|
||||||
Marubozu, MassIndex, MaxDrawdown, McGinleyDynamic, MedianAbsoluteDeviation, MedianPrice, Mfi,
|
MacdIndicator, MacdOutput, Mama, MamaOutput, MarketFacilitationIndex, Marubozu, MassIndex,
|
||||||
Microprice, Mom, MorningEveningStar, Natr, Nvi, Obv, OmegaRatio, OpenInterestDelta,
|
MaxDrawdown, McGinleyDynamic, MedianAbsoluteDeviation, MedianPrice, Mfi, Microprice, Mom,
|
||||||
OpeningRange, OpeningRangeOutput, OrderBookImbalanceFull, OrderBookImbalanceTop1,
|
MorningEveningStar, Natr, Nvi, OIPriceDivergence, OIWeighted, Obv, OmegaRatio,
|
||||||
OrderBookImbalanceTopN, PainIndex, PairSpreadZScore, PairwiseBeta, ParkinsonVolatility,
|
OpenInterestDelta, OpeningRange, OpeningRangeOutput, OrderBookImbalanceFull,
|
||||||
PearsonCorrelation, PercentB, PercentageTrailingStop, Pgo, PiercingDarkCloud, Pmo, Ppo,
|
OrderBookImbalanceTop1, OrderBookImbalanceTopN, PainIndex, PairSpreadZScore, PairwiseBeta,
|
||||||
ProfitFactor, Psar, Pvi, QuotedSpread, RSquared, RealizedSpread, RecoveryFactor,
|
ParkinsonVolatility, PearsonCorrelation, PercentB, PercentageTrailingStop, Pgo,
|
||||||
RelativeStrengthAB, RelativeStrengthOutput, RenkoTrailingStop, Roc, RogersSatchellVolatility,
|
PiercingDarkCloud, Pmo, Ppo, ProfitFactor, Psar, Pvi, QuotedSpread, RSquared, RealizedSpread,
|
||||||
RollingVwap, RoofingFilter, Rsi, Rvi, RviVolatility, Rwi, RwiOutput, SharpeRatio, ShootingStar,
|
RecoveryFactor, RelativeStrengthAB, RelativeStrengthOutput, RenkoTrailingStop, Roc,
|
||||||
SignedVolume, SineWave, Skewness, Sma, Smi, Smma, SortinoRatio, SpearmanCorrelation,
|
RogersSatchellVolatility, RollingVwap, RoofingFilter, Rsi, Rvi, RviVolatility, Rwi, RwiOutput,
|
||||||
SpinningTop, StandardError, StandardErrorBands, StandardErrorBandsOutput, StarcBands,
|
SharpeRatio, ShootingStar, SignedVolume, SineWave, Skewness, Sma, Smi, Smma, SortinoRatio,
|
||||||
StarcBandsOutput, Stc, StdDev, StepTrailingStop, StochRsi, Stochastic, StochasticOutput,
|
SpearmanCorrelation, SpinningTop, StandardError, StandardErrorBands, StandardErrorBandsOutput,
|
||||||
SuperSmoother, SuperTrend, SuperTrendOutput, TdCombo, TdCountdown, TdDeMarker, TdDifferential,
|
StarcBands, StarcBandsOutput, Stc, StdDev, StepTrailingStop, StochRsi, Stochastic,
|
||||||
TdLines, TdLinesOutput, TdOpen, TdPressure, TdRangeProjection, TdRangeProjectionOutput, TdRei,
|
StochasticOutput, SuperSmoother, SuperTrend, SuperTrendOutput, TakerBuySellRatio, TdCombo,
|
||||||
TdRiskLevel, TdRiskLevelOutput, TdSequential, TdSequentialOutput, TdSetup, Tema, ThreeInside,
|
TdCountdown, TdDeMarker, TdDifferential, TdLines, TdLinesOutput, TdOpen, TdPressure,
|
||||||
ThreeOutside, ThreeSoldiersOrCrows, Tii, TradeImbalance, TreynorRatio, Trima, Trix, TrueRange,
|
TdRangeProjection, TdRangeProjectionOutput, TdRei, TdRiskLevel, TdRiskLevelOutput,
|
||||||
Tsi, Tsv, TtmSqueeze, TtmSqueezeOutput, Tweezer, TypicalPrice, UlcerIndex, UltimateOscillator,
|
TdSequential, TdSequentialOutput, TdSetup, Tema, ThreeInside, ThreeOutside,
|
||||||
ValueArea, ValueAreaOutput, ValueAtRisk, Variance, VerticalHorizontalFilter, Vidya, VoltyStop,
|
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,
|
VolumeOscillator, VolumePriceTrend, Vortex, VortexOutput, Vwap, VwapStdDevBands,
|
||||||
VwapStdDevBandsOutput, Vwma, Vzo, WaveTrend, WaveTrendOutput, WeightedClose, WilliamsFractals,
|
VwapStdDevBandsOutput, Vwma, Vzo, WaveTrend, WaveTrendOutput, WeightedClose, WilliamsFractals,
|
||||||
WilliamsFractalsOutput, WilliamsR, Wma, WoodiePivots, WoodiePivotsOutput, YangZhangVolatility,
|
WilliamsFractalsOutput, WilliamsR, Wma, WoodiePivots, WoodiePivotsOutput, YangZhangVolatility,
|
||||||
|
|||||||
@@ -12,7 +12,8 @@
|
|||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
use wickra_core::{
|
use wickra_core::{
|
||||||
BatchExt, DerivativesTick, FundingBasis, FundingRate, FundingRateMean, FundingRateZScore,
|
BatchExt, DerivativesTick, FundingBasis, FundingRate, FundingRateMean, FundingRateZScore,
|
||||||
Indicator, OpenInterestDelta,
|
Indicator, LiquidationFeatures, LongShortRatio, OIPriceDivergence, OIWeighted,
|
||||||
|
OpenInterestDelta, TakerBuySellRatio,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
@@ -46,4 +47,15 @@ fuzz_target!(|data: &[u8]| {
|
|||||||
drive(|| FundingRateZScore::new(5).unwrap(), &ticks);
|
drive(|| FundingRateZScore::new(5).unwrap(), &ticks);
|
||||||
drive(FundingBasis::new, &ticks);
|
drive(FundingBasis::new, &ticks);
|
||||||
drive(OpenInterestDelta::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);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user