feat: derivatives funding & open-interest indicators (part 1 of 3) (#126)

* feat(derivatives): DerivativesTick input type + InvalidDerivatives error

* feat(derivatives): FundingRate indicator (core)

* feat(derivatives): FundingRateMean indicator (core)

* feat(derivatives): FundingRateZScore indicator (core)

* feat(derivatives): FundingBasis indicator (core)

* feat(derivatives): OpenInterestDelta indicator (core)

* feat(derivatives): Python, Node and WASM bindings for funding & OI-delta indicators

* test(derivatives): Python and Node tests for funding & OI-delta indicators

* bench(derivatives): synthetic-tick bench + derivatives fuzz target

* docs(derivatives): README family row + counter 232->237, CHANGELOG entry
This commit is contained in:
kingchenc
2026-06-01 21:26:37 +02:00
committed by GitHub
parent fae60e0d54
commit 5eb820a9c7
24 changed files with 2317 additions and 32 deletions
@@ -1094,3 +1094,45 @@ test('footprint streaming update matches batch and rejects bad tick', () => {
}
assert.throws(() => new wickra.Footprint(0));
});
test('derivatives indicators reference values', () => {
// Funding rate passes through (and may be negative).
assert.equal(new wickra.FundingRate().update(0.0001), 0.0001);
assert.equal(new wickra.FundingRate().update(-0.0003), -0.0003);
// Rolling mean: window [0.001, 0.003] -> 0.002.
const frm = new wickra.FundingRateMean(2);
assert.equal(frm.update(0.001), null); // warming up
assert.ok(Math.abs(frm.update(0.003) - 0.002) < 1e-12);
// Z-score: window [0.001, 0.003] -> +1.
const z = new wickra.FundingRateZScore(2);
assert.equal(z.update(0.001), null); // warming up
assert.ok(Math.abs(z.update(0.003) - 1.0) < 1e-9);
// Basis: mark 100.5 vs index 100.0 -> 0.005.
assert.ok(Math.abs(new wickra.FundingBasis().update(100.5, 100.0) - 0.005) < 1e-12);
// OI delta: seeds then emits the change.
const oid = new wickra.OpenInterestDelta();
assert.equal(oid.update(1000), null);
assert.equal(oid.update(1250), 250);
assert.equal(oid.update(1100), -150);
});
test('derivatives streaming update matches batch', () => {
const n = 30;
const rate = Array.from({ length: n }, (_, i) => 0.0001 * Math.sin(i * 0.3));
const batch = new wickra.FundingRateMean(5).batch(rate);
const streamer = new wickra.FundingRateMean(5);
assert.equal(batch.length, n);
for (let i = 0; i < n; i++) {
const s = streamer.update(rate[i]);
assert.ok(
(s === null && Number.isNaN(batch[i])) || Math.abs(s - batch[i]) < 1e-12,
`mismatch at ${i}: ${s} vs ${batch[i]}`,
);
}
});
test('derivatives reject bad input', () => {
assert.throws(() => new wickra.FundingRateMean(0));
assert.throws(() => new wickra.FundingRateZScore(0));
assert.throws(() => new wickra.FundingBasis().update(100, 0));
});
+45
View File
@@ -2319,6 +2319,51 @@ export declare class Footprint {
isReady(): boolean
warmupPeriod(): number
}
export type FundingRateNode = FundingRate
export declare class FundingRate {
constructor()
update(fundingRate: number): number | null
batch(fundingRate: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FundingRateMeanNode = FundingRateMean
export declare class FundingRateMean {
constructor(window: number)
update(fundingRate: number): number | null
batch(fundingRate: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FundingRateZScoreNode = FundingRateZScore
export declare class FundingRateZScore {
constructor(window: number)
update(fundingRate: number): number | null
batch(fundingRate: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FundingBasisNode = FundingBasis
export declare class FundingBasis {
constructor()
update(markPrice: number, indexPrice: number): number | null
batch(markPrice: Array<number>, indexPrice: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type OpenInterestDeltaNode = OpenInterestDelta
export declare class OpenInterestDelta {
constructor()
update(openInterest: number): number | null
batch(openInterest: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type SharpeRatioNode = SharpeRatio
export declare class SharpeRatio {
constructor(period: number, riskFree: number)
+6 -1
View File
@@ -310,7 +310,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, MOM, CMO, DPO, StdDev, UlcerIndex, VerticalHorizontalFilter, ZScore, McGinleyDynamic, FRAMA, SuperSmoother, FisherTransform, Decycler, CenterOfGravity, CyberneticCycle, InstantaneousTrendline, EhlersStochastic, RVIVolatility, Variance, CoefficientOfVariation, Skewness, Kurtosis, StandardError, DetrendedStdDev, RSquared, MedianAbsoluteDeviation, Autocorrelation, HurstExponent, PearsonCorrelation, Beta, PairwiseBeta, SpearmanCorrelation, PairSpreadZScore, LeadLagCrossCorrelation, Cointegration, RelativeStrengthAB, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, ADXR, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, RollingVWAP, AwesomeOscillator, Aroon, Inertia, ConnorsRSI, LaguerreRSI, SMI, KST, PGO, RVI, AwesomeOscillatorHistogram, STC, ElderImpulse, ZeroLagMACD, CFO, APO, KAMA, EVWMA, Alligator, JMA, VIDYA, ALMA, T3, TSI, PMO, TII, ADL, VolumePriceTrend, ChaikinMoneyFlow, ChaikinOscillator, ForceIndex, NVI, PVI, VolumeOscillator, KVO, WilliamsAD, AnchoredVWAP, DemandIndex, TSV, VZO, MarketFacilitationIndex, EaseOfMovement, SuperTrend, ChandelierExit, ChandeKrollStop, AtrTrailingStop, HiLoActivator, VoltyStop, YoyoExit, DonchianStop, PercentageTrailingStop, StepTrailingStop, RenkoTrailingStop, TypicalPrice, MedianPrice, WeightedClose, LinearRegression, LinRegSlope, AcceleratorOscillator, BalanceOfPower, ChoppinessIndex, TrueRange, ChaikinVolatility, YangZhangVolatility, RogersSatchellVolatility, GarmanKlassVolatility, ParkinsonVolatility, LinRegAngle, BollingerBandwidth, PercentB, NATR, HistoricalVolatility, AroonOscillator, WaveTrend, RWI, Vortex, MassIndex, StochRSI, UltimateOscillator, PPO, Coppock, VWMA, MaEnvelope, AccelerationBands, StarcBands, AtrBands, HurstChannel, LinRegChannel, StandardErrorBands, DoubleBollinger, TtmSqueeze, FractalChaosBands, VwapStdDevBands, ClassicPivots, FibonacciPivots, Camarilla, WoodiePivots, DemarkPivots, WilliamsFractals, ZigZag, TDSetup, TDSequential, TDDeMarker, TDREI, TDPressure, TDCombo, TDCountdown, TDLines, TDRangeProjection, TDDifferential, TDOpen, TDRiskLevel, InverseFisherTransform, DecyclerOscillator, RoofingFilter, EmpiricalModeDecomposition, HilbertDominantCycle, AdaptiveCycle, SineWave, MAMA, FAMA, Ichimoku, HeikinAshi, ValueArea, InitialBalance, OpeningRange, Doji, Hammer, InvertedHammer, HangingMan, ShootingStar, Engulfing, Harami, MorningEveningStar, ThreeSoldiersOrCrows, PiercingDarkCloud, Marubozu, Tweezer, SpinningTop, ThreeInside, ThreeOutside, OrderBookImbalanceTop1, OrderBookImbalanceFull, Microprice, QuotedSpread, DepthSlope, OrderBookImbalanceTopN, SignedVolume, CumulativeVolumeDelta, TradeImbalance, EffectiveSpread, RealizedSpread, KylesLambda, Footprint, 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, SharpeRatio, SortinoRatio, CalmarRatio, OmegaRatio, MaxDrawdown, AverageDrawdown, DrawdownDuration, PainIndex, ValueAtRisk, ConditionalValueAtRisk, ProfitFactor, GainLossRatio, RecoveryFactor, KellyCriterion, TreynorRatio, InformationRatio, Alpha } = nativeBinding
module.exports.version = version
module.exports.SMA = SMA
@@ -528,6 +528,11 @@ module.exports.EffectiveSpread = EffectiveSpread
module.exports.RealizedSpread = RealizedSpread
module.exports.KylesLambda = KylesLambda
module.exports.Footprint = Footprint
module.exports.FundingRate = FundingRate
module.exports.FundingRateMean = FundingRateMean
module.exports.FundingRateZScore = FundingRateZScore
module.exports.FundingBasis = FundingBasis
module.exports.OpenInterestDelta = OpenInterestDelta
module.exports.SharpeRatio = SharpeRatio
module.exports.SortinoRatio = SortinoRatio
module.exports.CalmarRatio = CalmarRatio
+283
View File
@@ -9352,6 +9352,289 @@ impl FootprintNode {
}
}
// ============================== Derivatives ==============================
//
// Derivatives indicators consume a perpetual / futures tick rather than OHLCV.
// Each wrapper exposes only the tick fields its indicator reads; the helpers
// below build a fully-valid `DerivativesTick`, filling the unused fields with
// neutral defaults (prices `1.0`, sizes / rates `0.0`).
fn deriv_funding(funding_rate: f64) -> napi::Result<wc::DerivativesTick> {
wc::DerivativesTick::new(
funding_rate,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_basis(mark_price: f64, index_price: f64) -> napi::Result<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
mark_price,
index_price,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_oi(open_interest: f64) -> napi::Result<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
1.0,
1.0,
1.0,
open_interest,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
#[napi(js_name = "FundingRate")]
pub struct FundingRateNode {
inner: wc::FundingRate,
}
impl Default for FundingRateNode {
fn default() -> Self {
Self::new()
}
}
#[napi]
impl FundingRateNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FundingRate::new(),
}
}
#[napi]
pub fn update(&mut self, funding_rate: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
#[napi]
pub fn batch(&mut self, funding_rate: Vec<f64>) -> napi::Result<Vec<f64>> {
let mut out = Vec::with_capacity(funding_rate.len());
for rate in funding_rate {
out.push(self.inner.update(deriv_funding(rate)?).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 = "FundingRateMean")]
pub struct FundingRateMeanNode {
inner: wc::FundingRateMean,
}
#[napi]
impl FundingRateMeanNode {
#[napi(constructor)]
pub fn new(window: u32) -> napi::Result<Self> {
Ok(Self {
inner: wc::FundingRateMean::new(window as usize).map_err(map_err)?,
})
}
#[napi]
pub fn update(&mut self, funding_rate: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
#[napi]
pub fn batch(&mut self, funding_rate: Vec<f64>) -> napi::Result<Vec<f64>> {
let mut out = Vec::with_capacity(funding_rate.len());
for rate in funding_rate {
out.push(self.inner.update(deriv_funding(rate)?).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 = "FundingRateZScore")]
pub struct FundingRateZScoreNode {
inner: wc::FundingRateZScore,
}
#[napi]
impl FundingRateZScoreNode {
#[napi(constructor)]
pub fn new(window: u32) -> napi::Result<Self> {
Ok(Self {
inner: wc::FundingRateZScore::new(window as usize).map_err(map_err)?,
})
}
#[napi]
pub fn update(&mut self, funding_rate: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
#[napi]
pub fn batch(&mut self, funding_rate: Vec<f64>) -> napi::Result<Vec<f64>> {
let mut out = Vec::with_capacity(funding_rate.len());
for rate in funding_rate {
out.push(self.inner.update(deriv_funding(rate)?).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 = "FundingBasis")]
pub struct FundingBasisNode {
inner: wc::FundingBasis,
}
impl Default for FundingBasisNode {
fn default() -> Self {
Self::new()
}
}
#[napi]
impl FundingBasisNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FundingBasis::new(),
}
}
#[napi]
pub fn update(&mut self, mark_price: f64, index_price: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(deriv_basis(mark_price, index_price)?))
}
#[napi]
pub fn batch(&mut self, mark_price: Vec<f64>, index_price: Vec<f64>) -> napi::Result<Vec<f64>> {
if mark_price.len() != index_price.len() {
return Err(NapiError::from_reason(
"mark_price and index_price 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_basis(mark_price[i], index_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 = "OpenInterestDelta")]
pub struct OpenInterestDeltaNode {
inner: wc::OpenInterestDelta,
}
impl Default for OpenInterestDeltaNode {
fn default() -> Self {
Self::new()
}
}
#[napi]
impl OpenInterestDeltaNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::OpenInterestDelta::new(),
}
}
#[napi]
pub fn update(&mut self, open_interest: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(deriv_oi(open_interest)?))
}
#[napi]
pub fn batch(&mut self, open_interest: Vec<f64>) -> napi::Result<Vec<f64>> {
let mut out = Vec::with_capacity(open_interest.len());
for oi in open_interest {
out.push(self.inner.update(deriv_oi(oi)?).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
}
}
// ============================== Family 15: Risk / Performance ==============================
// Risk metrics with fallible `new` (most need `period >= 2`), so each wrapper
+12
View File
@@ -257,6 +257,12 @@ from ._wickra import (
KylesLambda,
# Microstructure: footprint
Footprint,
# Derivatives
FundingRate,
FundingRateMean,
FundingRateZScore,
FundingBasis,
OpenInterestDelta,
# Risk / Performance
SharpeRatio,
SortinoRatio,
@@ -511,6 +517,12 @@ __all__ = [
"KylesLambda",
# Microstructure: footprint
"Footprint",
# Derivatives
"FundingRate",
"FundingRateMean",
"FundingRateZScore",
"FundingBasis",
"OpenInterestDelta",
# Risk / Performance
"SharpeRatio",
"SortinoRatio",
+307 -1
View File
@@ -28,7 +28,8 @@ fn map_err(e: wc::Error) -> PyErr {
| wc::Error::InvalidCandle { .. }
| wc::Error::InvalidTick { .. }
| wc::Error::InvalidOrderBook { .. }
| wc::Error::InvalidTrade { .. } => PyValueError::new_err(e.to_string()),
| wc::Error::InvalidTrade { .. }
| wc::Error::InvalidDerivatives { .. } => PyValueError::new_err(e.to_string()),
}
}
@@ -12182,6 +12183,305 @@ impl PyFootprint {
}
}
// ============================== Derivatives ==============================
//
// Derivatives indicators consume a perpetual / futures tick rather than OHLCV.
// Each wrapper exposes only the tick fields its indicator reads; the helpers
// below build a fully-valid `DerivativesTick`, filling the unused fields with
// neutral defaults (prices `1.0`, sizes / rates `0.0`).
fn deriv_funding(funding_rate: f64) -> PyResult<wc::DerivativesTick> {
wc::DerivativesTick::new(
funding_rate,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_basis(mark_price: f64, index_price: f64) -> PyResult<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
mark_price,
index_price,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_oi(open_interest: f64) -> PyResult<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
1.0,
1.0,
1.0,
open_interest,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
// FundingRate takes no parameters; streaming `update(funding_rate)`, `batch`
// over one funding-rate array.
#[pyclass(name = "FundingRate", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFundingRate {
inner: wc::FundingRate,
}
#[pymethods]
impl PyFundingRate {
#[new]
fn new() -> Self {
Self {
inner: wc::FundingRate::new(),
}
}
fn update(&mut self, funding_rate: f64) -> PyResult<Option<f64>> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
funding_rate: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let mut out = Vec::with_capacity(funding_rate.len());
for rate in funding_rate {
out.push(self.inner.update(deriv_funding(rate)?).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 {
"FundingRate()".to_string()
}
}
// FundingRateMean carries a `window` parameter.
#[pyclass(
name = "FundingRateMean",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyFundingRateMean {
inner: wc::FundingRateMean,
}
#[pymethods]
impl PyFundingRateMean {
#[new]
fn new(window: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::FundingRateMean::new(window).map_err(map_err)?,
})
}
fn update(&mut self, funding_rate: f64) -> PyResult<Option<f64>> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
funding_rate: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let mut out = Vec::with_capacity(funding_rate.len());
for rate in funding_rate {
out.push(self.inner.update(deriv_funding(rate)?).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!("FundingRateMean(window={})", self.inner.window())
}
}
// FundingRateZScore carries a `window` parameter.
#[pyclass(
name = "FundingRateZScore",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyFundingRateZScore {
inner: wc::FundingRateZScore,
}
#[pymethods]
impl PyFundingRateZScore {
#[new]
fn new(window: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::FundingRateZScore::new(window).map_err(map_err)?,
})
}
fn update(&mut self, funding_rate: f64) -> PyResult<Option<f64>> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
funding_rate: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let mut out = Vec::with_capacity(funding_rate.len());
for rate in funding_rate {
out.push(self.inner.update(deriv_funding(rate)?).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!("FundingRateZScore(window={})", self.inner.window())
}
}
// FundingBasis takes no parameters; streaming `update(mark_price, index_price)`.
#[pyclass(name = "FundingBasis", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFundingBasis {
inner: wc::FundingBasis,
}
#[pymethods]
impl PyFundingBasis {
#[new]
fn new() -> Self {
Self {
inner: wc::FundingBasis::new(),
}
}
fn update(&mut self, mark_price: f64, index_price: f64) -> PyResult<Option<f64>> {
Ok(self.inner.update(deriv_basis(mark_price, index_price)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
mark_price: Vec<f64>,
index_price: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if mark_price.len() != index_price.len() {
return Err(PyValueError::new_err(
"mark_price and index_price 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_basis(mark_price[i], index_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 {
"FundingBasis()".to_string()
}
}
// OpenInterestDelta takes no parameters; streaming `update(open_interest)`.
#[pyclass(
name = "OpenInterestDelta",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyOpenInterestDelta {
inner: wc::OpenInterestDelta,
}
#[pymethods]
impl PyOpenInterestDelta {
#[new]
fn new() -> Self {
Self {
inner: wc::OpenInterestDelta::new(),
}
}
fn update(&mut self, open_interest: f64) -> PyResult<Option<f64>> {
Ok(self.inner.update(deriv_oi(open_interest)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
open_interest: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let mut out = Vec::with_capacity(open_interest.len());
for oi in open_interest {
out.push(self.inner.update(deriv_oi(oi)?).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 {
"OpenInterestDelta()".to_string()
}
}
// ============================== Family 15: Risk / Performance ==============================
#[pyclass(name = "SharpeRatio", module = "wickra._wickra", skip_from_py_object)]
@@ -13304,6 +13604,12 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyKylesLambda>()?;
// Microstructure: footprint.
m.add_class::<PyFootprint>()?;
// Derivatives.
m.add_class::<PyFundingRate>()?;
m.add_class::<PyFundingRateMean>()?;
m.add_class::<PyFundingRateZScore>()?;
m.add_class::<PyFundingBasis>()?;
m.add_class::<PyOpenInterestDelta>()?;
// Family 15: Risk / Performance metrics.
m.add_class::<PySharpeRatio>()?;
m.add_class::<PySortinoRatio>()?;
@@ -238,3 +238,23 @@ def test_footprint_non_positive_tick_raises():
ta.Footprint(0.0)
with pytest.raises(ValueError):
ta.Footprint(-1.0)
def test_funding_rate_mean_zero_window_raises():
with pytest.raises(ValueError):
ta.FundingRateMean(0)
def test_funding_rate_zscore_zero_window_raises():
with pytest.raises(ValueError):
ta.FundingRateZScore(0)
def test_funding_basis_non_positive_index_raises():
with pytest.raises(ValueError):
ta.FundingBasis().update(100.0, 0.0)
def test_funding_rate_non_finite_raises():
with pytest.raises(ValueError):
ta.FundingRate().update(float("nan"))
@@ -946,3 +946,36 @@ def test_kyles_lambda_recovers_constant_impact():
mids.append(mid)
out = ta.KylesLambda(6).batch(price, size, is_buy, mids)
assert out[-1] == pytest.approx(0.5, abs=1e-9)
def test_funding_rate_reference_values():
assert ta.FundingRate().update(0.0001) == pytest.approx(0.0001)
assert ta.FundingRate().update(-0.0003) == pytest.approx(-0.0003)
def test_funding_rate_mean_reference_value():
frm = ta.FundingRateMean(2)
assert frm.update(0.001) is None # warming up
# Window [0.001, 0.003] -> mean 0.002.
assert frm.update(0.003) == pytest.approx(0.002)
def test_funding_rate_zscore_reference_value():
z = ta.FundingRateZScore(2)
assert z.update(0.001) is None # warming up
# Window [0.001, 0.003]: mean 0.002, population stddev 0.001 -> +1.
assert z.update(0.003) == pytest.approx(1.0, abs=1e-9)
def test_funding_basis_reference_value():
# mark 100.5 vs index 100.0 -> (100.5 - 100.0) / 100.0 = 0.005.
assert ta.FundingBasis().update(100.5, 100.0) == pytest.approx(0.005)
# A discount reads negative.
assert ta.FundingBasis().update(99.5, 100.0) == pytest.approx(-0.005)
def test_open_interest_delta_reference_value():
oid = ta.OpenInterestDelta()
assert oid.update(1000.0) is None # seeds the previous OI
assert oid.update(1250.0) == pytest.approx(250.0)
assert oid.update(1100.0) == pytest.approx(-150.0)
@@ -1952,3 +1952,45 @@ def test_footprint_streaming_equals_batch():
for i in range(n):
streamed = streamer.update(price[i], size[i], is_buy[i])
assert np.array_equal(streamed, batch[i])
def test_funding_indicators_streaming_equals_batch():
n = 40
rate = np.array([0.0001 * math.sin(i * 0.3) for i in range(n)], dtype=np.float64)
for make in (
ta.FundingRate,
lambda: ta.FundingRateMean(5),
lambda: ta.FundingRateZScore(5),
):
batch = make().batch(rate)
streamer = make()
streamed = np.array(
[streamer.update(rate[i]) for i in range(n)], dtype=np.float64
)
assert batch.shape == (n,)
assert _eq_nan(batch, streamed)
def test_funding_basis_streaming_equals_batch():
n = 40
index = np.array([100.0 + 0.5 * math.sin(i * 0.2) for i in range(n)], dtype=np.float64)
mark = np.array(
[index[i] + 0.1 * math.cos(i * 0.3) for i in range(n)], dtype=np.float64
)
batch = ta.FundingBasis().batch(mark, index)
streamer = ta.FundingBasis()
streamed = np.array(
[streamer.update(mark[i], index[i]) for i in range(n)], dtype=np.float64
)
assert batch.shape == (n,)
assert _eq_nan(batch, streamed)
def test_open_interest_delta_streaming_equals_batch():
n = 40
oi = np.array([1000.0 + 50.0 * math.sin(i * 0.25) for i in range(n)], dtype=np.float64)
batch = ta.OpenInterestDelta().batch(oi)
streamer = ta.OpenInterestDelta()
streamed = np.array([streamer.update(oi[i]) for i in range(n)], dtype=np.float64)
assert batch.shape == (n,)
assert _eq_nan(batch, streamed)
+225
View File
@@ -6747,6 +6747,231 @@ impl WasmFootprint {
}
}
// ============================== Derivatives ==============================
//
// Derivatives indicators consume a perpetual / futures tick rather than OHLCV.
// Each `update(...)` takes only the tick fields its indicator reads — the
// streaming model for a live browser derivatives feed. Batch over a tape is
// provided by the Python and Node bindings. The helpers build a fully-valid
// `DerivativesTick`, filling unused fields with neutral defaults.
fn deriv_funding(funding_rate: f64) -> Result<wc::DerivativesTick, JsError> {
wc::DerivativesTick::new(
funding_rate,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_basis(mark_price: f64, index_price: f64) -> Result<wc::DerivativesTick, JsError> {
wc::DerivativesTick::new(
0.0,
mark_price,
index_price,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_oi(open_interest: f64) -> Result<wc::DerivativesTick, JsError> {
wc::DerivativesTick::new(
0.0,
1.0,
1.0,
1.0,
open_interest,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
#[wasm_bindgen(js_name = FundingRate)]
pub struct WasmFundingRate {
inner: wc::FundingRate,
}
impl Default for WasmFundingRate {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FundingRate)]
impl WasmFundingRate {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFundingRate {
Self {
inner: wc::FundingRate::new(),
}
}
pub fn update(&mut self, funding_rate: f64) -> Result<Option<f64>, JsError> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
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 = FundingRateMean)]
pub struct WasmFundingRateMean {
inner: wc::FundingRateMean,
}
#[wasm_bindgen(js_class = FundingRateMean)]
impl WasmFundingRateMean {
#[wasm_bindgen(constructor)]
pub fn new(window: usize) -> Result<WasmFundingRateMean, JsError> {
Ok(Self {
inner: wc::FundingRateMean::new(window).map_err(map_err)?,
})
}
pub fn update(&mut self, funding_rate: f64) -> Result<Option<f64>, JsError> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
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 = FundingRateZScore)]
pub struct WasmFundingRateZScore {
inner: wc::FundingRateZScore,
}
#[wasm_bindgen(js_class = FundingRateZScore)]
impl WasmFundingRateZScore {
#[wasm_bindgen(constructor)]
pub fn new(window: usize) -> Result<WasmFundingRateZScore, JsError> {
Ok(Self {
inner: wc::FundingRateZScore::new(window).map_err(map_err)?,
})
}
pub fn update(&mut self, funding_rate: f64) -> Result<Option<f64>, JsError> {
Ok(self.inner.update(deriv_funding(funding_rate)?))
}
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 = FundingBasis)]
pub struct WasmFundingBasis {
inner: wc::FundingBasis,
}
impl Default for WasmFundingBasis {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FundingBasis)]
impl WasmFundingBasis {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFundingBasis {
Self {
inner: wc::FundingBasis::new(),
}
}
pub fn update(&mut self, mark_price: f64, index_price: f64) -> Result<Option<f64>, JsError> {
Ok(self.inner.update(deriv_basis(mark_price, index_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 = OpenInterestDelta)]
pub struct WasmOpenInterestDelta {
inner: wc::OpenInterestDelta,
}
impl Default for WasmOpenInterestDelta {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = OpenInterestDelta)]
impl WasmOpenInterestDelta {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmOpenInterestDelta {
Self {
inner: wc::OpenInterestDelta::new(),
}
}
pub fn update(&mut self, open_interest: f64) -> Result<Option<f64>, JsError> {
Ok(self.inner.update(deriv_oi(open_interest)?))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[cfg(test)]
mod tests {
use super::*;