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<
21		T,
22		E: From<OrderIdError>,
23	>(
24		self,
25	) -> Result<T, E> {
26		Err(OrderIdError::Invalid(self).into())
27	}
28}
29
30impl From<LocalOrderId> for OrderId {
31	fn from(
32		value: LocalOrderId,
33	) -> Self {
34		Self::Local(value)
35	}
36}
37
38impl From<RemoteOrderId> for OrderId {
39	fn from(
40		value: RemoteOrderId,
41	) -> Self {
42		Self::Remote(value)
43	}
44}
45
46impl From<&LocalOrderId> for OrderId {
47	fn from(
48		value: &LocalOrderId,
49	) -> Self {
50		Self::Local(*value)
51	}
52}
53
54impl From<&RemoteOrderId> for OrderId {
55	fn from(
56		value: &RemoteOrderId,
57	) -> Self {
58		Self::Remote(*value)
59	}
60}
61
62#[derive(Debug)]
63pub struct OrderIdGenerator {
64	local_order_id: u64,
65}
66
67impl OrderIdGenerator {
68	pub(crate) fn new() -> Self {
69		Self { local_order_id: 0 }
70	}
71
72	pub fn next_local_order_id(
73		&mut self,
74	) -> LocalOrderId {
75		self.local_order_id += 1;
76		LocalOrderId::new_from_u64(self.local_order_id)
77	}
78}
79
80/// Numerical identifier of an order that will be satisfied locally (eg. stop orders).
81#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
82pub struct LocalOrderId(u64);
83
84impl LocalOrderId {
85	pub(crate) fn new_from_u64(
86		value: u64,
87	) -> Self {
88		Self(value)
89	}
90
91	pub fn err_invalid<
92		T,
93		E: From<OrderIdError>,
94	>(
95		self,
96	) -> Result<T, E> {
97		Err(OrderIdError::Invalid(OrderId::Local(self)).into())
98	}
99
100	pub fn as_order_id(
101		&self,
102	) -> OrderId {
103		self.into()
104	}
105
106	pub fn into_order_id(
107		self,
108	) -> OrderId {
109		self.into()
110	}
111}
112
113/// Numerical identifier of an order that will be satisfied remotely (eg. market and limit orders).
114#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
115pub struct RemoteOrderId(u64);
116
117impl RemoteOrderId {
118	pub(crate) fn new_from_u64(
119		value: u64,
120	) -> Self {
121		Self(value)
122	}
123
124	pub fn err_invalid<
125		T,
126		E: From<OrderIdError>,
127	>(
128		self,
129	) -> Result<T, E> {
130		Err(OrderIdError::Invalid(OrderId::Remote(self)).into())
131	}
132
133	pub fn as_order_id(
134		&self,
135	) -> OrderId {
136		self.into()
137	}
138
139	pub fn into_order_id(
140		self,
141	) -> OrderId {
142		self.into()
143	}
144}