Skip to main content

digdigdig3_station/data/
basis.rs

1use digdigdig3::core::types::StreamEvent;
2use serde::{Deserialize, Serialize};
3
4use crate::series::DataPoint;
5
6/// 32 B record (LE):
7///   i64 ts_ms (8), f64 value (8), f64 mark (8), f64 index (8)
8///
9/// `value = mark - index`. The derived path (`BasisDerived`) always
10/// populates all four fields. The legacy WS path (no exchange emits
11/// `StreamEvent::Basis` today) populates `mark = NaN, index = NaN`.
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct BasisPoint {
14    pub ts_ms: i64,
15    /// basis = mark − index
16    pub value: f64,
17    pub mark:  f64,
18    pub index: f64,
19}
20
21const SIZE: usize = 32;
22
23impl DataPoint for BasisPoint {
24    const RECORD_SIZE: usize = SIZE;
25
26    fn encode(&self, out: &mut [u8]) {
27        out[0..8].copy_from_slice(&(self.ts_ms as u64).to_le_bytes());
28        out[8..16].copy_from_slice(&self.value.to_le_bytes());
29        out[16..24].copy_from_slice(&self.mark.to_le_bytes());
30        out[24..32].copy_from_slice(&self.index.to_le_bytes());
31    }
32
33    fn decode(bytes: &[u8]) -> Option<Self> {
34        if bytes.len() != SIZE { return None; }
35        Some(Self {
36            ts_ms: u64::from_le_bytes(bytes[0..8].try_into().ok()?) as i64,
37            value: f64::from_le_bytes(bytes[8..16].try_into().ok()?),
38            mark:  f64::from_le_bytes(bytes[16..24].try_into().ok()?),
39            index: f64::from_le_bytes(bytes[24..32].try_into().ok()?),
40        })
41    }
42
43    fn timestamp_ms(&self) -> i64 { self.ts_ms }
44
45    /// WS path: no exchange emits `StreamEvent::Basis` with real data today.
46    /// Populates `mark = NaN, index = NaN` for forward-compat if one ever does.
47    fn from_stream_event(ev: &StreamEvent) -> Option<Self> {
48        if let StreamEvent::Basis { basis, .. } = ev {
49            // Basis payload carries futures_price/index_price as Option<f64>;
50            // use NaN when absent so the record layout stays fixed-width.
51            Some(Self {
52                ts_ms: basis.timestamp,
53                value: basis.basis,
54                mark:  basis.futures_price.unwrap_or(f64::NAN),
55                index: basis.index_price.unwrap_or(f64::NAN),
56            })
57        } else {
58            None
59        }
60    }
61}