orderbook-rs 0.7.0

A high-performance, lock-free price level implementation for limit order books in Rust. This library provides the building blocks for creating efficient trading systems with support for multiple order types and concurrent access patterns.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Closed taxonomy of order-rejection reasons exposed on the wire.
//!
//! [`RejectReason`] is the canonical wire-side reject code surfaced on
//! `OrderStatus::Rejected`. Each named variant carries a stable
//! `#[repr(u16)]` discriminant — consumers that publish or parse the
//! value over the wire can rely on those numbers staying stable across
//! `0.7.x` and `0.7.x → 0.7.y` patch upgrades.
//!
//! Forward compatibility is preserved by:
//!
//! - `#[non_exhaustive]` so adding a new variant is non-breaking on
//!   downstream `match` blocks (consumers must keep a wildcard arm).
//! - [`RejectReason::Other`] as an escape hatch for application-side
//!   extensions. Values `>= 1000` are reserved for caller use; the
//!   library itself will never emit a value in that range.
//!
//! The [`From<&OrderBookError>`](RejectReason#impl-From<%26OrderBookError>-for-RejectReason)
//! impl provides operational ergonomics for callers that already hold a
//! typed [`OrderBookError`]: the typed error is the impl detail, the
//! [`RejectReason`] is the stable public contract.

use crate::orderbook::error::OrderBookError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Closed taxonomy of reasons an order may be rejected at admission.
///
/// `RejectReason` is the stable wire-side reject code. Each variant has
/// an explicit `#[repr(u16)]` discriminant — consumers that publish or
/// parse the value over the wire can rely on those numbers staying
/// stable across `0.7.x` and `0.7.x → 0.7.y` patch upgrades. Forward
/// compatibility is preserved by:
///
/// - `#[non_exhaustive]` so adding a variant is non-breaking on
///   downstream `match` blocks.
/// - [`Self::Other`] as an escape hatch for application-side extensions.
///   Values `>= 1000` are reserved for caller use; the library will
///   never emit a value in that range.
///
/// # Discriminant table
///
/// | Variant                  | u16 |
/// |--------------------------|-----|
/// | `KillSwitchActive`       | 1   |
/// | `RiskMaxOpenOrders`      | 2   |
/// | `RiskMaxNotional`        | 3   |
/// | `RiskPriceBand`          | 4   |
/// | `PostOnlyWouldCross`     | 5   |
/// | `SelfTradePrevention`    | 6   |
/// | `InvalidPrice`           | 7   |
/// | `InvalidQuantity`        | 8   |
/// | `InvalidPriceLevel`      | 9   |
/// | `OrderSizeOutOfRange`    | 10  |
/// | `MissingUserId`          | 11  |
/// | `DuplicateOrderId`       | 12  |
/// | `InsufficientLiquidity`  | 13  |
/// | `Other(code)`            | code|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u16)]
pub enum RejectReason {
    /// New flow rejected because the operational kill switch is engaged.
    KillSwitchActive = 1,
    /// Per-account open-order limit would be breached by this admission.
    RiskMaxOpenOrders = 2,
    /// Per-account notional limit would be breached by this admission.
    RiskMaxNotional = 3,
    /// Submitted price exceeds the configured price band against the
    /// reference price.
    RiskPriceBand = 4,
    /// Post-only order would cross the resting opposite side at the
    /// time of admission.
    PostOnlyWouldCross = 5,
    /// Self-trade prevention rejected the incoming order.
    SelfTradePrevention = 6,
    /// Submitted price violates the configured tick-size validation.
    InvalidPrice = 7,
    /// Submitted quantity violates the configured lot-size validation.
    InvalidQuantity = 8,
    /// The targeted price level is invalid for the requested operation.
    InvalidPriceLevel = 9,
    /// Submitted quantity is outside the configured min/max range.
    OrderSizeOutOfRange = 10,
    /// `user_id` is missing or zero while STP is enabled.
    MissingUserId = 11,
    /// An order with the same id is already present in the book.
    DuplicateOrderId = 12,
    /// The order could not be filled with the available resting depth
    /// (IOC / FOK semantics).
    InsufficientLiquidity = 13,
    /// Caller-supplied / unmapped code. The library never emits this
    /// variant; it exists so applications can ferry their own reject
    /// codes through the same channel without forking the enum.
    Other(u16),
}

impl RejectReason {
    /// Numeric wire code. Stable across `0.7.x`.
    ///
    /// For named variants this returns the explicit `#[repr(u16)]`
    /// discriminant; for [`Self::Other`] this returns the wrapped
    /// caller-supplied code verbatim.
    #[inline]
    #[must_use]
    pub fn as_u16(self) -> u16 {
        match self {
            Self::KillSwitchActive => 1,
            Self::RiskMaxOpenOrders => 2,
            Self::RiskMaxNotional => 3,
            Self::RiskPriceBand => 4,
            Self::PostOnlyWouldCross => 5,
            Self::SelfTradePrevention => 6,
            Self::InvalidPrice => 7,
            Self::InvalidQuantity => 8,
            Self::InvalidPriceLevel => 9,
            Self::OrderSizeOutOfRange => 10,
            Self::MissingUserId => 11,
            Self::DuplicateOrderId => 12,
            Self::InsufficientLiquidity => 13,
            Self::Other(code) => code,
        }
    }

    /// Reconstruct a [`RejectReason`] from its wire code. Known
    /// discriminants map to their named variant; any other value is
    /// preserved via [`Self::Other`] so older deserializers can carry
    /// forward unknown codes minted by newer producers.
    #[inline]
    #[must_use]
    pub fn from_u16(code: u16) -> Self {
        match code {
            1 => Self::KillSwitchActive,
            2 => Self::RiskMaxOpenOrders,
            3 => Self::RiskMaxNotional,
            4 => Self::RiskPriceBand,
            5 => Self::PostOnlyWouldCross,
            6 => Self::SelfTradePrevention,
            7 => Self::InvalidPrice,
            8 => Self::InvalidQuantity,
            9 => Self::InvalidPriceLevel,
            10 => Self::OrderSizeOutOfRange,
            11 => Self::MissingUserId,
            12 => Self::DuplicateOrderId,
            13 => Self::InsufficientLiquidity,
            other => Self::Other(other),
        }
    }
}

/// Serialize as the stable `u16` wire code via [`RejectReason::as_u16`].
///
/// JSON / Bincode / any serde format encodes the numeric reject code,
/// not the variant name or an internal serde index. This is what the
/// wire-stability rustdoc on the type promises and what consumers can
/// rely on across `0.7.x` patch upgrades.
impl Serialize for RejectReason {
    #[inline]
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_u16(self.as_u16())
    }
}

/// Deserialize from the stable `u16` wire code via
/// [`RejectReason::from_u16`].
///
/// Unknown codes map to [`RejectReason::Other`] so an older deserializer
/// can still parse a payload minted by a newer producer that has
/// introduced a new reject variant.
impl<'de> Deserialize<'de> for RejectReason {
    #[inline]
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let code = u16::deserialize(deserializer)?;
        Ok(Self::from_u16(code))
    }
}

impl std::fmt::Display for RejectReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::KillSwitchActive => write!(f, "kill switch active"),
            Self::RiskMaxOpenOrders => write!(f, "risk: max open orders"),
            Self::RiskMaxNotional => write!(f, "risk: max notional"),
            Self::RiskPriceBand => write!(f, "risk: price band"),
            Self::PostOnlyWouldCross => write!(f, "post-only would cross"),
            Self::SelfTradePrevention => write!(f, "self-trade prevention"),
            Self::InvalidPrice => write!(f, "invalid price"),
            Self::InvalidQuantity => write!(f, "invalid quantity"),
            Self::InvalidPriceLevel => write!(f, "invalid price level"),
            Self::OrderSizeOutOfRange => write!(f, "order size out of range"),
            Self::MissingUserId => write!(f, "missing user id"),
            Self::DuplicateOrderId => write!(f, "duplicate order id"),
            Self::InsufficientLiquidity => write!(f, "insufficient liquidity"),
            Self::Other(code) => write!(f, "other({code})"),
        }
    }
}

/// Map a typed [`OrderBookError`] to its wire-side reject code.
///
/// Errors that do not represent a public reject (e.g.
/// `SerializationError`, `ChecksumMismatch`, `NatsPublishError`,
/// internal-state errors) map to \[`RejectReason::Other(0)`\] — they are
/// not expected to surface on outbound reject events.
///
/// The match below is intentionally exhaustive (no `_ =>` catch-all);
/// any new variant added to [`OrderBookError`] must extend this mapping
/// at compile time. This is enforced because the `impl` lives inside
/// the crate, where exhaustive matches over a `#[non_exhaustive]` enum
/// are still permitted.
impl From<&OrderBookError> for RejectReason {
    #[inline]
    fn from(err: &OrderBookError) -> Self {
        match err {
            OrderBookError::KillSwitchActive => Self::KillSwitchActive,
            OrderBookError::RiskMaxOpenOrders { .. } => Self::RiskMaxOpenOrders,
            OrderBookError::RiskMaxNotional { .. } => Self::RiskMaxNotional,
            OrderBookError::RiskPriceBand { .. } => Self::RiskPriceBand,
            OrderBookError::SelfTradePrevented { .. } => Self::SelfTradePrevention,
            OrderBookError::InvalidPriceLevel(_) => Self::InvalidPriceLevel,
            OrderBookError::PriceCrossing { .. } => Self::PostOnlyWouldCross,
            OrderBookError::InsufficientLiquidity { .. } => Self::InsufficientLiquidity,
            OrderBookError::InvalidTickSize { .. } => Self::InvalidPrice,
            OrderBookError::InvalidLotSize { .. } => Self::InvalidQuantity,
            OrderBookError::OrderSizeOutOfRange { .. } => Self::OrderSizeOutOfRange,
            OrderBookError::MissingUserId { .. } => Self::MissingUserId,
            OrderBookError::PriceLevelError(_) => Self::Other(0),
            OrderBookError::OrderNotFound(_) => Self::Other(0),
            OrderBookError::InvalidOperation { .. } => Self::Other(0),
            OrderBookError::SerializationError { .. } => Self::Other(0),
            OrderBookError::DeserializationError { .. } => Self::Other(0),
            OrderBookError::ChecksumMismatch { .. } => Self::Other(0),
            #[cfg(feature = "nats")]
            OrderBookError::NatsPublishError { .. } => Self::Other(0),
            #[cfg(feature = "nats")]
            OrderBookError::NatsSerializationError { .. } => Self::Other(0),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pricelevel::{Hash32, Id, PriceLevelError, Side};

    /// Every named variant — used to drive exhaustive table-style tests.
    /// The `Other` variant is added explicitly where needed.
    fn named_variants() -> [RejectReason; 13] {
        [
            RejectReason::KillSwitchActive,
            RejectReason::RiskMaxOpenOrders,
            RejectReason::RiskMaxNotional,
            RejectReason::RiskPriceBand,
            RejectReason::PostOnlyWouldCross,
            RejectReason::SelfTradePrevention,
            RejectReason::InvalidPrice,
            RejectReason::InvalidQuantity,
            RejectReason::InvalidPriceLevel,
            RejectReason::OrderSizeOutOfRange,
            RejectReason::MissingUserId,
            RejectReason::DuplicateOrderId,
            RejectReason::InsufficientLiquidity,
        ]
    }

    #[test]
    fn test_discriminants_are_stable() {
        assert_eq!(RejectReason::KillSwitchActive.as_u16(), 1);
        assert_eq!(RejectReason::RiskMaxOpenOrders.as_u16(), 2);
        assert_eq!(RejectReason::RiskMaxNotional.as_u16(), 3);
        assert_eq!(RejectReason::RiskPriceBand.as_u16(), 4);
        assert_eq!(RejectReason::PostOnlyWouldCross.as_u16(), 5);
        assert_eq!(RejectReason::SelfTradePrevention.as_u16(), 6);
        assert_eq!(RejectReason::InvalidPrice.as_u16(), 7);
        assert_eq!(RejectReason::InvalidQuantity.as_u16(), 8);
        assert_eq!(RejectReason::InvalidPriceLevel.as_u16(), 9);
        assert_eq!(RejectReason::OrderSizeOutOfRange.as_u16(), 10);
        assert_eq!(RejectReason::MissingUserId.as_u16(), 11);
        assert_eq!(RejectReason::DuplicateOrderId.as_u16(), 12);
        assert_eq!(RejectReason::InsufficientLiquidity.as_u16(), 13);
    }

    #[test]
    fn test_other_passthrough() {
        assert_eq!(RejectReason::Other(0).as_u16(), 0);
        assert_eq!(RejectReason::Other(7777).as_u16(), 7777);
        assert_eq!(RejectReason::Other(u16::MAX).as_u16(), u16::MAX);
    }

    #[test]
    fn test_display_reads_human_text() {
        // Smoke check that every variant produces a non-empty,
        // human-readable line.
        for reason in named_variants() {
            let text = reason.to_string();
            assert!(!text.is_empty(), "Display for {reason:?} produced empty");
        }
        assert_eq!(
            RejectReason::KillSwitchActive.to_string(),
            "kill switch active"
        );
        assert_eq!(RejectReason::Other(42).to_string(), "other(42)");
    }

    #[test]
    fn test_from_order_book_error_kill_switch_maps_to_kill_switch_active() {
        let err = OrderBookError::KillSwitchActive;
        assert_eq!(RejectReason::from(&err), RejectReason::KillSwitchActive);
    }

    #[test]
    fn test_from_order_book_error_risk_max_open_maps_to_risk_max_open_orders() {
        let err = OrderBookError::RiskMaxOpenOrders {
            account: Hash32::from([1u8; 32]),
            current: 5,
            limit: 5,
        };
        assert_eq!(RejectReason::from(&err), RejectReason::RiskMaxOpenOrders);
    }

    #[test]
    fn test_from_order_book_error_risk_max_notional() {
        let err = OrderBookError::RiskMaxNotional {
            account: Hash32::from([1u8; 32]),
            current: 100,
            attempted: 50,
            limit: 100,
        };
        assert_eq!(RejectReason::from(&err), RejectReason::RiskMaxNotional);
    }

    #[test]
    fn test_from_order_book_error_risk_price_band() {
        let err = OrderBookError::RiskPriceBand {
            submitted: 1_000_000,
            reference: 500_000,
            deviation_bps: 10_000,
            limit_bps: 100,
        };
        assert_eq!(RejectReason::from(&err), RejectReason::RiskPriceBand);
    }

    #[test]
    fn test_from_order_book_error_invalid_price_level_maps_to_invalid_price_level() {
        let err = OrderBookError::InvalidPriceLevel(42);
        assert_eq!(RejectReason::from(&err), RejectReason::InvalidPriceLevel);
    }

    #[test]
    fn test_from_order_book_error_order_size_out_of_range() {
        let err = OrderBookError::OrderSizeOutOfRange {
            quantity: 0,
            min: Some(1),
            max: Some(100),
        };
        assert_eq!(RejectReason::from(&err), RejectReason::OrderSizeOutOfRange);
    }

    #[test]
    fn test_from_order_book_error_missing_user_id() {
        let err = OrderBookError::MissingUserId {
            order_id: Id::new_uuid(),
        };
        assert_eq!(RejectReason::from(&err), RejectReason::MissingUserId);
    }

    #[test]
    fn test_from_order_book_error_self_trade_prevented_maps_to_self_trade_prevention() {
        let err = OrderBookError::SelfTradePrevented {
            mode: crate::orderbook::stp::STPMode::CancelTaker,
            taker_order_id: Id::new_uuid(),
            user_id: Hash32::from([1u8; 32]),
        };
        assert_eq!(RejectReason::from(&err), RejectReason::SelfTradePrevention);
    }

    #[test]
    fn test_from_order_book_error_price_crossing_maps_to_post_only_would_cross() {
        let err = OrderBookError::PriceCrossing {
            price: 100,
            side: Side::Buy,
            opposite_price: 99,
        };
        assert_eq!(RejectReason::from(&err), RejectReason::PostOnlyWouldCross);
    }

    #[test]
    fn test_from_order_book_error_invalid_tick_size_maps_to_invalid_price() {
        let err = OrderBookError::InvalidTickSize {
            price: 150,
            tick_size: 100,
        };
        assert_eq!(RejectReason::from(&err), RejectReason::InvalidPrice);
    }

    #[test]
    fn test_from_order_book_error_invalid_lot_size_maps_to_invalid_quantity() {
        let err = OrderBookError::InvalidLotSize {
            quantity: 75,
            lot_size: 10,
        };
        assert_eq!(RejectReason::from(&err), RejectReason::InvalidQuantity);
    }

    #[test]
    fn test_from_order_book_error_insufficient_liquidity() {
        let err = OrderBookError::InsufficientLiquidity {
            side: Side::Buy,
            requested: 100,
            available: 50,
        };
        assert_eq!(
            RejectReason::from(&err),
            RejectReason::InsufficientLiquidity
        );
    }

    #[test]
    fn test_from_order_book_error_serialization_error_maps_to_other_zero() {
        let err = OrderBookError::SerializationError {
            message: "oops".to_string(),
        };
        assert_eq!(RejectReason::from(&err), RejectReason::Other(0));
    }

    #[test]
    fn test_from_order_book_error_internal_state_errors_map_to_other_zero() {
        let cases = [
            OrderBookError::OrderNotFound("x".to_string()),
            OrderBookError::InvalidOperation {
                message: "nope".to_string(),
            },
            OrderBookError::DeserializationError {
                message: "bad".to_string(),
            },
            OrderBookError::ChecksumMismatch {
                expected: "a".to_string(),
                actual: "b".to_string(),
            },
            OrderBookError::PriceLevelError(PriceLevelError::InvalidFormat),
        ];
        for err in cases {
            assert_eq!(
                RejectReason::from(&err),
                RejectReason::Other(0),
                "{err:?} should map to Other(0)"
            );
        }
    }

    #[test]
    fn test_serde_json_roundtrip_each_variant() {
        for reason in named_variants() {
            let json = serde_json::to_string(&reason).expect("serialize named variant");
            let decoded: RejectReason =
                serde_json::from_str(&json).expect("deserialize named variant");
            assert_eq!(decoded, reason);
        }
        let other = RejectReason::Other(42);
        let json = serde_json::to_string(&other).expect("serialize Other(42)");
        let decoded: RejectReason = serde_json::from_str(&json).expect("deserialize Other(42)");
        assert_eq!(decoded, other);
    }

    #[test]
    fn test_serde_json_emits_stable_u16_wire_code() {
        // Wire format must be the documented u16 code, not a variant
        // name or a serde-derived index. This is the contract consumers
        // rely on across `0.7.x` patch upgrades.
        for reason in named_variants() {
            let json = serde_json::to_string(&reason).expect("serialize named variant");
            assert_eq!(
                json,
                reason.as_u16().to_string(),
                "JSON wire code drift for {reason:?}"
            );
        }
        let other = RejectReason::Other(7777);
        let json = serde_json::to_string(&other).expect("serialize Other");
        assert_eq!(json, "7777");
    }

    #[test]
    fn test_serde_json_unknown_code_decodes_to_other() {
        // Forward-compat: an older deserializer reading a payload
        // minted by a newer producer with a code outside the documented
        // table preserves it via `RejectReason::Other(code)` instead of
        // failing to deserialize.
        let decoded: RejectReason = serde_json::from_str("999").expect("deserialize unknown code");
        assert_eq!(decoded, RejectReason::Other(999));

        // Reserved-application range round-trips too.
        let decoded: RejectReason =
            serde_json::from_str("1234").expect("deserialize reserved-range code");
        assert_eq!(decoded, RejectReason::Other(1234));
    }

    #[cfg(feature = "bincode")]
    #[test]
    fn test_serde_bincode_roundtrip_each_variant() {
        let cfg = bincode::config::standard();
        for reason in named_variants() {
            let bytes = bincode::serde::encode_to_vec(reason, cfg).expect("encode named variant");
            let (decoded, n) = bincode::serde::decode_from_slice::<RejectReason, _>(&bytes, cfg)
                .expect("decode named variant");
            assert_eq!(decoded, reason);
            assert_eq!(n, bytes.len(), "bincode should consume entire payload");
        }
        let other = RejectReason::Other(42);
        let bytes = bincode::serde::encode_to_vec(other, cfg).expect("encode Other(42)");
        let (decoded, n) = bincode::serde::decode_from_slice::<RejectReason, _>(&bytes, cfg)
            .expect("decode Other(42)");
        assert_eq!(decoded, other);
        assert_eq!(n, bytes.len());
    }
}