pragma_common/
instrument_type.rs

1#[derive(Debug, thiserror::Error)]
2pub enum InstrumentTypeError {
3    #[error("Unknown instrument_type")]
4    Unknown,
5}
6
7#[derive(Debug, Default, PartialEq, Eq, Hash, Clone, Copy, strum::EnumString, strum::Display)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize,))]
9#[cfg_attr(
10    feature = "borsh",
11    derive(borsh::BorshSerialize, borsh::BorshDeserialize)
12)]
13#[strum(ascii_case_insensitive, serialize_all = "UPPERCASE")]
14#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
15pub enum InstrumentType {
16    #[default]
17    Spot,
18    Perp,
19}
20
21impl InstrumentType {
22    pub const ALL: [Self; 2] = [Self::Spot, Self::Perp];
23
24    pub const fn to_id(&self) -> i32 {
25        match self {
26            Self::Spot => 1,
27            Self::Perp => 2,
28        }
29    }
30
31    pub const fn is_spot(&self) -> bool {
32        match self {
33            Self::Spot => true,
34            Self::Perp => false,
35        }
36    }
37
38    pub const fn is_perp(&self) -> bool {
39        match self {
40            Self::Spot => false,
41            Self::Perp => true,
42        }
43    }
44
45    pub const fn from_str_const(s: &str) -> Option<Self> {
46        match s.as_bytes() {
47            b"spot" | b"SPOT" | b"Spot" => Some(Self::Spot),
48            b"perp" | b"PERP" | b"Perp" => Some(Self::Perp),
49            _ => None,
50        }
51    }
52
53    pub fn to_ascii_uppercase(&self) -> String {
54        format!("{}", self).to_ascii_uppercase()
55    }
56}
57
58impl TryFrom<i32> for InstrumentType {
59    type Error = InstrumentTypeError;
60    fn try_from(value: i32) -> Result<Self, Self::Error> {
61        match value {
62            1 => Ok(Self::Spot),
63            2 => Ok(Self::Perp),
64            _ => Err(InstrumentTypeError::Unknown),
65        }
66    }
67}