Skip to main content

weirdnet_exchange/
num.rs

1//! Exact decimal prices and quantities.
2//!
3//! [`Price`] and [`Qty`] wrap [`Decimal`] so a size can't be passed where a price belongs.
4//! They serialize as strings (`"64250.10"`), never as floats. `Price * Qty` is the notional,
5//! a plain [`Decimal`] in the quote asset.
6
7use std::fmt;
8use std::ops::{Add, Mul, Sub};
9use std::str::FromStr;
10
11pub use rust_decimal::Decimal;
12use serde::{Deserialize, Serialize};
13
14use crate::ExchangeError;
15
16/// How to round to an increment.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Rounding {
19    /// Toward negative infinity (sizes, buy prices).
20    Down,
21    /// Toward positive infinity (sell prices).
22    Up,
23    /// To the nearest multiple, halves away from zero.
24    Nearest,
25}
26
27/// `value` rounded to a multiple of `increment`. A zero or negative increment leaves it as is.
28pub fn round_to(value: Decimal, increment: Decimal, mode: Rounding) -> Decimal {
29    if increment <= Decimal::ZERO {
30        return value;
31    }
32    let n = value / increment;
33    let n = match mode {
34        Rounding::Down => n.floor(),
35        Rounding::Up => n.ceil(),
36        Rounding::Nearest => n.round_dp_with_strategy(0, rust_decimal::RoundingStrategy::MidpointAwayFromZero),
37    };
38    (n * increment).normalize()
39}
40
41/// `value` is a whole multiple of `increment` (always true for a zero increment).
42pub fn is_multiple(value: Decimal, increment: Decimal) -> bool {
43    increment <= Decimal::ZERO || (value % increment).is_zero()
44}
45
46macro_rules! decimal_newtype {
47    ($(#[$m:meta])* $name:ident) => {
48        $(#[$m])*
49        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
50        #[serde(transparent)]
51        pub struct $name(pub Decimal);
52
53        impl $name {
54            pub const ZERO: Self = Self(Decimal::ZERO);
55
56            pub fn new(value: Decimal) -> Self {
57                Self(value)
58            }
59
60            /// Parses an exact decimal string such as `"0.00012"`.
61            pub fn parse(s: &str) -> Result<Self, ExchangeError> {
62                Decimal::from_str_exact(s.trim()).map(Self).map_err(|e| ExchangeError::invalid(format!("{s:?}: {e}")))
63            }
64
65            pub fn value(self) -> Decimal {
66                self.0
67            }
68
69            pub fn is_zero(self) -> bool {
70                self.0.is_zero()
71            }
72
73            pub fn is_positive(self) -> bool {
74                self.0 > Decimal::ZERO
75            }
76
77            /// Rounded to a multiple of `increment`.
78            pub fn round_to(self, increment: Decimal, mode: Rounding) -> Self {
79                Self(round_to(self.0, increment, mode))
80            }
81
82            pub fn min(self, other: Self) -> Self {
83                if other < self { other } else { self }
84            }
85        }
86
87        impl fmt::Display for $name {
88            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89                fmt::Display::fmt(&self.0.normalize(), f)
90            }
91        }
92
93        impl FromStr for $name {
94            type Err = ExchangeError;
95            fn from_str(s: &str) -> Result<Self, ExchangeError> {
96                Self::parse(s)
97            }
98        }
99
100        impl From<Decimal> for $name {
101            fn from(d: Decimal) -> Self {
102                Self(d)
103            }
104        }
105
106        impl Add for $name {
107            type Output = Self;
108            fn add(self, o: Self) -> Self {
109                Self(self.0 + o.0)
110            }
111        }
112
113        impl Sub for $name {
114            type Output = Self;
115            fn sub(self, o: Self) -> Self {
116                Self(self.0 - o.0)
117            }
118        }
119    };
120}
121
122decimal_newtype!(
123    /// A price in the quote asset per unit of the base asset.
124    Price
125);
126decimal_newtype!(
127    /// A quantity of the base asset (or contracts).
128    Qty
129);
130
131impl Mul<Qty> for Price {
132    type Output = Decimal;
133    fn mul(self, q: Qty) -> Decimal {
134        self.0 * q.0
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    fn d(s: &str) -> Decimal {
143        Decimal::from_str_exact(s).unwrap()
144    }
145
146    #[test]
147    fn exact_parsing_rounding_and_strings() {
148        let p = Price::parse("64250.105").unwrap();
149        assert_eq!(p.round_to(d("0.01"), Rounding::Down), Price::parse("64250.10").unwrap());
150        assert_eq!(p.round_to(d("0.01"), Rounding::Up).to_string(), "64250.11");
151        assert_eq!(p.round_to(d("0.01"), Rounding::Nearest).to_string(), "64250.11");
152        assert_eq!(Qty::parse("0.000123456").unwrap().round_to(d("0.00001"), Rounding::Down).to_string(), "0.00012");
153        assert!(Price::parse("abc").is_err());
154        assert!(is_multiple(d("0.30"), d("0.1")) && !is_multiple(d("0.35"), d("0.1")) && is_multiple(d("7"), Decimal::ZERO));
155        // 0.1 + 0.2 is exactly 0.3.
156        assert_eq!(Price::parse("0.1").unwrap() + Price::parse("0.2").unwrap(), Price::parse("0.3").unwrap());
157        assert_eq!(Price::parse("2.5").unwrap() * Qty::parse("4").unwrap(), d("10"));
158        let json = serde_json::to_string(&Price::parse("64250.10").unwrap()).unwrap();
159        assert_eq!(json, "\"64250.10\"");
160        assert_eq!(serde_json::from_str::<Qty>("\"0.5\"").unwrap(), Qty::parse("0.5").unwrap());
161    }
162}