Skip to main content

o2_primitives/
lib.rs

1//! Core trading primitives for the Fuel O2 exchange.
2//!
3//! This crate contains pure types with minimal dependencies,
4//! suitable for sharing across the entire O2 stack.
5
6use std::{
7    fmt::Display,
8    str::FromStr,
9};
10
11pub type Price = u64;
12
13/// Determines how the order should be matched in the order book.
14#[derive(
15    Default, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Clone, Copy, Hash,
16)]
17pub enum OrderType {
18    Limit(Price, u128),
19    #[default]
20    Spot,
21    FillOrKill,
22    PostOnly,
23    Market,
24    BoundedMarket {
25        max_price: Price,
26        min_price: Price,
27    },
28    TurboSharedSpot,
29    TurboSharedPostOnly,
30}
31
32impl OrderType {
33    pub fn is_market_order(&self) -> bool {
34        matches!(self, OrderType::Market | OrderType::BoundedMarket { .. })
35    }
36}
37
38#[derive(
39    Default, Debug, serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, Hash,
40)]
41pub enum Side {
42    #[default]
43    Sell,
44    Buy,
45}
46
47impl Display for Side {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        match self {
50            Side::Sell => write!(f, "sell"),
51            Side::Buy => write!(f, "buy"),
52        }
53    }
54}
55
56impl FromStr for Side {
57    type Err = anyhow::Error;
58
59    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
60        match s {
61            "sell" => Ok(Side::Sell),
62            "buy" => Ok(Side::Buy),
63            s => Err(anyhow::anyhow!("Invalid side: {}", s)),
64        }
65    }
66}
67
68impl<T: AsRef<str>> From<T> for Side {
69    fn from(s: T) -> Self {
70        if s.as_ref() == "sell" {
71            Side::Sell
72        } else {
73            Side::Buy
74        }
75    }
76}
77
78impl From<Side> for String {
79    fn from(s: Side) -> Self {
80        if s == Side::Sell {
81            "sell".to_string()
82        } else {
83            "buy".to_string()
84        }
85    }
86}