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}
29
30impl OrderType {
31    pub fn is_market_order(&self) -> bool {
32        matches!(self, OrderType::Market | OrderType::BoundedMarket { .. })
33    }
34}
35
36#[derive(
37    Default, Debug, serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, Hash,
38)]
39pub enum Side {
40    #[default]
41    Sell,
42    Buy,
43}
44
45impl Display for Side {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            Side::Sell => write!(f, "sell"),
49            Side::Buy => write!(f, "buy"),
50        }
51    }
52}
53
54impl FromStr for Side {
55    type Err = anyhow::Error;
56
57    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
58        match s {
59            "sell" => Ok(Side::Sell),
60            "buy" => Ok(Side::Buy),
61            s => Err(anyhow::anyhow!("Invalid side: {}", s)),
62        }
63    }
64}
65
66impl<T: AsRef<str>> From<T> for Side {
67    fn from(s: T) -> Self {
68        if s.as_ref() == "sell" {
69            Side::Sell
70        } else {
71            Side::Buy
72        }
73    }
74}
75
76impl From<Side> for String {
77    fn from(s: Side) -> Self {
78        if s == Side::Sell {
79            "sell".to_string()
80        } else {
81            "buy".to_string()
82        }
83    }
84}