Skip to main content

kraken_types/
level.rs

1//! Price level types with decimal precision
2
3use rust_decimal::Decimal;
4use serde::{Deserialize, Deserializer, Serialize};
5
6/// A single price level in the orderbook
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct Level {
9    /// Price of this level
10    #[serde(deserialize_with = "deserialize_decimal")]
11    pub price: Decimal,
12    /// Quantity at this price level
13    #[serde(deserialize_with = "deserialize_decimal")]
14    pub qty: Decimal,
15}
16
17impl Level {
18    /// Create a new price level
19    pub fn new(price: Decimal, qty: Decimal) -> Self {
20        Self { price, qty }
21    }
22
23    /// Create a level from f64 values (for testing)
24    pub fn from_f64(price: f64, qty: f64) -> Self {
25        use rust_decimal::prelude::FromPrimitive;
26        Self {
27            price: Decimal::from_f64(price).unwrap_or_default(),
28            qty: Decimal::from_f64(qty).unwrap_or_default(),
29        }
30    }
31
32    /// Get price as f64 (for JavaScript interop)
33    pub fn price_f64(&self) -> f64 {
34        use rust_decimal::prelude::ToPrimitive;
35        self.price.to_f64().unwrap_or(0.0)
36    }
37
38    /// Get quantity as f64 (for JavaScript interop)
39    pub fn qty_f64(&self) -> f64 {
40        use rust_decimal::prelude::ToPrimitive;
41        self.qty.to_f64().unwrap_or(0.0)
42    }
43
44    /// Check if this level has zero quantity (should be removed)
45    pub fn is_zero(&self) -> bool {
46        self.qty.is_zero()
47    }
48}
49
50/// CRITICAL: Custom deserializer to preserve decimal precision
51/// Kraken sends JSON numbers that lose precision with f64
52fn deserialize_decimal<'de, D>(deserializer: D) -> Result<Decimal, D::Error>
53where
54    D: Deserializer<'de>,
55{
56    use rust_decimal::prelude::FromPrimitive;
57    use serde::de::Error;
58    use std::str::FromStr;
59
60    #[derive(Deserialize)]
61    #[serde(untagged)]
62    enum StringOrNumber {
63        String(String),
64        Number(serde_json::Number),
65    }
66
67    match StringOrNumber::deserialize(deserializer)? {
68        StringOrNumber::String(s) => Decimal::from_str(&s).map_err(D::Error::custom),
69        StringOrNumber::Number(n) => {
70            // First try to parse the string representation
71            let s = n.to_string();
72            // Handle scientific notation (e.g., 5e-6) by using f64 conversion
73            if s.contains('e') || s.contains('E') {
74                let f = n.as_f64().ok_or_else(|| D::Error::custom("invalid number"))?;
75                Decimal::from_f64(f).ok_or_else(|| D::Error::custom("cannot convert to decimal"))
76            } else {
77                Decimal::from_str(&s).map_err(D::Error::custom)
78            }
79        }
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn test_level_from_json_number() {
89        // Test parsing from JSON with number values (as sent by Kraken)
90        let json = r#"{"price": 88813.5, "qty": 0.00460208}"#;
91        let level: Level = serde_json::from_str(json).unwrap();
92
93        assert_eq!(level.price.to_string(), "88813.5");
94        assert_eq!(level.qty.to_string(), "0.00460208");
95    }
96
97    #[test]
98    fn test_level_from_json_string() {
99        // Test parsing from JSON with string values
100        let json = r#"{"price": "88813.5", "qty": "0.00460208"}"#;
101        let level: Level = serde_json::from_str(json).unwrap();
102
103        assert_eq!(level.price.to_string(), "88813.5");
104        assert_eq!(level.qty.to_string(), "0.00460208");
105    }
106
107    #[test]
108    fn test_level_precision_preserved() {
109        // Ensure precision is preserved for checksum calculation
110        // Using realistic Kraken values that don't trigger scientific notation
111        let json = r#"{"price": 88813.5, "qty": 0.00460208}"#;
112        let level: Level = serde_json::from_str(json).unwrap();
113
114        assert_eq!(level.price.to_string(), "88813.5");
115        assert_eq!(level.qty.to_string(), "0.00460208");
116    }
117
118    #[test]
119    fn test_level_small_qty() {
120        // Test small quantities that might be in scientific notation
121        let json = r#"{"price": 0.05005, "qty": 0.000005}"#;
122        let level: Level = serde_json::from_str(json).unwrap();
123
124        assert_eq!(level.price.to_string(), "0.05005");
125        // Small values might have trailing zeros stripped
126        assert!(level.qty > Decimal::ZERO);
127    }
128
129    #[test]
130    fn test_level_is_zero() {
131        let zero = Level::new(Decimal::new(100, 0), Decimal::ZERO);
132        assert!(zero.is_zero());
133
134        let non_zero = Level::new(Decimal::new(100, 0), Decimal::ONE);
135        assert!(!non_zero.is_zero());
136    }
137}