trading_types/
price.rs

1use core::ops;
2use std::cmp::{Eq, PartialEq, PartialOrd};
3// use std::cmp::{Ord, Ordering};
4use std::hash::{Hash, Hasher};
5
6use serde::{Deserialize, Serialize};
7
8// Price (exchange rate) for base/quote
9#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialOrd, PartialEq)]
10pub struct Price(pub f64); // NaN, inf are not allowed
11
12impl Hash for Price {
13    fn hash<H>(&self, state: &mut H)
14    where
15        H: Hasher,
16    {
17        self.0.to_bits().hash(state)
18    }
19}
20
21impl Eq for Price {}
22
23impl ops::Sub<Price> for Price {
24    type Output = Self;
25    fn sub(self, rhs: Price) -> Self {
26        Self(self.0 - rhs.0)
27    }
28}
29
30impl ops::Add<Price> for Price {
31    type Output = Self;
32    fn add(self, rhs: Price) -> Self {
33        Self(self.0 + rhs.0)
34    }
35}
36
37impl ops::AddAssign<Price> for Price {
38    fn add_assign(&mut self, rhs: Price) {
39        self.0 += rhs.0;
40    }
41}
42
43impl ops::SubAssign<Price> for Price {
44    fn sub_assign(&mut self, rhs: Price) {
45        self.0 -= rhs.0;
46    }
47}
48
49impl ops::Mul<f64> for Price {
50    type Output = Self;
51    fn mul(self, rhs: f64) -> Self {
52        Self(self.0 * rhs)
53    }
54}
55
56impl ops::Div<f64> for Price {
57    type Output = Self;
58    fn div(self, rhs: f64) -> Self {
59        Self(self.0 / rhs)
60    }
61}
62
63impl ops::Div<Price> for f64 {
64    type Output = Price;
65    fn div(self, rhs: Price) -> Price {
66        Price(self / rhs.0)
67    }
68}
69
70impl ops::Div<Price> for Price {
71    type Output = f64;
72    fn div(self, rhs: Price) -> f64 {
73        self.0 / rhs.0
74    }
75}
76
77// for min, max
78// https://www.reddit.com/r/rust/comments/29kia3/no_ord_for_f32/
79// impl Ord for Price {
80//     fn cmp(&self, rhs: &Self) -> Ordering {
81//         self.0.partial_cmp(&rhs.0).unwrap_or(Ordering::Equal)
82//     }
83// }