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/// A venue's own identifier for one order, carried through opaquely.
70///
71/// # Uniqueness is the venue's to define, and is not global
72///
73/// Each venue mints its own ids, so two venues can issue the same one: the key that identifies an
74/// order is `(exchange, OrderId)`, not the id alone. A consumer that keys on the id by itself will
75/// merge unrelated orders from different venues.
76///
77/// [`SimulatedVenue`](crate::exchange::mock::SimulatedVenue) mints ids unique within one venue
78/// instance for its lifetime — and, because each venue counts from zero, **not** across the
79/// several a multi-exchange backtest holds. That is the same scoping a real venue gives. Within
80/// one venue, a minted id never repeats a decimal id seeded through its initial account state.
81#[derive(
82 Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display, From,
83)]
84pub struct OrderId<T = SmolStr>(pub T);
85
86impl OrderId {
87 pub fn new<S: AsRef<str>>(id: S) -> Self {
88 Self(SmolStr::new(id))
89 }
90}
91
92/// How an order accepted by a venue can be addressed.
93///
94/// A venue normally answers an accepted order with an identifier of its own, and that identifier
95/// is what every later message about the order carries. Some venues do not: they acknowledge the
96/// order while assigning nothing, and it remains addressable only by the [`ClientOrderId`] the
97/// caller sent. Hyperliquid does this for an order that is resting but not yet triggered, where
98/// the cancel endpoint takes the client id.
99///
100/// Naming both cases keeps them apart. The alternative -- storing the client id in the same field
101/// as a venue id -- makes the field a union of two identifier kinds that can only be told apart by
102/// inspecting the string, and leaves a consumer unable to answer the one question that matters:
103/// whether two states describe the same venue order. See [`Self::assigned`].
104#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
105pub enum VenueOrderId {
106 /// The venue assigned its own identifier, and this is it.
107 Assigned(OrderId),
108 /// The venue accepted the order without assigning an identifier. It is addressable only by
109 /// the [`ClientOrderId`] that was sent with it.
110 ClientAssigned,
111}
112
113impl VenueOrderId {
114 /// The venue's own identifier, or `None` if it never assigned one.
115 ///
116 /// Use this rather than matching on the variant when the question is identity: two states
117 /// describe the same venue order only when both are `Some` and equal. Two `None`s prove
118 /// nothing -- neither carries an identifier to compare -- so `None == None` must not be read
119 /// as a match.
120 pub fn assigned(&self) -> Option<&OrderId> {
121 match self {
122 Self::Assigned(id) => Some(id),
123 Self::ClientAssigned => None,
124 }
125 }
126
127 /// Whether this is the same venue order as `other`, as far as either can tell.
128 ///
129 /// `false` unless both carry a venue identifier and the two agree. A state with no venue
130 /// identifier cannot be shown to be the same order as anything, including another such state.
131 pub fn is_same_order_as(&self, other: &Self) -> bool {
132 match (self.assigned(), other.assigned()) {
133 (Some(lhs), Some(rhs)) => lhs == rhs,
134 _ => false,
135 }
136 }
137
138 /// Whether the venue has assigned an identifier that differs from `other`'s.
139 ///
140 /// This is the safe negation of [`Self::is_same_order_as`]: it is `true` only on positive
141 /// evidence of a *different* order, never on the mere absence of an identifier. A caller
142 /// rejecting an update must test this rather than `!is_same_order_as(..)`, which is also
143 /// `true` when nothing is known.
144 pub fn contradicts(&self, other: &Self) -> bool {
145 match (self.assigned(), other.assigned()) {
146 (Some(lhs), Some(rhs)) => lhs != rhs,
147 _ => false,
148 }
149 }
150
151 /// The identifier a *terminal* state records for this order.
152 ///
153 /// `Cancelled`, `Filled` and `Expired` carry a plain [`OrderId`]: they are records of an order
154 /// that has ended, not handles for addressing one, and nothing compares them for identity. An
155 /// order the venue never named has no identifier of its own to record, so it records `cid` --
156 /// the client id it was addressed by throughout its life.
157 pub fn or_client_id(&self, cid: &ClientOrderId) -> OrderId {
158 match self {
159 Self::Assigned(id) => id.clone(),
160 Self::ClientAssigned => OrderId(cid.0.clone()),
161 }
162 }
163}
164
165impl From<OrderId> for VenueOrderId {
166 fn from(id: OrderId) -> Self {
167 Self::Assigned(id)
168 }
169}
170
171impl std::fmt::Display for VenueOrderId {
172 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 match self {
174 Self::Assigned(id) => id.fmt(f),
175 // Deliberately not an empty string: this appears in diagnostics, where "no venue id"
176 // and "a venue id that happens to be empty" must not look alike.
177 Self::ClientAssigned => f.write_str("<client-assigned>"),
178 }
179 }
180}
181
182#[derive(
183 Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display, From,
184)]
185pub struct StrategyId(pub SmolStr);
186
187impl StrategyId {
188 pub fn new<S: AsRef<str>>(id: S) -> Self {
189 Self(SmolStr::new(id))
190 }
191
192 pub fn unknown() -> Self {
193 // "unknown" is 7 bytes — always inline; new_inline avoids the heap-allocation
194 // branch in SmolStr::new and is safe because the literal fits.
195 Self(SmolStr::new_inline("unknown"))
196 }
197
198 /// The fixed `StrategyId` used for synthetic settlement trades generated by the engine
199 /// on `ContractExpiry`. Using a `pub const` prevents bypassing any future validation.
200 ///
201 /// Note: conceptually this constant belongs to `rustrade::engine` (it is used exclusively
202 /// by the engine's contract lifecycle logic). It lives here because `StrategyId` is
203 /// defined in `rustrade-execution`; moving it to `rustrade::engine` would add a `smol_str`
204 /// import to that crate for a single constant.
205 pub const ENGINE_EXPIRY: StrategyId = StrategyId(SmolStr::new_static("__engine_expiry__"));
206}
207
208/// Opaque identifier for a tracked position.
209///
210/// In `OmsMode::Netting` this is always `"netting"` (at most one position per instrument).
211/// In `OmsMode::Hedging` this is derived from the `ClientOrderId` of the opening order,
212/// specified via [`crate::order::request::RequestOpen::position_id`] at order submission.
213#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
214pub struct PositionId(pub SmolStr);
215
216impl PositionId {
217 pub fn new(id: impl Into<SmolStr>) -> Self {
218 Self(id.into())
219 }
220
221 /// The fixed `PositionId` used for all netting-mode positions.
222 pub const NETTING: PositionId = PositionId(SmolStr::new_static("netting"));
223}
224
225impl Default for PositionId {
226 fn default() -> Self {
227 Self::NETTING
228 }
229}
230
231impl std::fmt::Display for PositionId {
232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233 self.0.fmt(f)
234 }
235}
236
237#[cfg(test)]
238#[allow(clippy::expect_used)] // Test code: panics on bad input are acceptable
239mod tests {
240 use super::*;
241
242 #[test]
243 fn client_order_id_random_is_23_bytes() {
244 let cid = ClientOrderId::random();
245 assert_eq!(cid.0.len(), 23);
246 }
247
248 #[test]
249 fn assigned_exposes_only_an_id_the_venue_gave() {
250 assert_eq!(
251 VenueOrderId::Assigned(OrderId::new("12345")).assigned(),
252 Some(&OrderId::new("12345"))
253 );
254 assert_eq!(VenueOrderId::ClientAssigned.assigned(), None);
255 }
256
257 /// The distinction the whole type exists for: absence of an identifier is not an identifier
258 /// that two orders can share. Deriving `PartialEq` makes two `ClientAssigned` values equal, so
259 /// anything asking "same order?" must go through these methods rather than `==`.
260 #[test]
261 fn two_orders_the_venue_has_not_named_are_not_shown_to_be_the_same_order() {
262 let unnamed = VenueOrderId::ClientAssigned;
263 let also_unnamed = VenueOrderId::ClientAssigned;
264
265 assert_eq!(unnamed, also_unnamed, "the derived equality still holds");
266 assert!(!unnamed.is_same_order_as(&also_unnamed));
267 // Nor are they evidence of being *different* orders, so neither test fires.
268 assert!(!unnamed.contradicts(&also_unnamed));
269 }
270
271 #[test]
272 fn identity_needs_two_agreeing_venue_ids_and_contradiction_needs_two_disagreeing_ones() {
273 let a = VenueOrderId::Assigned(OrderId::new("A"));
274 let a_again = VenueOrderId::Assigned(OrderId::new("A"));
275 let b = VenueOrderId::Assigned(OrderId::new("B"));
276 let unnamed = VenueOrderId::ClientAssigned;
277
278 assert!(a.is_same_order_as(&a_again));
279 assert!(!a.contradicts(&a_again));
280
281 assert!(!a.is_same_order_as(&b));
282 assert!(a.contradicts(&b));
283
284 // An unnamed order proves nothing either way, in either direction.
285 assert!(!a.is_same_order_as(&unnamed));
286 assert!(!a.contradicts(&unnamed));
287 assert!(!unnamed.is_same_order_as(&a));
288 assert!(!unnamed.contradicts(&a));
289 }
290
291 #[test]
292 fn a_terminal_record_falls_back_to_the_client_id() {
293 let cid = ClientOrderId::new("cid-1");
294
295 assert_eq!(
296 VenueOrderId::Assigned(OrderId::new("12345")).or_client_id(&cid),
297 OrderId::new("12345")
298 );
299 assert_eq!(
300 VenueOrderId::ClientAssigned.or_client_id(&cid),
301 OrderId::new("cid-1")
302 );
303 }
304
305 /// `ClientAssigned` renders as a marker rather than an empty string, so a diagnostic cannot
306 /// confuse "no venue id" with "a venue id that happens to be empty".
307 #[test]
308 fn display_names_an_unnamed_order_rather_than_rendering_nothing() {
309 assert_eq!(
310 VenueOrderId::Assigned(OrderId::new("12345")).to_string(),
311 "12345"
312 );
313 assert_eq!(
314 VenueOrderId::ClientAssigned.to_string(),
315 "<client-assigned>"
316 );
317 }
318
319 #[test]
320 #[cfg(feature = "hyperliquid")]
321 fn client_order_id_uuid_is_valid_uuid() {
322 let cid = ClientOrderId::uuid();
323 // UUID v4 string is 36 chars (8-4-4-4-12 with hyphens)
324 assert_eq!(cid.0.len(), 36);
325 // Verify it parses as a valid UUID
326 uuid::Uuid::parse_str(&cid.0).expect("should be valid UUID");
327 }
328}