Skip to main content

apple_quant_algorithmic/backend/orders/
id.rs

1use thiserror::Error;
2
3#[derive(Debug, Error)]
4pub enum OrderIdError {
5	#[error("Invalid: {0:?}.")]
6	Invalid(OrderId),
7
8	#[error("Unavailable order id.")]
9	Unavailable,
10}
11
12/// Numerical identifier of different types of orders assigned by the client.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub enum OrderId {
15	Local(LocalOrderId),
16	Remote(RemoteOrderId),
17}
18
19impl OrderId {
20	pub fn err_invalid<T, E: From<OrderIdError>>(self) -> Result<T, E> {
21		Err(OrderIdError::Invalid(self).into())
22	}
23}
24
25impl From<LocalOrderId> for OrderId {
26	fn from(value: LocalOrderId) -> Self {
27		Self::Local(value)
28	}
29}
30
31impl From<RemoteOrderId> for OrderId {
32	fn from(value: RemoteOrderId) -> Self {
33		Self::Remote(value)
34	}
35}
36
37impl From<&LocalOrderId> for OrderId {
38	fn from(value: &LocalOrderId) -> Self {
39		Self::Local(*value)
40	}
41}
42
43impl From<&RemoteOrderId> for OrderId {
44	fn from(value: &RemoteOrderId) -> Self {
45		Self::Remote(*value)
46	}
47}
48
49pub struct OrderIdGenerator {
50	local_order_id: u64,
51}
52
53impl OrderIdGenerator {
54	pub(crate) fn new() -> Self {
55		Self { local_order_id: 0 }
56	}
57
58	pub fn next_local_order_id(&mut self) -> LocalOrderId {
59		self.local_order_id += 1;
60		LocalOrderId::new_from_u64(self.local_order_id)
61	}
62}
63
64/// Numerical identifier of an order that will be satisfied locally (eg. stop orders).
65#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub struct LocalOrderId(u64);
67
68impl LocalOrderId {
69	pub(crate) fn new_from_u64(value: u64) -> Self {
70		Self(value)
71	}
72
73	pub fn err_invalid<T, E: From<OrderIdError>>(self) -> Result<T, E> {
74		Err(OrderIdError::Invalid(OrderId::Local(self)).into())
75	}
76
77	pub fn as_order_id(&self) -> OrderId {
78		self.into()
79	}
80
81	pub fn into_order_id(self) -> OrderId {
82		self.into()
83	}
84}
85
86/// Numerical identifier of an order that will be satisfied remotely (eg. market and limit orders).
87#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
88pub struct RemoteOrderId(u64);
89
90impl RemoteOrderId {
91	pub(crate) fn new_from_u64(value: u64) -> Self {
92		Self(value)
93	}
94
95	pub fn err_invalid<T, E: From<OrderIdError>>(self) -> Result<T, E> {
96		Err(OrderIdError::Invalid(OrderId::Remote(self)).into())
97	}
98
99	pub fn as_order_id(&self) -> OrderId {
100		self.into()
101	}
102
103	pub fn into_order_id(self) -> OrderId {
104		self.into()
105	}
106}