rustrade_execution/order/id.rs
1use derive_more::{Display, From};
2use rand::prelude::IndexedRandom;
3use serde::{Deserialize, Serialize};
4use smol_str::SmolStr;
5
6#[derive(
7 Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display, From,
8)]
9pub struct ClientOrderId<T = SmolStr>(pub T);
10
11impl ClientOrderId<SmolStr> {
12 /// Construct a `ClientOrderId` from the specified string.
13 ///
14 /// Use [`Self::random`] to generate a random stack-allocated `ClientOrderId`.
15 pub fn new<S: Into<SmolStr>>(id: S) -> Self {
16 Self(id.into())
17 }
18
19 /// Construct a `ClientOrderId` containing a UUID v4 string.
20 ///
21 /// Produces lowercase hyphenated format (`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`, 36 chars).
22 ///
23 /// Required for every Hyperliquid order, of any kind. The venue stores the id as a 16-byte
24 /// cloid and reports each order back under it, and only this spelling of a UUID converts
25 /// back to the same id. The Hyperliquid clients refuse an order under any other id,
26 /// including [`Self::random`], which suits other venues (stack-allocated, no heap).
27 #[cfg(feature = "hyperliquid")]
28 pub fn uuid() -> Self {
29 Self(SmolStr::new(uuid::Uuid::new_v4().to_string()))
30 }
31
32 /// Construct a stack-allocated `ClientOrderId` backed by a 23 byte [`SmolStr`].
33 pub fn random() -> Self {
34 const LEN_URL_SAFE_SYMBOLS: usize = 64;
35 const URL_SAFE_SYMBOLS: [char; LEN_URL_SAFE_SYMBOLS] = [
36 '_', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
37 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
38 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
39 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
40 ];
41 // SmolStr can be up to 23 bytes long without allocating
42 const LEN_NON_ALLOCATING_CID: usize = 23;
43
44 let mut thread_rng = rand::rng();
45
46 #[allow(clippy::expect_used)] // Invariant: URL_SAFE_SYMBOLS is a const 64-element array
47 let random_utf8: [u8; LEN_NON_ALLOCATING_CID] = std::array::from_fn(|_| {
48 let symbol = URL_SAFE_SYMBOLS
49 .choose(&mut thread_rng)
50 .expect("URL_SAFE_SYMBOLS slice is not empty");
51
52 *symbol as u8
53 });
54
55 #[allow(clippy::expect_used)] // Invariant: all URL_SAFE_SYMBOLS chars are ASCII
56 let random_utf8_str =
57 std::str::from_utf8(&random_utf8).expect("URL_SAFE_SYMBOLS are valid utf8");
58
59 Self(SmolStr::new_inline(random_utf8_str))
60 }
61}
62
63impl Default for ClientOrderId<SmolStr> {
64 fn default() -> Self {
65 Self::random()
66 }
67}
68
69#[derive(
70 Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display, From,
71)]
72pub struct OrderId<T = SmolStr>(pub T);
73
74impl OrderId {
75 pub fn new<S: AsRef<str>>(id: S) -> Self {
76 Self(SmolStr::new(id))
77 }
78}
79
80/// How an order accepted by a venue can be addressed.
81///
82/// A venue normally answers an accepted order with an identifier of its own, and that identifier
83/// is what every later message about the order carries. Some venues do not: they acknowledge the
84/// order while assigning nothing, and it remains addressable only by the [`ClientOrderId`] the
85/// caller sent. Hyperliquid does this for an order that is resting but not yet triggered, where
86/// the cancel endpoint takes the client id.
87///
88/// Naming both cases keeps them apart. The alternative -- storing the client id in the same field
89/// as a venue id -- makes the field a union of two identifier kinds that can only be told apart by
90/// inspecting the string, and leaves a consumer unable to answer the one question that matters:
91/// whether two states describe the same venue order. See [`Self::assigned`].
92#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
93pub enum VenueOrderId {
94 /// The venue assigned its own identifier, and this is it.
95 Assigned(OrderId),
96 /// The venue accepted the order without assigning an identifier. It is addressable only by
97 /// the [`ClientOrderId`] that was sent with it.
98 ClientAssigned,
99}
100
101impl VenueOrderId {
102 /// The venue's own identifier, or `None` if it never assigned one.
103 ///
104 /// Use this rather than matching on the variant when the question is identity: two states
105 /// describe the same venue order only when both are `Some` and equal. Two `None`s prove
106 /// nothing -- neither carries an identifier to compare -- so `None == None` must not be read
107 /// as a match.
108 pub fn assigned(&self) -> Option<&OrderId> {
109 match self {
110 Self::Assigned(id) => Some(id),
111 Self::ClientAssigned => None,
112 }
113 }
114
115 /// Whether this is the same venue order as `other`, as far as either can tell.
116 ///
117 /// `false` unless both carry a venue identifier and the two agree. A state with no venue
118 /// identifier cannot be shown to be the same order as anything, including another such state.
119 pub fn is_same_order_as(&self, other: &Self) -> bool {
120 match (self.assigned(), other.assigned()) {
121 (Some(lhs), Some(rhs)) => lhs == rhs,
122 _ => false,
123 }
124 }
125
126 /// Whether the venue has assigned an identifier that differs from `other`'s.
127 ///
128 /// This is the safe negation of [`Self::is_same_order_as`]: it is `true` only on positive
129 /// evidence of a *different* order, never on the mere absence of an identifier. A caller
130 /// rejecting an update must test this rather than `!is_same_order_as(..)`, which is also
131 /// `true` when nothing is known.
132 pub fn contradicts(&self, other: &Self) -> bool {
133 match (self.assigned(), other.assigned()) {
134 (Some(lhs), Some(rhs)) => lhs != rhs,
135 _ => false,
136 }
137 }
138
139 /// The identifier a *terminal* state records for this order.
140 ///
141 /// `Cancelled`, `Filled` and `Expired` carry a plain [`OrderId`]: they are records of an order
142 /// that has ended, not handles for addressing one, and nothing compares them for identity. An
143 /// order the venue never named has no identifier of its own to record, so it records `cid` --
144 /// the client id it was addressed by throughout its life.
145 pub fn or_client_id(&self, cid: &ClientOrderId) -> OrderId {
146 match self {
147 Self::Assigned(id) => id.clone(),
148 Self::ClientAssigned => OrderId(cid.0.clone()),
149 }
150 }
151}
152
153impl From<OrderId> for VenueOrderId {
154 fn from(id: OrderId) -> Self {
155 Self::Assigned(id)
156 }
157}
158
159impl std::fmt::Display for VenueOrderId {
160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 match self {
162 Self::Assigned(id) => id.fmt(f),
163 // Deliberately not an empty string: this appears in diagnostics, where "no venue id"
164 // and "a venue id that happens to be empty" must not look alike.
165 Self::ClientAssigned => f.write_str("<client-assigned>"),
166 }
167 }
168}
169
170#[derive(
171 Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display, From,
172)]
173pub struct StrategyId(pub SmolStr);
174
175impl StrategyId {
176 pub fn new<S: AsRef<str>>(id: S) -> Self {
177 Self(SmolStr::new(id))
178 }
179
180 pub fn unknown() -> Self {
181 // "unknown" is 7 bytes — always inline; new_inline avoids the heap-allocation
182 // branch in SmolStr::new and is safe because the literal fits.
183 Self(SmolStr::new_inline("unknown"))
184 }
185
186 /// The fixed `StrategyId` used for synthetic settlement trades generated by the engine
187 /// on `ContractExpiry`. Using a `pub const` prevents bypassing any future validation.
188 ///
189 /// Note: conceptually this constant belongs to `rustrade::engine` (it is used exclusively
190 /// by the engine's contract lifecycle logic). It lives here because `StrategyId` is
191 /// defined in `rustrade-execution`; moving it to `rustrade::engine` would add a `smol_str`
192 /// import to that crate for a single constant.
193 pub const ENGINE_EXPIRY: StrategyId = StrategyId(SmolStr::new_static("__engine_expiry__"));
194}
195
196/// Opaque identifier for a tracked position.
197///
198/// In `OmsMode::Netting` this is always `"netting"` (at most one position per instrument).
199/// In `OmsMode::Hedging` this is derived from the `ClientOrderId` of the opening order,
200/// specified via [`crate::order::request::RequestOpen::position_id`] at order submission.
201#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
202pub struct PositionId(pub SmolStr);
203
204impl PositionId {
205 pub fn new(id: impl Into<SmolStr>) -> Self {
206 Self(id.into())
207 }
208
209 /// The fixed `PositionId` used for all netting-mode positions.
210 pub const NETTING: PositionId = PositionId(SmolStr::new_static("netting"));
211}
212
213impl Default for PositionId {
214 fn default() -> Self {
215 Self::NETTING
216 }
217}
218
219impl std::fmt::Display for PositionId {
220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 self.0.fmt(f)
222 }
223}
224
225#[cfg(test)]
226#[allow(clippy::expect_used)] // Test code: panics on bad input are acceptable
227mod tests {
228 use super::*;
229
230 #[test]
231 fn client_order_id_random_is_23_bytes() {
232 let cid = ClientOrderId::random();
233 assert_eq!(cid.0.len(), 23);
234 }
235
236 #[test]
237 fn assigned_exposes_only_an_id_the_venue_gave() {
238 assert_eq!(
239 VenueOrderId::Assigned(OrderId::new("12345")).assigned(),
240 Some(&OrderId::new("12345"))
241 );
242 assert_eq!(VenueOrderId::ClientAssigned.assigned(), None);
243 }
244
245 /// The distinction the whole type exists for: absence of an identifier is not an identifier
246 /// that two orders can share. Deriving `PartialEq` makes two `ClientAssigned` values equal, so
247 /// anything asking "same order?" must go through these methods rather than `==`.
248 #[test]
249 fn two_orders_the_venue_has_not_named_are_not_shown_to_be_the_same_order() {
250 let unnamed = VenueOrderId::ClientAssigned;
251 let also_unnamed = VenueOrderId::ClientAssigned;
252
253 assert_eq!(unnamed, also_unnamed, "the derived equality still holds");
254 assert!(!unnamed.is_same_order_as(&also_unnamed));
255 // Nor are they evidence of being *different* orders, so neither test fires.
256 assert!(!unnamed.contradicts(&also_unnamed));
257 }
258
259 #[test]
260 fn identity_needs_two_agreeing_venue_ids_and_contradiction_needs_two_disagreeing_ones() {
261 let a = VenueOrderId::Assigned(OrderId::new("A"));
262 let a_again = VenueOrderId::Assigned(OrderId::new("A"));
263 let b = VenueOrderId::Assigned(OrderId::new("B"));
264 let unnamed = VenueOrderId::ClientAssigned;
265
266 assert!(a.is_same_order_as(&a_again));
267 assert!(!a.contradicts(&a_again));
268
269 assert!(!a.is_same_order_as(&b));
270 assert!(a.contradicts(&b));
271
272 // An unnamed order proves nothing either way, in either direction.
273 assert!(!a.is_same_order_as(&unnamed));
274 assert!(!a.contradicts(&unnamed));
275 assert!(!unnamed.is_same_order_as(&a));
276 assert!(!unnamed.contradicts(&a));
277 }
278
279 #[test]
280 fn a_terminal_record_falls_back_to_the_client_id() {
281 let cid = ClientOrderId::new("cid-1");
282
283 assert_eq!(
284 VenueOrderId::Assigned(OrderId::new("12345")).or_client_id(&cid),
285 OrderId::new("12345")
286 );
287 assert_eq!(
288 VenueOrderId::ClientAssigned.or_client_id(&cid),
289 OrderId::new("cid-1")
290 );
291 }
292
293 /// `ClientAssigned` renders as a marker rather than an empty string, so a diagnostic cannot
294 /// confuse "no venue id" with "a venue id that happens to be empty".
295 #[test]
296 fn display_names_an_unnamed_order_rather_than_rendering_nothing() {
297 assert_eq!(
298 VenueOrderId::Assigned(OrderId::new("12345")).to_string(),
299 "12345"
300 );
301 assert_eq!(
302 VenueOrderId::ClientAssigned.to_string(),
303 "<client-assigned>"
304 );
305 }
306
307 #[test]
308 #[cfg(feature = "hyperliquid")]
309 fn client_order_id_uuid_is_valid_uuid() {
310 let cid = ClientOrderId::uuid();
311 // UUID v4 string is 36 chars (8-4-4-4-12 with hyphens)
312 assert_eq!(cid.0.len(), 36);
313 // Verify it parses as a valid UUID
314 uuid::Uuid::parse_str(&cid.0).expect("should be valid UUID");
315 }
316}