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
@@ -0,0 +1,137 @@
//! Funding Basis — the perpetual mark's relative premium to the spot index.
use crate::derivatives::DerivativesTick;
use crate::traits::Indicator;
/// Funding Basis — the relative basis between the perpetual mark price and the
/// spot index it tracks.
///
/// ```text
/// basis = (markPrice indexPrice) / indexPrice
/// ```
///
/// The basis is the spread that the funding mechanism continuously pulls toward
/// zero: a positive basis (perpetual above spot) goes hand in hand with positive
/// funding (longs pay), a negative basis with negative funding. Reading the
/// instantaneous basis alongside the [funding rate] separates a genuine premium
/// from a stale-funding artefact and sizes the carry available to a cash-and-carry
/// or basis-arbitrage trade. The output is a fraction (e.g. `0.001` = 10 bps);
/// multiply by `10_000` for basis points.
///
/// `Input = DerivativesTick`, `Output = f64`. Stateless; ready after the first
/// tick.
///
/// [funding rate]: crate::FundingRate
///
/// # Example
///
/// ```
/// use wickra_core::{DerivativesTick, FundingBasis, Indicator};
///
/// let mut fb = FundingBasis::new();
/// // mark 100.5 vs index 100.0 -> (100.5 - 100.0) / 100.0 = 0.005.
/// let tick = DerivativesTick::new(
/// 0.0, 100.5, 100.0, 100.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0,
/// )
/// .unwrap();
/// assert!((fb.update(tick).unwrap() - 0.005).abs() < 1e-12);
/// ```
#[derive(Debug, Clone, Default)]
pub struct FundingBasis {
has_emitted: bool,
}
impl FundingBasis {
/// Construct a new funding-basis indicator.
#[must_use]
pub const fn new() -> Self {
Self { has_emitted: false }
}
}
impl Indicator for FundingBasis {
type Input = DerivativesTick;
type Output = f64;
fn update(&mut self, tick: DerivativesTick) -> Option<f64> {
self.has_emitted = true;
Some((tick.mark_price - tick.index_price) / tick.index_price)
}
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 {
"FundingBasis"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
fn tick(mark: f64, index: f64) -> DerivativesTick {
DerivativesTick::new_unchecked(0.0, mark, index, mark, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0)
}
#[test]
fn accessors_and_metadata() {
let fb = FundingBasis::new();
assert_eq!(fb.name(), "FundingBasis");
assert_eq!(fb.warmup_period(), 1);
assert!(!fb.is_ready());
}
#[test]
fn premium_is_positive() {
let mut fb = FundingBasis::new();
let out = fb.update(tick(100.5, 100.0)).unwrap();
assert!((out - 0.005).abs() < 1e-12);
assert!(fb.is_ready());
}
#[test]
fn discount_is_negative() {
let mut fb = FundingBasis::new();
let out = fb.update(tick(99.5, 100.0)).unwrap();
assert!((out + 0.005).abs() < 1e-12);
}
#[test]
fn at_par_is_zero() {
let mut fb = FundingBasis::new();
assert_eq!(fb.update(tick(100.0, 100.0)), Some(0.0));
}
#[test]
fn batch_equals_streaming() {
let ticks: Vec<DerivativesTick> = (0..20)
.map(|i| tick(100.0 + f64::from(i % 5) * 0.1, 100.0))
.collect();
let mut a = FundingBasis::new();
let mut b = FundingBasis::new();
assert_eq!(
a.batch(&ticks),
ticks.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut fb = FundingBasis::new();
fb.update(tick(100.5, 100.0));
assert!(fb.is_ready());
fb.reset();
assert!(!fb.is_ready());
}
}
@@ -0,0 +1,131 @@
//! Funding Rate — the current perpetual funding rate.
use crate::derivatives::DerivativesTick;
use crate::traits::Indicator;
/// Funding Rate — the funding rate carried by each derivatives tick.
///
/// The funding rate is the periodic payment exchanged between long and short
/// perpetual-swap holders that tethers the perpetual mark to the spot index. A
/// positive rate means longs pay shorts (the perpetual trades at a premium); a
/// negative rate means shorts pay longs (a discount). This indicator simply
/// surfaces the rate from the [`DerivativesTick`] feed so it can be charted,
/// chained or fed to the rolling funding statistics ([`FundingRateMean`],
/// [`FundingRateZScore`]).
///
/// `Input = DerivativesTick`, `Output = f64`. Stateless; ready after the first
/// tick.
///
/// [`FundingRateMean`]: crate::FundingRateMean
/// [`FundingRateZScore`]: crate::FundingRateZScore
///
/// # Example
///
/// ```
/// use wickra_core::{DerivativesTick, FundingRate, Indicator};
///
/// let mut fr = FundingRate::new();
/// let tick = DerivativesTick::new(
/// 0.0001, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0,
/// )
/// .unwrap();
/// assert_eq!(fr.update(tick), Some(0.0001));
/// ```
#[derive(Debug, Clone, Default)]
pub struct FundingRate {
has_emitted: bool,
}
impl FundingRate {
/// Construct a new funding-rate indicator.
#[must_use]
pub const fn new() -> Self {
Self { has_emitted: false }
}
}
impl Indicator for FundingRate {
type Input = DerivativesTick;
type Output = f64;
fn update(&mut self, tick: DerivativesTick) -> Option<f64> {
self.has_emitted = true;
Some(tick.funding_rate)
}
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 {
"FundingRate"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
fn tick(funding_rate: f64) -> DerivativesTick {
DerivativesTick::new_unchecked(
funding_rate,
100.0,
100.0,
100.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
}
#[test]
fn accessors_and_metadata() {
let fr = FundingRate::new();
assert_eq!(fr.name(), "FundingRate");
assert_eq!(fr.warmup_period(), 1);
assert!(!fr.is_ready());
}
#[test]
fn passes_through_funding_rate() {
let mut fr = FundingRate::new();
assert_eq!(fr.update(tick(0.0001)), Some(0.0001));
assert_eq!(fr.update(tick(-0.0003)), Some(-0.0003));
assert!(fr.is_ready());
}
#[test]
fn batch_equals_streaming() {
let ticks: Vec<DerivativesTick> =
(0..20).map(|i| tick(0.0001 * f64::from(i - 10))).collect();
let mut a = FundingRate::new();
let mut b = FundingRate::new();
assert_eq!(
a.batch(&ticks),
ticks.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut fr = FundingRate::new();
fr.update(tick(0.0001));
assert!(fr.is_ready());
fr.reset();
assert!(!fr.is_ready());
}
}
@@ -0,0 +1,181 @@
//! Funding Rate Rolling Mean — average funding rate over a trailing window.
use std::collections::VecDeque;
use crate::derivatives::DerivativesTick;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Funding Rate Rolling Mean — the arithmetic mean of the funding rate over the
/// trailing window of `window` ticks.
///
/// ```text
/// mean = (1 / window) · Σ fundingRate over the last `window` ticks
/// ```
///
/// Smoothing the raw [funding rate] reveals the persistent carry regime — a
/// sustained positive mean marks a crowded-long market paying to hold the
/// perpetual, a sustained negative mean a crowded-short one. The indicator warms
/// up for `window` ticks — `update` returns `None` until the window is full —
/// then emits the rolling mean, maintained in O(1) per tick via a running sum.
///
/// `Input = DerivativesTick`, `Output = f64`.
///
/// [funding rate]: crate::FundingRate
///
/// # Example
///
/// ```
/// use wickra_core::{DerivativesTick, FundingRateMean, Indicator};
///
/// fn tick(rate: f64) -> DerivativesTick {
/// DerivativesTick::new(rate, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0)
/// .unwrap()
/// }
///
/// let mut frm = FundingRateMean::new(2).unwrap();
/// assert_eq!(frm.update(tick(0.001)), None);
/// // Window full: (0.001 + 0.003) / 2 = 0.002.
/// assert_eq!(frm.update(tick(0.003)), Some(0.002));
/// ```
#[derive(Debug, Clone)]
pub struct FundingRateMean {
window: usize,
history: VecDeque<f64>,
sum: f64,
}
impl FundingRateMean {
/// Construct a funding-rate rolling mean 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),
sum: 0.0,
})
}
/// The configured window length, in ticks.
#[must_use]
pub fn window(&self) -> usize {
self.window
}
}
impl Indicator for FundingRateMean {
type Input = DerivativesTick;
type Output = f64;
fn update(&mut self, tick: DerivativesTick) -> Option<f64> {
self.history.push_back(tick.funding_rate);
self.sum += tick.funding_rate;
if self.history.len() > self.window {
let old = self.history.pop_front().expect("window >= 1, len > window");
self.sum -= old;
}
if self.history.len() < self.window {
return None;
}
Some(self.sum / self.window as f64)
}
fn reset(&mut self) {
self.history.clear();
self.sum = 0.0;
}
fn warmup_period(&self) -> usize {
self.window
}
fn is_ready(&self) -> bool {
self.history.len() >= self.window
}
fn name(&self) -> &'static str {
"FundingRateMean"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
fn tick(rate: f64) -> DerivativesTick {
DerivativesTick::new_unchecked(
rate, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0,
)
}
#[test]
fn rejects_zero_window() {
assert!(matches!(FundingRateMean::new(0), Err(Error::PeriodZero)));
}
#[test]
fn accessors_and_metadata() {
let frm = FundingRateMean::new(5).unwrap();
assert_eq!(frm.name(), "FundingRateMean");
assert_eq!(frm.warmup_period(), 5);
assert_eq!(frm.window(), 5);
assert!(!frm.is_ready());
}
#[test]
fn warms_up_then_emits_mean() {
let mut frm = FundingRateMean::new(2).unwrap();
assert_eq!(frm.update(tick(0.001)), None);
assert!(!frm.is_ready());
assert_eq!(frm.update(tick(0.003)), Some(0.002));
assert!(frm.is_ready());
}
#[test]
fn rolls_off_old_values() {
let mut frm = FundingRateMean::new(2).unwrap();
frm.update(tick(0.001));
frm.update(tick(0.003)); // mean 0.002
let out = frm.update(tick(0.005)).unwrap(); // window [0.003, 0.005] -> 0.004
assert!((out - 0.004).abs() < 1e-12);
}
#[test]
fn handles_negative_rates() {
let mut frm = FundingRateMean::new(2).unwrap();
frm.update(tick(-0.002));
let out = frm.update(tick(0.004)).unwrap();
assert!((out - 0.001).abs() < 1e-12);
}
#[test]
fn batch_equals_streaming() {
let ticks: Vec<DerivativesTick> = (0..30)
.map(|i| tick(0.0001 * f64::from(i % 7) - 0.0003))
.collect();
let mut a = FundingRateMean::new(5).unwrap();
let mut b = FundingRateMean::new(5).unwrap();
assert_eq!(
a.batch(&ticks),
ticks.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut frm = FundingRateMean::new(2).unwrap();
frm.update(tick(0.001));
frm.update(tick(0.003));
assert!(frm.is_ready());
frm.reset();
assert!(!frm.is_ready());
assert_eq!(frm.update(tick(0.002)), None);
}
}
@@ -0,0 +1,201 @@
//! Funding Rate Z-Score — how extreme the latest funding rate is versus its
//! recent history.
use std::collections::VecDeque;
use crate::derivatives::DerivativesTick;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Funding Rate Z-Score — the latest funding rate expressed in standard
/// deviations from its rolling mean over the trailing window of `window` ticks.
///
/// ```text
/// zScore = (fundingRate mean) / population_stddev over the last `window` ticks
/// ```
///
/// A reading of `+2` means funding is two standard deviations richer than its
/// recent norm — an unusually crowded long, a contrarian fade signal; `2` is
/// the mirror. Normalising the [funding rate] this way makes funding extremes
/// comparable across regimes and assets. A window with zero dispersion (a flat
/// funding series) yields `0`. The indicator warms up for `window` ticks, then
/// emits the rolling z-score, maintained in O(1) per tick.
///
/// `Input = DerivativesTick`, `Output = f64`.
///
/// [funding rate]: crate::FundingRate
///
/// # Example
///
/// ```
/// use wickra_core::{DerivativesTick, FundingRateZScore, Indicator};
///
/// fn tick(rate: f64) -> DerivativesTick {
/// DerivativesTick::new(rate, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0)
/// .unwrap()
/// }
///
/// let mut z = FundingRateZScore::new(2).unwrap();
/// assert_eq!(z.update(tick(0.001)), None);
/// // Window [0.001, 0.003]: mean 0.002, population stddev 0.001 -> (0.003 - 0.002) / 0.001 = 1.
/// assert!((z.update(tick(0.003)).unwrap() - 1.0).abs() < 1e-9);
/// ```
#[derive(Debug, Clone)]
pub struct FundingRateZScore {
window: usize,
history: VecDeque<f64>,
sum: f64,
sum_sq: f64,
}
impl FundingRateZScore {
/// Construct a funding-rate z-score 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),
sum: 0.0,
sum_sq: 0.0,
})
}
/// The configured window length, in ticks.
#[must_use]
pub fn window(&self) -> usize {
self.window
}
}
impl Indicator for FundingRateZScore {
type Input = DerivativesTick;
type Output = f64;
fn update(&mut self, tick: DerivativesTick) -> Option<f64> {
let value = tick.funding_rate;
if self.history.len() == self.window {
let old = self.history.pop_front().expect("non-empty");
self.sum -= old;
self.sum_sq -= old * old;
}
self.history.push_back(value);
self.sum += value;
self.sum_sq += value * value;
if self.history.len() < self.window {
return None;
}
let n = self.window as f64;
let mean = self.sum / n;
// Population variance E[x²] E[x]²; clamp away tiny negative drift.
let variance = (self.sum_sq / n - mean * mean).max(0.0);
let std = variance.sqrt();
if std == 0.0 {
// A window with no dispersion: funding is exactly its own mean.
return Some(0.0);
}
Some((value - mean) / std)
}
fn reset(&mut self) {
self.history.clear();
self.sum = 0.0;
self.sum_sq = 0.0;
}
fn warmup_period(&self) -> usize {
self.window
}
fn is_ready(&self) -> bool {
self.history.len() == self.window
}
fn name(&self) -> &'static str {
"FundingRateZScore"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
fn tick(rate: f64) -> DerivativesTick {
DerivativesTick::new_unchecked(
rate, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0,
)
}
#[test]
fn rejects_zero_window() {
assert!(matches!(FundingRateZScore::new(0), Err(Error::PeriodZero)));
}
#[test]
fn accessors_and_metadata() {
let z = FundingRateZScore::new(5).unwrap();
assert_eq!(z.name(), "FundingRateZScore");
assert_eq!(z.warmup_period(), 5);
assert_eq!(z.window(), 5);
assert!(!z.is_ready());
}
#[test]
fn reference_value() {
let mut z = FundingRateZScore::new(2).unwrap();
assert_eq!(z.update(tick(0.001)), None);
// Window [0.001, 0.003]: mean 0.002, var (1e-6 + 9e-6)/2 - 4e-6 = 1e-6,
// stddev 0.001; latest 0.003 is (0.003 - 0.002) / 0.001 = 1.
let out = z.update(tick(0.003)).unwrap();
assert!((out - 1.0).abs() < 1e-9);
assert!(z.is_ready());
}
#[test]
fn flat_window_is_zero() {
let mut z = FundingRateZScore::new(3).unwrap();
z.update(tick(0.002));
z.update(tick(0.002));
assert_eq!(z.update(tick(0.002)), Some(0.0));
}
#[test]
fn rolls_off_old_values() {
let mut z = FundingRateZScore::new(2).unwrap();
z.update(tick(0.001));
z.update(tick(0.003));
// Window now [0.003, 0.005]: mean 0.004, stddev 0.001 -> +1.
let out = z.update(tick(0.005)).unwrap();
assert!((out - 1.0).abs() < 1e-9);
}
#[test]
fn batch_equals_streaming() {
let ticks: Vec<DerivativesTick> = (0..30)
.map(|i| tick(0.0001 * f64::from(i % 5) - 0.0002))
.collect();
let mut a = FundingRateZScore::new(6).unwrap();
let mut b = FundingRateZScore::new(6).unwrap();
assert_eq!(
a.batch(&ticks),
ticks.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut z = FundingRateZScore::new(2).unwrap();
z.update(tick(0.001));
z.update(tick(0.003));
assert!(z.is_ready());
z.reset();
assert!(!z.is_ready());
assert_eq!(z.update(tick(0.002)), None);
}
}
+21 -1
View File
@@ -77,6 +77,10 @@ mod footprint;
mod force_index;
mod fractal_chaos_bands;
mod frama;
mod funding_basis;
mod funding_rate;
mod funding_rate_mean;
mod funding_rate_zscore;
mod gain_loss_ratio;
mod garman_klass;
mod hammer;
@@ -130,6 +134,7 @@ mod ob_imbalance_full;
mod ob_imbalance_top1;
mod ob_imbalance_topn;
mod obv;
mod oi_delta;
mod omega_ratio;
mod opening_range;
mod pain_index;
@@ -309,6 +314,10 @@ pub use footprint::{Footprint, FootprintLevel, FootprintOutput};
pub use force_index::ForceIndex;
pub use fractal_chaos_bands::{FractalChaosBands, FractalChaosBandsOutput};
pub use frama::Frama;
pub use funding_basis::FundingBasis;
pub use funding_rate::FundingRate;
pub use funding_rate_mean::FundingRateMean;
pub use funding_rate_zscore::FundingRateZScore;
pub use gain_loss_ratio::GainLossRatio;
pub use garman_klass::GarmanKlassVolatility;
pub use hammer::Hammer;
@@ -362,6 +371,7 @@ pub use ob_imbalance_full::OrderBookImbalanceFull;
pub use ob_imbalance_top1::OrderBookImbalanceTop1;
pub use ob_imbalance_topn::OrderBookImbalanceTopN;
pub use obv::Obv;
pub use oi_delta::OpenInterestDelta;
pub use omega_ratio::OmegaRatio;
pub use opening_range::{OpeningRange, OpeningRangeOutput};
pub use pain_index::PainIndex;
@@ -751,6 +761,16 @@ pub const FAMILIES: &[(&str, &[&str])] = &[
"Footprint",
],
),
(
"Derivatives",
&[
"FundingRate",
"FundingRateMean",
"FundingRateZScore",
"FundingBasis",
"OpenInterestDelta",
],
),
(
"Market Profile",
&["ValueArea", "InitialBalance", "OpeningRange"],
@@ -805,6 +825,6 @@ mod family_tests {
// the actual indicator count is the early-warning signal that an
// indicator was added without being assigned a family.
let total: usize = FAMILIES.iter().map(|(_, ns)| ns.len()).sum();
assert_eq!(total, 227, "FAMILIES total drifted from indicator count");
assert_eq!(total, 232, "FAMILIES total drifted from indicator count");
}
}
@@ -0,0 +1,142 @@
//! Open-Interest Delta — the tick-over-tick change in open interest.
use crate::derivatives::DerivativesTick;
use crate::traits::Indicator;
/// Open-Interest Delta — the change in open interest from the previous tick.
///
/// ```text
/// delta = openInterestₜ openInterestₜ₋₁
/// ```
///
/// Open interest is the count of outstanding contracts; its change separates new
/// positioning from mere turnover. Read together with price, rising OI confirms
/// a trend (fresh money entering) while falling OI flags an unwind (positions
/// closing) — the raw input to the [OI / price divergence] signal. A positive
/// delta is net position-building, a negative delta net liquidation/closing.
///
/// The first tick only seeds the previous value and returns `None`; from the
/// second tick on the indicator emits the delta.
///
/// `Input = DerivativesTick`, `Output = f64`.
///
/// [OI / price divergence]: crate::OIPriceDivergence
///
/// # Example
///
/// ```
/// use wickra_core::{DerivativesTick, Indicator, OpenInterestDelta};
///
/// fn tick(oi: f64) -> DerivativesTick {
/// DerivativesTick::new(0.0, 100.0, 100.0, 100.0, oi, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0)
/// .unwrap()
/// }
///
/// let mut oid = OpenInterestDelta::new();
/// assert_eq!(oid.update(tick(1_000.0)), None); // seeds the previous OI
/// assert_eq!(oid.update(tick(1_250.0)), Some(250.0));
/// assert_eq!(oid.update(tick(1_100.0)), Some(-150.0));
/// ```
#[derive(Debug, Clone, Default)]
pub struct OpenInterestDelta {
prev: Option<f64>,
has_emitted: bool,
}
impl OpenInterestDelta {
/// Construct a new open-interest delta indicator.
#[must_use]
pub const fn new() -> Self {
Self {
prev: None,
has_emitted: false,
}
}
}
impl Indicator for OpenInterestDelta {
type Input = DerivativesTick;
type Output = f64;
fn update(&mut self, tick: DerivativesTick) -> Option<f64> {
let oi = tick.open_interest;
let delta = self.prev.map(|prev| oi - prev);
self.prev = Some(oi);
if delta.is_some() {
self.has_emitted = true;
}
delta
}
fn reset(&mut self) {
self.prev = None;
self.has_emitted = false;
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
self.has_emitted
}
fn name(&self) -> &'static str {
"OpenInterestDelta"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
fn tick(oi: f64) -> DerivativesTick {
DerivativesTick::new_unchecked(
0.0, 100.0, 100.0, 100.0, oi, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0,
)
}
#[test]
fn accessors_and_metadata() {
let oid = OpenInterestDelta::new();
assert_eq!(oid.name(), "OpenInterestDelta");
assert_eq!(oid.warmup_period(), 2);
assert!(!oid.is_ready());
}
#[test]
fn seeds_then_emits_delta() {
let mut oid = OpenInterestDelta::new();
assert_eq!(oid.update(tick(1_000.0)), None);
assert!(!oid.is_ready());
assert_eq!(oid.update(tick(1_250.0)), Some(250.0));
assert!(oid.is_ready());
assert_eq!(oid.update(tick(1_100.0)), Some(-150.0));
}
#[test]
fn batch_equals_streaming() {
let ticks: Vec<DerivativesTick> = (0..20)
.map(|i| tick(1_000.0 + f64::from(i * i % 13) * 10.0))
.collect();
let mut a = OpenInterestDelta::new();
let mut b = OpenInterestDelta::new();
assert_eq!(
a.batch(&ticks),
ticks.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut oid = OpenInterestDelta::new();
oid.update(tick(1_000.0));
oid.update(tick(1_250.0));
assert!(oid.is_ready());
oid.reset();
assert!(!oid.is_ready());
// After reset the next tick only re-seeds, returning None.
assert_eq!(oid.update(tick(2_000.0)), None);
}
}