1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use crate::Dir;
use derive::FromValue;
use netidx_derive::Pack;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};

/// A dirpair is a structure for holding things that depend on trading direction.
///
/// For example one might hold one's position in a particular coin in a `DirPair<Decimal>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Pack, FromValue)]
pub struct DirPair<T: 'static> {
    pub buy: T,
    pub sell: T,
}

impl<T: Default + 'static> Default for DirPair<T> {
    fn default() -> Self {
        Self { buy: T::default(), sell: T::default() }
    }
}

impl<T: 'static> DirPair<T> {
    /// get a shared reference to the field specified by dir
    pub fn get(&self, dir: Dir) -> &T {
        match dir {
            Dir::Buy => &self.buy,
            Dir::Sell => &self.sell,
        }
    }

    /// get a mutable reference to field side specified by dir
    pub fn get_mut(&mut self, dir: Dir) -> &mut T {
        match dir {
            Dir::Buy => &mut self.buy,
            Dir::Sell => &mut self.sell,
        }
    }
}

impl DirPair<Decimal> {
    /// true if both sides are 0
    pub fn is_empty(&self) -> bool {
        self.buy == dec!(0) && self.sell == dec!(0)
    }

    /// net the buy and the sell side (buy - sell)
    pub fn net(&self) -> Decimal {
        self.buy - self.sell
    }
}