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:
@@ -0,0 +1,321 @@
|
||||
//! Derivatives value type: the perpetual / futures tick.
|
||||
//!
|
||||
//! [`DerivativesTick`] is the non-OHLCV input consumed by the derivatives /
|
||||
//! perpetual-futures indicator family. A single tick bundles the funding,
|
||||
//! price, open-interest, positioning, taker-flow and liquidation fields a
|
||||
//! perp/futures venue publishes per update; each indicator reads only the
|
||||
//! subset it needs (the same one-rich-type-per-family pattern as [`Trade`] /
|
||||
//! [`OrderBook`] in [`crate::microstructure`]).
|
||||
//!
|
||||
//! [`Trade`]: crate::microstructure::Trade
|
||||
//! [`OrderBook`]: crate::microstructure::OrderBook
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
/// A single derivatives / perpetual-futures market tick.
|
||||
///
|
||||
/// Field invariants enforced by [`new`](DerivativesTick::new):
|
||||
///
|
||||
/// - `funding_rate` is finite and **may be negative** (a negative funding rate
|
||||
/// means shorts pay longs).
|
||||
/// - `mark_price`, `index_price` and `futures_price` are finite and strictly
|
||||
/// positive.
|
||||
/// - `open_interest`, `long_size`, `short_size`, `taker_buy_volume`,
|
||||
/// `taker_sell_volume`, `long_liquidation` and `short_liquidation` are finite
|
||||
/// and non-negative.
|
||||
///
|
||||
/// `timestamp` is a caller-defined epoch / resolution and is not validated.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct DerivativesTick {
|
||||
/// Current funding rate for the interval (finite; may be negative).
|
||||
pub funding_rate: f64,
|
||||
/// Perpetual mark price (finite, strictly positive).
|
||||
pub mark_price: f64,
|
||||
/// Spot / index price the perpetual tracks (finite, strictly positive).
|
||||
pub index_price: f64,
|
||||
/// Dated (e.g. quarterly) futures mark price (finite, strictly positive).
|
||||
pub futures_price: f64,
|
||||
/// Open interest — outstanding contracts / notional (finite, non-negative).
|
||||
pub open_interest: f64,
|
||||
/// Aggregate long size / long account count (finite, non-negative).
|
||||
pub long_size: f64,
|
||||
/// Aggregate short size / short account count (finite, non-negative).
|
||||
pub short_size: f64,
|
||||
/// Taker buy (ask-lifting) volume (finite, non-negative).
|
||||
pub taker_buy_volume: f64,
|
||||
/// Taker sell (bid-hitting) volume (finite, non-negative).
|
||||
pub taker_sell_volume: f64,
|
||||
/// Long-side liquidation notional (finite, non-negative).
|
||||
pub long_liquidation: f64,
|
||||
/// Short-side liquidation notional (finite, non-negative).
|
||||
pub short_liquidation: f64,
|
||||
/// Tick timestamp (caller-defined epoch / resolution).
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
impl DerivativesTick {
|
||||
/// Construct a derivatives tick, validating every field invariant.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::InvalidDerivatives`] if `funding_rate` is not finite;
|
||||
/// any of `mark_price`, `index_price`, `futures_price` is not a finite
|
||||
/// positive number; or any of the six size / volume / liquidation fields is
|
||||
/// not a finite non-negative number.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
funding_rate: f64,
|
||||
mark_price: f64,
|
||||
index_price: f64,
|
||||
futures_price: f64,
|
||||
open_interest: f64,
|
||||
long_size: f64,
|
||||
short_size: f64,
|
||||
taker_buy_volume: f64,
|
||||
taker_sell_volume: f64,
|
||||
long_liquidation: f64,
|
||||
short_liquidation: f64,
|
||||
timestamp: i64,
|
||||
) -> Result<Self> {
|
||||
if !funding_rate.is_finite() {
|
||||
return Err(Error::InvalidDerivatives {
|
||||
message: "funding_rate must be finite",
|
||||
});
|
||||
}
|
||||
for price in [mark_price, index_price, futures_price] {
|
||||
if !price.is_finite() || price <= 0.0 {
|
||||
return Err(Error::InvalidDerivatives {
|
||||
message:
|
||||
"mark_price, index_price and futures_price must be finite and positive",
|
||||
});
|
||||
}
|
||||
}
|
||||
for amount in [
|
||||
open_interest,
|
||||
long_size,
|
||||
short_size,
|
||||
taker_buy_volume,
|
||||
taker_sell_volume,
|
||||
long_liquidation,
|
||||
short_liquidation,
|
||||
] {
|
||||
if !amount.is_finite() || amount < 0.0 {
|
||||
return Err(Error::InvalidDerivatives {
|
||||
message: "open interest, sizes, volumes and liquidations must be finite and non-negative",
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
funding_rate,
|
||||
mark_price,
|
||||
index_price,
|
||||
futures_price,
|
||||
open_interest,
|
||||
long_size,
|
||||
short_size,
|
||||
taker_buy_volume,
|
||||
taker_sell_volume,
|
||||
long_liquidation,
|
||||
short_liquidation,
|
||||
timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
/// Construct a derivatives tick without validation. The caller asserts that
|
||||
/// every field invariant documented on [`DerivativesTick`] holds.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[must_use]
|
||||
pub const fn new_unchecked(
|
||||
funding_rate: f64,
|
||||
mark_price: f64,
|
||||
index_price: f64,
|
||||
futures_price: f64,
|
||||
open_interest: f64,
|
||||
long_size: f64,
|
||||
short_size: f64,
|
||||
taker_buy_volume: f64,
|
||||
taker_sell_volume: f64,
|
||||
long_liquidation: f64,
|
||||
short_liquidation: f64,
|
||||
timestamp: i64,
|
||||
) -> Self {
|
||||
Self {
|
||||
funding_rate,
|
||||
mark_price,
|
||||
index_price,
|
||||
futures_price,
|
||||
open_interest,
|
||||
long_size,
|
||||
short_size,
|
||||
taker_buy_volume,
|
||||
taker_sell_volume,
|
||||
long_liquidation,
|
||||
short_liquidation,
|
||||
timestamp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A fully valid tick used as a baseline; individual tests override one
|
||||
/// field to exercise a single reject branch.
|
||||
fn valid() -> DerivativesTick {
|
||||
DerivativesTick::new(
|
||||
0.0001, 100.0, 99.5, 100.5, 1_000.0, 600.0, 400.0, 50.0, 40.0, 5.0, 3.0, 42,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_accepts_valid() {
|
||||
let tick = valid();
|
||||
assert_eq!(tick.funding_rate, 0.0001);
|
||||
assert_eq!(tick.mark_price, 100.0);
|
||||
assert_eq!(tick.index_price, 99.5);
|
||||
assert_eq!(tick.futures_price, 100.5);
|
||||
assert_eq!(tick.open_interest, 1_000.0);
|
||||
assert_eq!(tick.long_size, 600.0);
|
||||
assert_eq!(tick.short_size, 400.0);
|
||||
assert_eq!(tick.taker_buy_volume, 50.0);
|
||||
assert_eq!(tick.taker_sell_volume, 40.0);
|
||||
assert_eq!(tick.long_liquidation, 5.0);
|
||||
assert_eq!(tick.short_liquidation, 3.0);
|
||||
assert_eq!(tick.timestamp, 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_accepts_negative_funding_and_zero_amounts() {
|
||||
let tick = DerivativesTick::new(
|
||||
-0.0005, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(tick.funding_rate, -0.0005);
|
||||
assert_eq!(tick.open_interest, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_non_finite_funding() {
|
||||
assert!(matches!(
|
||||
DerivativesTick::new(
|
||||
f64::NAN,
|
||||
100.0,
|
||||
100.0,
|
||||
100.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0
|
||||
),
|
||||
Err(Error::InvalidDerivatives { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
DerivativesTick::new(
|
||||
f64::INFINITY,
|
||||
100.0,
|
||||
100.0,
|
||||
100.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0
|
||||
),
|
||||
Err(Error::InvalidDerivatives { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_non_positive_mark() {
|
||||
assert!(matches!(
|
||||
DerivativesTick::new(0.0, 0.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0),
|
||||
Err(Error::InvalidDerivatives { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_non_positive_index() {
|
||||
assert!(matches!(
|
||||
DerivativesTick::new(0.0, 100.0, -1.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0),
|
||||
Err(Error::InvalidDerivatives { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_non_finite_futures() {
|
||||
assert!(matches!(
|
||||
DerivativesTick::new(
|
||||
0.0,
|
||||
100.0,
|
||||
100.0,
|
||||
f64::NAN,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0
|
||||
),
|
||||
Err(Error::InvalidDerivatives { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_negative_open_interest() {
|
||||
assert!(matches!(
|
||||
DerivativesTick::new(0.0, 100.0, 100.0, 100.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0),
|
||||
Err(Error::InvalidDerivatives { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_non_finite_size() {
|
||||
assert!(matches!(
|
||||
DerivativesTick::new(
|
||||
0.0,
|
||||
100.0,
|
||||
100.0,
|
||||
100.0,
|
||||
0.0,
|
||||
f64::INFINITY,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0
|
||||
),
|
||||
Err(Error::InvalidDerivatives { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_negative_liquidation() {
|
||||
assert!(matches!(
|
||||
DerivativesTick::new(0.0, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2.0, 0),
|
||||
Err(Error::InvalidDerivatives { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_unchecked_preserves_fields() {
|
||||
let tick = DerivativesTick::new_unchecked(
|
||||
-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0, -10.0, -11.0, 7,
|
||||
);
|
||||
assert_eq!(tick.funding_rate, -1.0);
|
||||
assert_eq!(tick.mark_price, -2.0);
|
||||
assert_eq!(tick.short_liquidation, -11.0);
|
||||
assert_eq!(tick.timestamp, 7);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,15 @@ pub enum Error {
|
||||
/// non-finite price or negative size) was provided.
|
||||
#[error("invalid trade: {message}")]
|
||||
InvalidTrade { message: &'static str },
|
||||
|
||||
/// A derivatives tick whose components do not satisfy the tick invariants
|
||||
/// (e.g. a non-positive price, a non-finite funding rate, or a negative
|
||||
/// size/volume/liquidation) was provided. Derivatives ticks (funding /
|
||||
/// open-interest / liquidation feeds) are a perpetual-futures input
|
||||
/// distinct from candles, order books and trades, so they surface as their
|
||||
/// own variant.
|
||||
#[error("invalid derivatives tick: {message}")]
|
||||
InvalidDerivatives { message: &'static str },
|
||||
}
|
||||
|
||||
/// Convenience alias for `Result<T, wickra_core::Error>`.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@
|
||||
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
|
||||
mod derivatives;
|
||||
mod error;
|
||||
mod microstructure;
|
||||
mod ohlcv;
|
||||
@@ -43,6 +44,7 @@ mod traits;
|
||||
|
||||
pub mod indicators;
|
||||
|
||||
pub use derivatives::DerivativesTick;
|
||||
pub use error::{Error, Result};
|
||||
pub use indicators::{
|
||||
AccelerationBands, AccelerationBandsOutput, AcceleratorOscillator, AdOscillator, AdaptiveCycle,
|
||||
@@ -60,23 +62,23 @@ pub use indicators::{
|
||||
DrawdownDuration, EaseOfMovement, EffectiveSpread, EhlersStochastic, ElderImpulse, Ema,
|
||||
EmpiricalModeDecomposition, Engulfing, Evwma, Fama, FibonacciPivots, FibonacciPivotsOutput,
|
||||
FisherTransform, Footprint, FootprintOutput, ForceIndex, FractalChaosBands,
|
||||
FractalChaosBandsOutput, Frama, GainLossRatio, GarmanKlassVolatility, Hammer, HangingMan,
|
||||
Harami, HeikinAshi, HeikinAshiOutput, HiLoActivator, HilbertDominantCycle,
|
||||
HistoricalVolatility, Hma, HurstChannel, HurstChannelOutput, HurstExponent, Ichimoku,
|
||||
IchimokuOutput, Inertia, InformationRatio, InitialBalance, InitialBalanceOutput,
|
||||
InstantaneousTrendline, InverseFisherTransform, InvertedHammer, Jma, Kama, KellyCriterion,
|
||||
Keltner, KeltnerOutput, Kst, KstOutput, Kurtosis, Kvo, KylesLambda, LaguerreRsi,
|
||||
LeadLagCrossCorrelation, LeadLagCrossCorrelationOutput, LinRegAngle, LinRegChannel,
|
||||
LinRegChannelOutput, LinRegSlope, LinearRegression, MaEnvelope, MaEnvelopeOutput,
|
||||
MacdIndicator, MacdOutput, Mama, MamaOutput, MarketFacilitationIndex, Marubozu, MassIndex,
|
||||
MaxDrawdown, McGinleyDynamic, MedianAbsoluteDeviation, MedianPrice, Mfi, Microprice, Mom,
|
||||
MorningEveningStar, Natr, Nvi, Obv, OmegaRatio, OpeningRange, OpeningRangeOutput,
|
||||
OrderBookImbalanceFull, OrderBookImbalanceTop1, OrderBookImbalanceTopN, PainIndex,
|
||||
PairSpreadZScore, PairwiseBeta, ParkinsonVolatility, PearsonCorrelation, PercentB,
|
||||
PercentageTrailingStop, Pgo, PiercingDarkCloud, Pmo, Ppo, ProfitFactor, Psar, Pvi,
|
||||
QuotedSpread, RSquared, RealizedSpread, RecoveryFactor, RelativeStrengthAB,
|
||||
RelativeStrengthOutput, RenkoTrailingStop, Roc, RogersSatchellVolatility, RollingVwap,
|
||||
RoofingFilter, Rsi, Rvi, RviVolatility, Rwi, RwiOutput, SharpeRatio, ShootingStar,
|
||||
FractalChaosBandsOutput, Frama, FundingBasis, FundingRate, FundingRateMean, FundingRateZScore,
|
||||
GainLossRatio, GarmanKlassVolatility, Hammer, HangingMan, Harami, HeikinAshi, HeikinAshiOutput,
|
||||
HiLoActivator, HilbertDominantCycle, HistoricalVolatility, Hma, HurstChannel,
|
||||
HurstChannelOutput, HurstExponent, Ichimoku, IchimokuOutput, Inertia, InformationRatio,
|
||||
InitialBalance, InitialBalanceOutput, InstantaneousTrendline, InverseFisherTransform,
|
||||
InvertedHammer, Jma, Kama, KellyCriterion, Keltner, KeltnerOutput, Kst, KstOutput, Kurtosis,
|
||||
Kvo, KylesLambda, LaguerreRsi, LeadLagCrossCorrelation, LeadLagCrossCorrelationOutput,
|
||||
LinRegAngle, LinRegChannel, LinRegChannelOutput, LinRegSlope, LinearRegression, MaEnvelope,
|
||||
MaEnvelopeOutput, MacdIndicator, MacdOutput, Mama, MamaOutput, MarketFacilitationIndex,
|
||||
Marubozu, MassIndex, MaxDrawdown, McGinleyDynamic, MedianAbsoluteDeviation, MedianPrice, Mfi,
|
||||
Microprice, Mom, MorningEveningStar, Natr, Nvi, Obv, OmegaRatio, OpenInterestDelta,
|
||||
OpeningRange, OpeningRangeOutput, OrderBookImbalanceFull, OrderBookImbalanceTop1,
|
||||
OrderBookImbalanceTopN, PainIndex, PairSpreadZScore, PairwiseBeta, ParkinsonVolatility,
|
||||
PearsonCorrelation, PercentB, PercentageTrailingStop, Pgo, PiercingDarkCloud, Pmo, Ppo,
|
||||
ProfitFactor, Psar, Pvi, QuotedSpread, RSquared, RealizedSpread, RecoveryFactor,
|
||||
RelativeStrengthAB, RelativeStrengthOutput, RenkoTrailingStop, Roc, RogersSatchellVolatility,
|
||||
RollingVwap, RoofingFilter, Rsi, Rvi, RviVolatility, Rwi, RwiOutput, SharpeRatio, ShootingStar,
|
||||
SignedVolume, SineWave, Skewness, Sma, Smi, Smma, SortinoRatio, SpearmanCorrelation,
|
||||
SpinningTop, StandardError, StandardErrorBands, StandardErrorBandsOutput, StarcBands,
|
||||
StarcBandsOutput, Stc, StdDev, StepTrailingStop, StochRsi, Stochastic, StochasticOutput,
|
||||
|
||||
Reference in New Issue
Block a user