Skip to main content

df_hyperliquid_core/markets/
side.rs

1//! The side of an order, a fill, a trade or a book level: `B` and `A` on the wire, one type
2//! wherever the venue writes it.
3
4use std::fmt;
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
7
8use crate::utils::dec::Round;
9
10/// `B` a buy or a bid, `A` a sell or an ask. On a trade it is the aggressor's
11/// side, on a fill the account's own, on a resting order the side of the book
12/// it rests on. A bid sorts before an ask.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
14pub enum Side {
15    /// `B`: a buy or a bid.
16    Buy,
17    /// `A`: a sell or an ask.
18    Sell,
19}
20
21impl Side {
22    /// Both sides, buy first.
23    pub const ALL: [Side; 2] = [Side::Buy, Side::Sell];
24
25    /// `B` or `A`, exactly as the venue writes it.
26    #[must_use]
27    pub fn parse(said: &str) -> Option<Side> {
28        match said {
29            "B" => Some(Side::Buy),
30            "A" => Some(Side::Sell),
31            _ => None,
32        }
33    }
34
35    /// `B` or `A`.
36    #[must_use]
37    pub const fn wire(self) -> &'static str {
38        match self {
39            Side::Buy => "B",
40            Side::Sell => "A",
41        }
42    }
43
44    /// Whether the side is [`Side::Buy`].
45    #[must_use]
46    pub const fn is_buy(self) -> bool {
47        matches!(self, Side::Buy)
48    }
49
50    /// The opposite side.
51    #[must_use]
52    pub const fn other(self) -> Side {
53        match self {
54            Side::Buy => Side::Sell,
55            Side::Sell => Side::Buy,
56        }
57    }
58
59    /// How a price for this side rounds onto the grid, never against the trader: a buy rounds
60    /// down, a sell up.
61    #[must_use]
62    pub const fn price_rounding(self) -> Round {
63        match self {
64            Side::Buy => Round::Down,
65            Side::Sell => Round::Up,
66        }
67    }
68}
69
70impl fmt::Display for Side {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(self.wire())
73    }
74}
75
76impl Serialize for Side {
77    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
78        serializer.serialize_str(self.wire())
79    }
80}
81
82impl<'de> Deserialize<'de> for Side {
83    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
84        let said = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
85        Side::parse(&said).ok_or_else(|| de::Error::custom(format!("`{said}` is not a side; expected B or A")))
86    }
87}
88
89#[cfg(test)]
90#[path = "tests/side.rs"]
91mod tests;