architect_api/utils/
dir_pair.rs

1use crate::Dir;
2#[cfg(feature = "netidx")]
3use derive::FromValue;
4#[cfg(feature = "netidx")]
5use netidx_derive::Pack;
6use rust_decimal::Decimal;
7use rust_decimal_macros::dec;
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11/// A dirpair is a structure for holding things that depend on trading direction.
12///
13/// For example one might hold one's position in a particular coin in a `DirPair<Decimal>`.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
15#[cfg_attr(feature = "netidx", derive(Pack, FromValue))]
16pub struct DirPair<T: 'static> {
17    pub buy: T,
18    pub sell: T,
19}
20
21impl<T: Default + 'static> Default for DirPair<T> {
22    fn default() -> Self {
23        Self { buy: T::default(), sell: T::default() }
24    }
25}
26
27impl<T: 'static> DirPair<T> {
28    /// get a shared reference to the field specified by dir
29    pub fn get(&self, dir: Dir) -> &T {
30        match dir {
31            Dir::Buy => &self.buy,
32            Dir::Sell => &self.sell,
33        }
34    }
35
36    /// get a mutable reference to field side specified by dir
37    pub fn get_mut(&mut self, dir: Dir) -> &mut T {
38        match dir {
39            Dir::Buy => &mut self.buy,
40            Dir::Sell => &mut self.sell,
41        }
42    }
43}
44
45impl DirPair<Decimal> {
46    /// true if both sides are 0
47    pub fn is_empty(&self) -> bool {
48        self.buy == dec!(0) && self.sell == dec!(0)
49    }
50
51    /// net the buy and the sell side (buy - sell)
52    pub fn net(&self) -> Decimal {
53        self.buy - self.sell
54    }
55}