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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! Order book error types
use pricelevel::{Hash32, PriceLevelError, Side};
use std::fmt;
/// Errors that can occur within the OrderBook
#[derive(Debug)]
#[non_exhaustive]
pub enum OrderBookError {
/// Error from underlying price level operations
PriceLevelError(PriceLevelError),
/// Order not found in the book
OrderNotFound(String),
/// Invalid price level
InvalidPriceLevel(u128),
/// Price crossing (bid >= ask)
PriceCrossing {
/// Price that would cause crossing
price: u128,
/// Side of the order
side: Side,
/// Best opposite price
opposite_price: u128,
},
/// Insufficient liquidity for market order
InsufficientLiquidity {
/// The side of the market order
side: Side,
/// Quantity requested
requested: u64,
/// Quantity available
available: u64,
},
/// Operation not permitted for specified order type
InvalidOperation {
/// Description of the error
message: String,
},
/// New flow (submit / modify / replace) is rejected because the
/// kill switch is engaged. Cancel and mass-cancel paths still
/// operate so operators can drain the book in an orderly way.
KillSwitchActive,
/// Error while serializing snapshot data
SerializationError {
/// Underlying error message
message: String,
},
/// Error while deserializing snapshot data
DeserializationError {
/// Underlying error message
message: String,
},
/// Snapshot integrity check failed
ChecksumMismatch {
/// Expected checksum value
expected: String,
/// Actual checksum value
actual: String,
},
/// Order price is not a multiple of the configured tick size
InvalidTickSize {
/// The order price that failed validation
price: u128,
/// The configured tick size
tick_size: u128,
},
/// Order quantity is not a multiple of the configured lot size
InvalidLotSize {
/// The order quantity that failed validation
quantity: u64,
/// The configured lot size
lot_size: u64,
},
/// Order quantity is outside the allowed min/max range
OrderSizeOutOfRange {
/// The order quantity that failed validation
quantity: u64,
/// The configured minimum order size, if any
min: Option<u64>,
/// The configured maximum order size, if any
max: Option<u64>,
},
/// Order rejected because `user_id` is `Hash32::zero()` while
/// Self-Trade Prevention is enabled. All orders must carry a non-zero
/// `user_id` when STP mode is active.
MissingUserId {
/// The order ID that was rejected
order_id: pricelevel::Id,
},
/// Self-trade prevention triggered: the incoming order would have
/// matched against a resting order from the same user.
SelfTradePrevented {
/// The STP mode that was active
mode: crate::orderbook::stp::STPMode,
/// The taker (incoming) order ID
taker_order_id: pricelevel::Id,
/// The user ID that triggered the STP check
user_id: pricelevel::Hash32,
},
/// Per-account open-order limit breached.
///
/// Returned by limit-order admission when the requesting account
/// already has `current` resting orders and the configured ceiling
/// is `limit`. `current >= limit` always holds when this variant
/// is constructed.
RiskMaxOpenOrders {
/// Account that breached the limit.
account: Hash32,
/// Account's current resting-order count at check time.
current: u64,
/// Configured maximum.
limit: u64,
},
/// Per-account notional limit would be breached by this admission.
///
/// `current + attempted > limit` always holds when this variant
/// is constructed. `attempted` is computed as
/// `submitted_quantity * submitted_price`.
RiskMaxNotional {
/// Account that breached the limit.
account: Hash32,
/// Account's current resting notional at check time (raw ticks).
current: u128,
/// Notional this submission would add (raw ticks).
attempted: u128,
/// Configured maximum (raw ticks).
limit: u128,
},
/// Submitted price exceeds the configured price band against the
/// reference price.
///
/// `deviation_bps > limit_bps` always holds when this variant is
/// constructed.
RiskPriceBand {
/// Limit price submitted by the caller (raw ticks).
submitted: u128,
/// Resolved reference price at check time (raw ticks).
reference: u128,
/// Computed deviation in basis points. Saturates at `u32::MAX`.
deviation_bps: u32,
/// Configured maximum allowed deviation in basis points.
limit_bps: u32,
},
/// Failed to publish a trade event to NATS JetStream.
#[cfg(feature = "nats")]
NatsPublishError {
/// Description of the publish failure
message: String,
},
/// Failed to serialize a trade event for NATS publishing.
#[cfg(feature = "nats")]
NatsSerializationError {
/// Description of the serialization failure
message: String,
},
}
impl fmt::Display for OrderBookError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OrderBookError::PriceLevelError(err) => write!(f, "Price level error: {err}"),
OrderBookError::OrderNotFound(id) => write!(f, "Order not found: {id}"),
OrderBookError::InvalidPriceLevel(price) => write!(f, "Invalid price level: {price}"),
OrderBookError::PriceCrossing {
price,
side,
opposite_price,
} => {
write!(
f,
"Price crossing: {side} {price} would cross opposite at {opposite_price}"
)
}
OrderBookError::InsufficientLiquidity {
side,
requested,
available,
} => {
write!(
f,
"Insufficient liquidity for {side} order: requested {requested}, available {available}"
)
}
OrderBookError::InvalidOperation { message } => {
write!(f, "Invalid operation: {message}")
}
OrderBookError::KillSwitchActive => {
write!(
f,
"kill switch active: new order entry and modifications are halted"
)
}
OrderBookError::SerializationError { message } => {
write!(f, "Serialization error: {message}")
}
OrderBookError::DeserializationError { message } => {
write!(f, "Deserialization error: {message}")
}
OrderBookError::ChecksumMismatch { expected, actual } => {
write!(
f,
"Checksum mismatch: expected {expected}, but computed {actual}"
)
}
OrderBookError::InvalidTickSize { price, tick_size } => {
write!(
f,
"invalid tick size: price {price} is not a multiple of tick size {tick_size}"
)
}
OrderBookError::InvalidLotSize { quantity, lot_size } => {
write!(
f,
"invalid lot size: quantity {quantity} is not a multiple of lot size {lot_size}"
)
}
OrderBookError::OrderSizeOutOfRange { quantity, min, max } => {
write!(
f,
"order size out of range: quantity {quantity}, min {min:?}, max {max:?}"
)
}
OrderBookError::MissingUserId { order_id } => {
write!(
f,
"missing user_id: order {order_id} rejected because STP is enabled and user_id is zero"
)
}
OrderBookError::SelfTradePrevented {
mode,
taker_order_id,
user_id,
} => {
write!(
f,
"self-trade prevented ({mode}): taker {taker_order_id}, user {user_id}"
)
}
OrderBookError::RiskMaxOpenOrders {
account,
current,
limit,
} => {
write!(
f,
"risk: account {account} has {current} open orders (limit {limit})"
)
}
OrderBookError::RiskMaxNotional {
account,
current,
attempted,
limit,
} => {
write!(
f,
"risk: account {account} notional {current} + attempted {attempted} would exceed limit {limit}"
)
}
OrderBookError::RiskPriceBand {
submitted,
reference,
deviation_bps,
limit_bps,
} => {
write!(
f,
"risk: submitted price {submitted} deviates {deviation_bps} bps from reference {reference} (limit {limit_bps} bps)"
)
}
#[cfg(feature = "nats")]
OrderBookError::NatsPublishError { message } => {
write!(f, "nats publish error: {message}")
}
#[cfg(feature = "nats")]
OrderBookError::NatsSerializationError { message } => {
write!(f, "nats serialization error: {message}")
}
}
}
}
impl std::error::Error for OrderBookError {}
impl From<PriceLevelError> for OrderBookError {
fn from(err: PriceLevelError) -> Self {
OrderBookError::PriceLevelError(err)
}
}
impl Clone for OrderBookError {
fn clone(&self) -> Self {
match self {
OrderBookError::PriceLevelError(err) => {
// PriceLevelError doesn't implement Clone, so we manually clone each variant
let cloned_err = match err {
PriceLevelError::ParseError { message } => PriceLevelError::ParseError {
message: message.clone(),
},
PriceLevelError::InvalidFormat => PriceLevelError::InvalidFormat,
PriceLevelError::UnknownOrderType(s) => {
PriceLevelError::UnknownOrderType(s.clone())
}
PriceLevelError::MissingField(s) => PriceLevelError::MissingField(s.clone()),
PriceLevelError::InvalidFieldValue { field, value } => {
PriceLevelError::InvalidFieldValue {
field: field.clone(),
value: value.clone(),
}
}
PriceLevelError::InvalidOperation { message } => {
PriceLevelError::InvalidOperation {
message: message.clone(),
}
}
PriceLevelError::SerializationError { message } => {
PriceLevelError::SerializationError {
message: message.clone(),
}
}
PriceLevelError::DeserializationError { message } => {
PriceLevelError::DeserializationError {
message: message.clone(),
}
}
PriceLevelError::ChecksumMismatch { expected, actual } => {
PriceLevelError::ChecksumMismatch {
expected: expected.clone(),
actual: actual.clone(),
}
}
};
OrderBookError::PriceLevelError(cloned_err)
}
OrderBookError::OrderNotFound(s) => OrderBookError::OrderNotFound(s.clone()),
OrderBookError::InvalidPriceLevel(p) => OrderBookError::InvalidPriceLevel(*p),
OrderBookError::PriceCrossing {
price,
side,
opposite_price,
} => OrderBookError::PriceCrossing {
price: *price,
side: *side,
opposite_price: *opposite_price,
},
OrderBookError::InsufficientLiquidity {
side,
requested,
available,
} => OrderBookError::InsufficientLiquidity {
side: *side,
requested: *requested,
available: *available,
},
OrderBookError::InvalidOperation { message } => OrderBookError::InvalidOperation {
message: message.clone(),
},
OrderBookError::KillSwitchActive => OrderBookError::KillSwitchActive,
OrderBookError::SerializationError { message } => OrderBookError::SerializationError {
message: message.clone(),
},
OrderBookError::DeserializationError { message } => {
OrderBookError::DeserializationError {
message: message.clone(),
}
}
OrderBookError::ChecksumMismatch { expected, actual } => {
OrderBookError::ChecksumMismatch {
expected: expected.clone(),
actual: actual.clone(),
}
}
OrderBookError::InvalidTickSize { price, tick_size } => {
OrderBookError::InvalidTickSize {
price: *price,
tick_size: *tick_size,
}
}
OrderBookError::InvalidLotSize { quantity, lot_size } => {
OrderBookError::InvalidLotSize {
quantity: *quantity,
lot_size: *lot_size,
}
}
OrderBookError::OrderSizeOutOfRange { quantity, min, max } => {
OrderBookError::OrderSizeOutOfRange {
quantity: *quantity,
min: *min,
max: *max,
}
}
OrderBookError::MissingUserId { order_id } => OrderBookError::MissingUserId {
order_id: *order_id,
},
OrderBookError::SelfTradePrevented {
mode,
taker_order_id,
user_id,
} => OrderBookError::SelfTradePrevented {
mode: *mode,
taker_order_id: *taker_order_id,
user_id: *user_id,
},
OrderBookError::RiskMaxOpenOrders {
account,
current,
limit,
} => OrderBookError::RiskMaxOpenOrders {
account: *account,
current: *current,
limit: *limit,
},
OrderBookError::RiskMaxNotional {
account,
current,
attempted,
limit,
} => OrderBookError::RiskMaxNotional {
account: *account,
current: *current,
attempted: *attempted,
limit: *limit,
},
OrderBookError::RiskPriceBand {
submitted,
reference,
deviation_bps,
limit_bps,
} => OrderBookError::RiskPriceBand {
submitted: *submitted,
reference: *reference,
deviation_bps: *deviation_bps,
limit_bps: *limit_bps,
},
#[cfg(feature = "nats")]
OrderBookError::NatsPublishError { message } => OrderBookError::NatsPublishError {
message: message.clone(),
},
#[cfg(feature = "nats")]
OrderBookError::NatsSerializationError { message } => {
OrderBookError::NatsSerializationError {
message: message.clone(),
}
}
}
}
}
/// Errors that can occur in BookManager operations
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ManagerError {
/// Trade processor has already been started
ProcessorAlreadyStarted,
}
impl fmt::Display for ManagerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ManagerError::ProcessorAlreadyStarted => {
write!(f, "trade processor already started")
}
}
}
}
impl std::error::Error for ManagerError {}
#[cfg(test)]
mod tests {
use super::*;
use pricelevel::{Hash32, Id};
#[test]
fn test_clone_order_not_found() {
let error = OrderBookError::OrderNotFound("order123".to_string());
let cloned = error.clone();
assert!(matches!(cloned, OrderBookError::OrderNotFound(ref s) if s == "order123"));
}
#[test]
fn test_clone_invalid_price_level() {
let error = OrderBookError::InvalidPriceLevel(12345);
let cloned = error.clone();
assert!(matches!(cloned, OrderBookError::InvalidPriceLevel(12345)));
}
#[test]
fn test_clone_price_crossing() {
let error = OrderBookError::PriceCrossing {
price: 100,
side: Side::Buy,
opposite_price: 99,
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::PriceCrossing {
price: 100,
side: Side::Buy,
opposite_price: 99
}
));
}
#[test]
fn test_clone_insufficient_liquidity() {
let error = OrderBookError::InsufficientLiquidity {
side: Side::Sell,
requested: 1000,
available: 500,
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::InsufficientLiquidity {
side: Side::Sell,
requested: 1000,
available: 500
}
));
}
#[test]
fn test_clone_invalid_operation() {
let error = OrderBookError::InvalidOperation {
message: "Cannot cancel filled order".to_string(),
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::InvalidOperation { ref message } if message == "Cannot cancel filled order"
));
}
#[test]
fn test_clone_serialization_error() {
let error = OrderBookError::SerializationError {
message: "Failed to serialize".to_string(),
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::SerializationError { ref message } if message == "Failed to serialize"
));
}
#[test]
fn test_clone_checksum_mismatch() {
let error = OrderBookError::ChecksumMismatch {
expected: "abc123".to_string(),
actual: "def456".to_string(),
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::ChecksumMismatch { ref expected, ref actual }
if expected == "abc123" && actual == "def456"
));
}
#[test]
fn test_clone_invalid_tick_size() {
let error = OrderBookError::InvalidTickSize {
price: 10050,
tick_size: 100,
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::InvalidTickSize {
price: 10050,
tick_size: 100
}
));
}
#[test]
fn test_clone_invalid_lot_size() {
let error = OrderBookError::InvalidLotSize {
quantity: 75,
lot_size: 10,
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::InvalidLotSize {
quantity: 75,
lot_size: 10
}
));
}
#[test]
fn test_clone_order_size_out_of_range() {
let error = OrderBookError::OrderSizeOutOfRange {
quantity: 5,
min: Some(10),
max: Some(1000),
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::OrderSizeOutOfRange {
quantity: 5,
min: Some(10),
max: Some(1000)
}
));
}
#[test]
fn test_clone_missing_user_id() {
let order_id = Id::new_uuid();
let error = OrderBookError::MissingUserId { order_id };
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::MissingUserId { order_id: id } if id == order_id
));
}
#[test]
fn test_clone_self_trade_prevented() {
let taker_id = Id::new_uuid();
let user_id = Hash32::from([1u8; 32]);
let error = OrderBookError::SelfTradePrevented {
mode: crate::orderbook::stp::STPMode::CancelMaker,
taker_order_id: taker_id,
user_id,
};
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::SelfTradePrevented {
mode: crate::orderbook::stp::STPMode::CancelMaker,
taker_order_id: id,
user_id: uid
} if id == taker_id && uid == user_id
));
}
#[test]
fn test_clone_price_level_error_parse_error() {
let price_level_err = PriceLevelError::ParseError {
message: "Parse failed".to_string(),
};
let error = OrderBookError::PriceLevelError(price_level_err);
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::PriceLevelError(PriceLevelError::ParseError { ref message })
if message == "Parse failed"
));
}
#[test]
fn test_clone_price_level_error_invalid_format() {
let price_level_err = PriceLevelError::InvalidFormat;
let error = OrderBookError::PriceLevelError(price_level_err);
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::PriceLevelError(PriceLevelError::InvalidFormat)
));
}
#[test]
fn test_clone_price_level_error_unknown_order_type() {
let price_level_err = PriceLevelError::UnknownOrderType("CUSTOM".to_string());
let error = OrderBookError::PriceLevelError(price_level_err);
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::PriceLevelError(PriceLevelError::UnknownOrderType(ref s))
if s == "CUSTOM"
));
}
#[test]
fn test_clone_price_level_error_checksum_mismatch() {
let price_level_err = PriceLevelError::ChecksumMismatch {
expected: "hash1".to_string(),
actual: "hash2".to_string(),
};
let error = OrderBookError::PriceLevelError(price_level_err);
let cloned = error.clone();
assert!(matches!(
cloned,
OrderBookError::PriceLevelError(PriceLevelError::ChecksumMismatch {
ref expected,
ref actual
}) if expected == "hash1" && actual == "hash2"
));
}
}