nautilus-model 0.59.0

Domain model for the Nautilus trading engine
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
716
717
718
719
720
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Standardized reasons for local order denial.
//!
//! [`OrderDeniedReason`] is the single source of truth for the `CATEGORY_CONDITION` codes
//! attached to [`OrderDenied`](super::denied::OrderDenied) events. Each variant renders, via
//! [`std::fmt::Display`], to a message whose leading token is the stable code followed by
//! `key=value` context. The companion [`OrderDeniedCode`] enum (generated by `strum`) enumerates
//! the codes without their per-denial context, so documentation and grouping can iterate the
//! closed set.

use rust_decimal::Decimal;
use strum::{AsRefStr, Display, EnumDiscriminants, EnumIter, EnumString};
use thiserror::Error;

use crate::{
    enums::{OrderSide, OrderType, TimeInForce, TrailingOffsetType},
    identifiers::{ClientId, InstrumentId, OrderListId, PositionId, Venue},
    types::{Money, Quantity},
};

/// A standardized reason an order was denied locally by the Nautilus system.
///
/// A denial is a local rejection: the order never reached a venue. Each variant carries the
/// context needed to render its message and maps to a stable [`OrderDeniedCode`].
#[derive(Debug, Clone, PartialEq, Eq, Error, EnumDiscriminants)]
#[strum_discriminants(
    name(OrderDeniedCode),
    derive(Display, AsRefStr, EnumIter, EnumString),
    strum(serialize_all = "SCREAMING_SNAKE_CASE")
)]
pub enum OrderDeniedReason {
    /// The effective order quantity exceeds the instrument maximum.
    #[error(
        "QUANTITY_EXCEEDS_MAXIMUM: effective_quantity={effective_quantity}, max_quantity={max_quantity}"
    )]
    QuantityExceedsMaximum {
        /// The order quantity after any quote-to-base conversion.
        effective_quantity: Quantity,
        /// The instrument's maximum tradable quantity.
        max_quantity: Quantity,
    },
    /// The effective order quantity is below the instrument minimum.
    #[error(
        "QUANTITY_BELOW_MINIMUM: effective_quantity={effective_quantity}, min_quantity={min_quantity}"
    )]
    QuantityBelowMinimum {
        /// The order quantity after any quote-to-base conversion.
        effective_quantity: Quantity,
        /// The instrument's minimum tradable quantity.
        min_quantity: Quantity,
    },
    /// The order notional exceeds the configured maximum per order.
    #[error("NOTIONAL_EXCEEDS_MAX_PER_ORDER: max_notional={max_notional:?}, notional={notional:?}")]
    NotionalExceedsMaxPerOrder {
        /// The configured maximum notional per order.
        max_notional: Money,
        /// The order's notional value.
        notional: Money,
    },
    /// The order notional exceeds the instrument maximum.
    #[error("NOTIONAL_EXCEEDS_MAXIMUM: max_notional={max_notional:?}, notional={notional:?}")]
    NotionalExceedsMaximum {
        /// The instrument's maximum notional.
        max_notional: Money,
        /// The order's notional value.
        notional: Money,
    },
    /// The order notional is below the instrument minimum.
    #[error("NOTIONAL_BELOW_MINIMUM: min_notional={min_notional:?}, notional={notional:?}")]
    NotionalBelowMinimum {
        /// The instrument's minimum notional.
        min_notional: Money,
        /// The order's notional value.
        notional: Money,
    },
    /// The order notional exceeds the account free balance.
    #[error("NOTIONAL_EXCEEDS_FREE_BALANCE: free={free:?}, notional={notional:?}")]
    NotionalExceedsFreeBalance {
        /// The account's free balance.
        free: Money,
        /// The order's notional value.
        notional: Money,
    },
    /// The cumulative order notional exceeds the account free balance.
    #[error("CUM_NOTIONAL_EXCEEDS_FREE_BALANCE: free={free}, cum_notional={cum_notional}")]
    CumNotionalExceedsFreeBalance {
        /// The account's free balance.
        free: Money,
        /// The cumulative notional across the checked orders.
        cum_notional: Money,
    },
    /// The order initial margin exceeds the account free balance.
    #[error("MARGIN_EXCEEDS_FREE_BALANCE: free={free}, margin_required={margin_required}")]
    MarginExceedsFreeBalance {
        /// The account's free balance.
        free: Money,
        /// The initial margin required for the order.
        margin_required: Money,
    },
    /// The cumulative initial margin exceeds the account free balance.
    #[error("CUM_MARGIN_EXCEEDS_FREE_BALANCE: free={free}, cum_margin={cum_margin}")]
    CumMarginExceedsFreeBalance {
        /// The account's free balance.
        free: Money,
        /// The cumulative initial margin across the checked orders.
        cum_margin: Money,
    },
    /// The configured maximum notional per order is invalid.
    #[error("INVALID_MAX_NOTIONAL_PER_ORDER: instrument_id={instrument_id}, value={value}")]
    InvalidMaxNotionalPerOrder {
        /// The instrument the setting applies to.
        instrument_id: InstrumentId,
        /// The invalid configured value.
        value: Decimal,
    },
    /// The order side is invalid for this operation.
    #[error("INVALID_ORDER_SIDE: {order_side}")]
    InvalidOrderSide {
        /// The offending order side.
        order_side: OrderSide,
    },
    /// A GTD order is missing its expire time.
    #[error("MISSING_EXPIRE_TIME")]
    MissingExpireTime,
    /// The order's expire time is in the past.
    #[error("EXPIRE_TIME_IN_PAST: expire_time={expire_time}")]
    ExpireTimeInPast {
        /// The expire time that has already elapsed.
        expire_time: String,
    },
    /// The order is missing a required trigger type.
    #[error("MISSING_TRIGGER_TYPE")]
    MissingTriggerType,
    /// The order is missing a required trailing offset.
    #[error("MISSING_TRAILING_OFFSET")]
    MissingTrailingOffset,
    /// The order is missing a required trailing offset type.
    #[error("MISSING_TRAILING_OFFSET_TYPE")]
    MissingTrailingOffsetType,
    /// The order's trailing offset type is not supported.
    #[error("UNSUPPORTED_TRAILING_OFFSET_TYPE: {offset_type:?}")]
    UnsupportedTrailingOffsetType {
        /// The unsupported trailing offset type.
        offset_type: TrailingOffsetType,
    },
    /// The trailing stop trigger price could not be calculated.
    #[error("TRAILING_STOP_CALC_FAILED: {detail}")]
    TrailingStopCalcFailed {
        /// The underlying calculation error.
        detail: String,
    },
    /// The order quantity could not be converted for risk checks.
    #[error("QUANTITY_CONVERSION_FAILED: {detail}")]
    QuantityConversionFailed {
        /// The underlying conversion error.
        detail: String,
    },
    /// The instrument was not found in the cache.
    #[error("INSTRUMENT_NOT_FOUND: instrument_id={instrument_id}")]
    InstrumentNotFound {
        /// The instrument that was not found.
        instrument_id: InstrumentId,
    },
    /// The position for a reduce-only order was not found.
    #[error("POSITION_NOT_FOUND: position_id={position_id}")]
    PositionNotFound {
        /// The position that was not found.
        position_id: PositionId,
    },
    /// A reduce-only order would increase the position.
    #[error("REDUCE_ONLY_WOULD_INCREASE_POSITION: position_id={position_id}")]
    ReduceOnlyWouldIncreasePosition {
        /// The position the order would increase.
        position_id: PositionId,
    },
    /// The order list is missing orders in the cache.
    #[error("ORDER_LIST_INCOMPLETE: order_list_id={order_list_id}")]
    OrderListIncomplete {
        /// The order list with missing orders.
        order_list_id: OrderListId,
    },
    /// The order was denied because its order list failed risk checks.
    #[error("ORDER_LIST_DENIED: order_list_id={order_list_id}")]
    OrderListDenied {
        /// The order list that failed risk checks.
        order_list_id: OrderListId,
    },
    /// Trading is halted; new orders are denied.
    #[error("TRADING_HALTED")]
    TradingHalted,
    /// Trading is reducing; the order would increase exposure.
    #[error("TRADING_STATE_REDUCING: order_side={order_side}, instrument_id={instrument_id}")]
    TradingStateReducing {
        /// The side of the order that would increase exposure.
        order_side: OrderSide,
        /// The instrument the order applies to.
        instrument_id: InstrumentId,
    },
    /// The order submission rate limit was exceeded.
    #[error("RATE_LIMIT_EXCEEDED")]
    RateLimitExceeded,
    /// No execution client was found for the routed command.
    #[error("NO_EXECUTION_CLIENT: client_id={client_id:?}, routing_context={routing_context}")]
    NoExecutionClient {
        /// The explicitly requested client, if one was supplied.
        client_id: Option<ClientId>,
        /// The routing context used to look up an execution client.
        routing_context: String,
    },
    /// The execution client does not handle the order venue.
    #[error(
        "CLIENT_VENUE_MISMATCH: client_id={client_id}, order_venue={order_venue}, client_venue={client_venue}"
    )]
    ClientVenueMismatch {
        /// The routed execution client.
        client_id: ClientId,
        /// The order venue.
        order_venue: Venue,
        /// The execution client's venue.
        client_venue: Venue,
    },
    /// Submitting the order to the execution client failed.
    #[error("SUBMIT_FAILED: {detail}")]
    SubmitFailed {
        /// The underlying submission error.
        detail: String,
    },
    /// The supplied position ID is invalid for the order submission.
    #[error("INVALID_POSITION_ID: position_id={position_id}, detail={detail}")]
    InvalidPositionId {
        /// The invalid position ID.
        position_id: PositionId,
        /// The validation failure detail.
        detail: String,
    },
    /// The order's time in force is not supported.
    #[error("UNSUPPORTED_TIME_IN_FORCE: {0}")]
    UnsupportedTimeInForce(TimeInForce),
    /// The client order ID is invalid for the venue.
    #[error("INVALID_CLIENT_ORDER_ID: {detail}")]
    InvalidClientOrderId {
        /// The validation failure detail.
        detail: String,
    },
    /// The venue does not support the requested order list.
    #[error("UNSUPPORTED_ORDER_LIST: {detail}")]
    UnsupportedOrderList {
        /// The reason the order list is unsupported.
        detail: String,
    },
    /// The order type is not supported by the venue.
    #[error("UNSUPPORTED_ORDER_TYPE: {order_type}")]
    UnsupportedOrderType {
        /// The unsupported order type.
        order_type: OrderType,
    },
    /// The venue does not support the requested take-profit/stop-loss parameters.
    #[error("UNSUPPORTED_TP_SL: {detail}")]
    UnsupportedTpSl {
        /// The reason the take-profit/stop-loss parameters are unsupported.
        detail: String,
    },
    /// The order failed adapter validation before submission.
    #[error("VALIDATION_FAILED: {detail}")]
    ValidationFailed {
        /// The validation failure detail.
        detail: String,
    },
    /// A post-reconnect stream reconciliation is in progress; retry once it completes.
    #[error(
        "STREAM_RECONCILING: post-reconnect reconciliation in progress, retry once it completes"
    )]
    StreamReconciling,
}

impl OrderDeniedCode {
    /// Returns a one-line description of this denial code.
    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            Self::QuantityExceedsMaximum => {
                "The effective order quantity exceeds the instrument maximum."
            }
            Self::QuantityBelowMinimum => {
                "The effective order quantity is below the instrument minimum."
            }
            Self::NotionalExceedsMaxPerOrder => {
                "The order notional exceeds the configured maximum per order."
            }
            Self::NotionalExceedsMaximum => "The order notional exceeds the instrument maximum.",
            Self::NotionalBelowMinimum => "The order notional is below the instrument minimum.",
            Self::NotionalExceedsFreeBalance => {
                "The order notional exceeds the account free balance."
            }
            Self::CumNotionalExceedsFreeBalance => {
                "The cumulative order notional exceeds the account free balance."
            }
            Self::MarginExceedsFreeBalance => {
                "The order initial margin exceeds the account free balance."
            }
            Self::CumMarginExceedsFreeBalance => {
                "The cumulative initial margin exceeds the account free balance."
            }
            Self::InvalidMaxNotionalPerOrder => {
                "The configured maximum notional per order is invalid."
            }
            Self::InvalidOrderSide => "The order side is invalid for this operation.",
            Self::MissingExpireTime => "A GTD order is missing its expire time.",
            Self::ExpireTimeInPast => "The order's expire time is in the past.",
            Self::MissingTriggerType => "The order is missing a required trigger type.",
            Self::MissingTrailingOffset => "The order is missing a required trailing offset.",
            Self::MissingTrailingOffsetType => {
                "The order is missing a required trailing offset type."
            }
            Self::UnsupportedTrailingOffsetType => {
                "The order's trailing offset type is not supported."
            }
            Self::TrailingStopCalcFailed => {
                "The trailing stop trigger price could not be calculated."
            }
            Self::QuantityConversionFailed => {
                "The order quantity could not be converted for risk checks."
            }
            Self::InstrumentNotFound => "The instrument was not found in the cache.",
            Self::PositionNotFound => "The position for a reduce‑only order was not found.",
            Self::ReduceOnlyWouldIncreasePosition => {
                "A reduce‑only order would increase the position."
            }
            Self::OrderListIncomplete => "The order list is missing orders in the cache.",
            Self::OrderListDenied => {
                "The order was denied because its order list failed risk checks."
            }
            Self::TradingHalted => "Trading is halted; new orders are denied.",
            Self::TradingStateReducing => "Trading is reducing; the order would increase exposure.",
            Self::RateLimitExceeded => "The order submission rate limit was exceeded.",
            Self::NoExecutionClient => "No execution client was found for the routed command.",
            Self::ClientVenueMismatch => "The execution client does not handle the order venue.",
            Self::SubmitFailed => "Submitting the order to the execution client failed.",
            Self::InvalidPositionId => {
                "The supplied position ID is invalid for the order submission."
            }
            Self::UnsupportedTimeInForce => "The order's time in force is not supported.",
            Self::InvalidClientOrderId => "The client order ID is invalid for the venue.",
            Self::UnsupportedOrderList => "The venue does not support the requested order list.",
            Self::UnsupportedOrderType => "The order type is not supported by the venue.",
            Self::UnsupportedTpSl => {
                "The venue does not support the requested take‑profit/stop‑loss parameters."
            }
            Self::ValidationFailed => "The order failed adapter validation before submission.",
            Self::StreamReconciling => {
                "A post‑reconnect stream reconciliation is in progress; retry once it completes."
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use strum::IntoEnumIterator;

    use super::*;

    const DOC_PATH: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../docs/concepts/execution.md"
    );
    const BLOCK_BEGIN: &str = "<!-- BEGIN GENERATED: order-denied-reasons -->";
    const BLOCK_END: &str = "<!-- END GENERATED: order-denied-reasons -->";

    #[rstest]
    fn renders_subject_led_messages() {
        let exceeds = OrderDeniedReason::QuantityExceedsMaximum {
            effective_quantity: Quantity::from("15"),
            max_quantity: Quantity::from("10"),
        };
        let below = OrderDeniedReason::QuantityBelowMinimum {
            effective_quantity: Quantity::from("1"),
            min_quantity: Quantity::from("5"),
        };
        let notional = OrderDeniedReason::NotionalBelowMinimum {
            min_notional: Money::from("1.00 USD"),
            notional: Money::from("0.90 USD"),
        };

        assert_eq!(
            exceeds.to_string(),
            "QUANTITY_EXCEEDS_MAXIMUM: effective_quantity=15, max_quantity=10"
        );
        assert_eq!(
            below.to_string(),
            "QUANTITY_BELOW_MINIMUM: effective_quantity=1, min_quantity=5"
        );
        assert_eq!(
            notional.to_string(),
            "NOTIONAL_BELOW_MINIMUM: min_notional=Money(1.00, USD), notional=Money(0.90, USD)"
        );
    }

    #[rstest]
    fn renders_lifecycle_and_state_messages() {
        let not_found = OrderDeniedReason::InstrumentNotFound {
            instrument_id: InstrumentId::from("AUD/USD.SIM"),
        };
        let bad_side = OrderDeniedReason::InvalidOrderSide {
            order_side: OrderSide::NoOrderSide,
        };
        let reducing = OrderDeniedReason::TradingStateReducing {
            order_side: OrderSide::Buy,
            instrument_id: InstrumentId::from("AUD/USD.SIM"),
        };

        assert_eq!(
            not_found.to_string(),
            "INSTRUMENT_NOT_FOUND: instrument_id=AUD/USD.SIM"
        );
        assert_eq!(bad_side.to_string(), "INVALID_ORDER_SIDE: NO_ORDER_SIDE");
        assert_eq!(
            OrderDeniedReason::TradingHalted.to_string(),
            "TRADING_HALTED"
        );
        assert_eq!(
            OrderDeniedReason::RateLimitExceeded.to_string(),
            "RATE_LIMIT_EXCEEDED"
        );
        assert_eq!(
            reducing.to_string(),
            "TRADING_STATE_REDUCING: order_side=BUY, instrument_id=AUD/USD.SIM"
        );
    }

    #[rstest]
    fn renders_routing_messages() {
        let missing_client = OrderDeniedReason::NoExecutionClient {
            client_id: Some(ClientId::from("SIM")),
            routing_context: "venue=SIM".to_string(),
        };
        let mismatch = OrderDeniedReason::ClientVenueMismatch {
            client_id: ClientId::from("IB"),
            order_venue: Venue::from("XCME"),
            client_venue: Venue::from("IB"),
        };
        let submit_failed = OrderDeniedReason::SubmitFailed {
            detail: "transport closed".to_string(),
        };
        let invalid_position_id = OrderDeniedReason::InvalidPositionId {
            position_id: PositionId::from("P-1"),
            detail: "not valid for NETTING OMS".to_string(),
        };

        assert_eq!(
            missing_client.to_string(),
            "NO_EXECUTION_CLIENT: client_id=Some(\"SIM\"), routing_context=venue=SIM"
        );
        assert_eq!(
            mismatch.to_string(),
            "CLIENT_VENUE_MISMATCH: client_id=IB, order_venue=XCME, client_venue=IB"
        );
        assert_eq!(submit_failed.to_string(), "SUBMIT_FAILED: transport closed");
        assert_eq!(
            invalid_position_id.to_string(),
            "INVALID_POSITION_ID: position_id=P-1, detail=not valid for NETTING OMS"
        );
    }

    #[rstest]
    fn renders_condition_led_message() {
        let reason = OrderDeniedReason::UnsupportedTimeInForce(TimeInForce::Gtd);
        assert_eq!(reason.to_string(), "UNSUPPORTED_TIME_IN_FORCE: GTD");
    }

    #[rstest]
    fn renders_adapter_messages() {
        let invalid_client_order_id = OrderDeniedReason::InvalidClientOrderId {
            detail: "clOrdId must be alphanumeric".to_string(),
        };
        let unsupported_order_list = OrderDeniedReason::UnsupportedOrderList {
            detail: "spread instruments are not supported in order lists".to_string(),
        };
        let unsupported_order_type = OrderDeniedReason::UnsupportedOrderType {
            order_type: OrderType::TrailingStopMarket,
        };
        let unsupported_tp_sl = OrderDeniedReason::UnsupportedTpSl {
            detail: "TP/SL trigger prices are not supported in demo mode".to_string(),
        };
        let validation_failed = OrderDeniedReason::ValidationFailed {
            detail: "`bbo_side_type` and `bbo_level` are only supported for linear products"
                .to_string(),
        };

        assert_eq!(
            invalid_client_order_id.to_string(),
            "INVALID_CLIENT_ORDER_ID: clOrdId must be alphanumeric"
        );
        assert_eq!(
            unsupported_order_list.to_string(),
            "UNSUPPORTED_ORDER_LIST: spread instruments are not supported in order lists"
        );
        assert_eq!(
            unsupported_order_type.to_string(),
            "UNSUPPORTED_ORDER_TYPE: TRAILING_STOP_MARKET"
        );
        assert_eq!(
            unsupported_tp_sl.to_string(),
            "UNSUPPORTED_TP_SL: TP/SL trigger prices are not supported in demo mode"
        );
        assert_eq!(
            validation_failed.to_string(),
            "VALIDATION_FAILED: `bbo_side_type` and `bbo_level` are only supported for linear products"
        );
        assert_eq!(
            OrderDeniedReason::StreamReconciling.to_string(),
            "STREAM_RECONCILING: post-reconnect reconciliation in progress, retry once it completes"
        );
    }

    // Drift pin: each variant's rendered message must start with its discriminant code, keeping
    // the hand-written `#[error]` prefix in sync with the strum-derived `OrderDeniedCode`.
    #[rstest]
    fn message_prefix_matches_code() {
        let usd = || Money::from("100.00 USD");
        let samples = [
            OrderDeniedReason::QuantityExceedsMaximum {
                effective_quantity: Quantity::from("15"),
                max_quantity: Quantity::from("10"),
            },
            OrderDeniedReason::QuantityBelowMinimum {
                effective_quantity: Quantity::from("1"),
                min_quantity: Quantity::from("5"),
            },
            OrderDeniedReason::NotionalExceedsMaxPerOrder {
                max_notional: usd(),
                notional: usd(),
            },
            OrderDeniedReason::NotionalExceedsMaximum {
                max_notional: usd(),
                notional: usd(),
            },
            OrderDeniedReason::NotionalBelowMinimum {
                min_notional: usd(),
                notional: usd(),
            },
            OrderDeniedReason::NotionalExceedsFreeBalance {
                free: usd(),
                notional: usd(),
            },
            OrderDeniedReason::CumNotionalExceedsFreeBalance {
                free: usd(),
                cum_notional: usd(),
            },
            OrderDeniedReason::MarginExceedsFreeBalance {
                free: usd(),
                margin_required: usd(),
            },
            OrderDeniedReason::CumMarginExceedsFreeBalance {
                free: usd(),
                cum_margin: usd(),
            },
            OrderDeniedReason::InvalidMaxNotionalPerOrder {
                instrument_id: InstrumentId::from("AUD/USD.SIM"),
                value: Decimal::ONE,
            },
            OrderDeniedReason::InvalidOrderSide {
                order_side: OrderSide::NoOrderSide,
            },
            OrderDeniedReason::MissingExpireTime,
            OrderDeniedReason::ExpireTimeInPast {
                expire_time: "1970-01-01T00:00:00Z".to_string(),
            },
            OrderDeniedReason::MissingTriggerType,
            OrderDeniedReason::MissingTrailingOffset,
            OrderDeniedReason::MissingTrailingOffsetType,
            OrderDeniedReason::UnsupportedTrailingOffsetType {
                offset_type: TrailingOffsetType::Price,
            },
            OrderDeniedReason::TrailingStopCalcFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::QuantityConversionFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::InstrumentNotFound {
                instrument_id: InstrumentId::from("AUD/USD.SIM"),
            },
            OrderDeniedReason::PositionNotFound {
                position_id: PositionId::from("P-1"),
            },
            OrderDeniedReason::ReduceOnlyWouldIncreasePosition {
                position_id: PositionId::from("P-1"),
            },
            OrderDeniedReason::OrderListIncomplete {
                order_list_id: OrderListId::from("OL-1"),
            },
            OrderDeniedReason::OrderListDenied {
                order_list_id: OrderListId::from("OL-1"),
            },
            OrderDeniedReason::TradingHalted,
            OrderDeniedReason::TradingStateReducing {
                order_side: OrderSide::Buy,
                instrument_id: InstrumentId::from("AUD/USD.SIM"),
            },
            OrderDeniedReason::RateLimitExceeded,
            OrderDeniedReason::NoExecutionClient {
                client_id: Some(ClientId::from("SIM")),
                routing_context: "venue=SIM".to_string(),
            },
            OrderDeniedReason::ClientVenueMismatch {
                client_id: ClientId::from("IB"),
                order_venue: Venue::from("XCME"),
                client_venue: Venue::from("IB"),
            },
            OrderDeniedReason::SubmitFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::InvalidPositionId {
                position_id: PositionId::from("P-1"),
                detail: "boom".to_string(),
            },
            OrderDeniedReason::UnsupportedTimeInForce(TimeInForce::Gtd),
            OrderDeniedReason::InvalidClientOrderId {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::UnsupportedOrderList {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::UnsupportedOrderType {
                order_type: OrderType::TrailingStopMarket,
            },
            OrderDeniedReason::UnsupportedTpSl {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::ValidationFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::StreamReconciling,
        ];

        for reason in samples {
            let code = OrderDeniedCode::from(&reason).to_string();
            assert!(
                reason.to_string().starts_with(&code),
                "message `{reason}` must start with code `{code}`"
            );
        }
    }

    #[rstest]
    fn generated_table_is_in_sync() {
        let committed = std::fs::read_to_string(DOC_PATH).expect("execution.md should exist");
        assert!(
            committed.contains(&generated_block()),
            "the order-denied-reasons table in docs/concepts/execution.md is stale; regenerate \
             with `cargo test -p nautilus-model regenerate_order_denied_reasons_doc -- --ignored`"
        );
    }

    #[rstest]
    #[ignore = "rewrites the generated table in execution.md; run after changing OrderDeniedReason variants"]
    fn regenerate_order_denied_reasons_doc() {
        let doc = std::fs::read_to_string(DOC_PATH).expect("execution.md should exist");
        let start = doc.find(BLOCK_BEGIN).expect("begin marker present");
        let end = doc.find(BLOCK_END).expect("end marker present") + BLOCK_END.len();
        let updated = format!("{}{}{}", &doc[..start], generated_block(), &doc[end..]);
        std::fs::write(DOC_PATH, updated).expect("should write execution.md");
    }

    fn generated_block() -> String {
        format!("{BLOCK_BEGIN}\n\n{}\n\n{BLOCK_END}", markdown_table())
    }

    fn markdown_table() -> String {
        const CODE_HEADER: &str = "Code";
        const DESC_HEADER: &str = "Description";

        // Sort codes alphabetically so families (UNSUPPORTED_, MISSING_, ...) cluster in the
        // table; the enum itself stays in declaration order to track the rollout phases.
        let mut codes: Vec<OrderDeniedCode> = OrderDeniedCode::iter().collect();
        codes.sort_by_key(ToString::to_string);
        let rows: Vec<(String, &'static str)> = codes
            .iter()
            .map(|code| (format!("`{code}`"), code.description()))
            .collect();
        let code_w = rows
            .iter()
            .map(|(code, _)| code.len())
            .max()
            .unwrap_or(0)
            .max(CODE_HEADER.len());
        let desc_w = rows
            .iter()
            .map(|(_, desc)| desc.len())
            .max()
            .unwrap_or(0)
            .max(DESC_HEADER.len());

        let mut lines = vec![
            format!("| {CODE_HEADER:<code_w$} | {DESC_HEADER:<desc_w$} |"),
            format!("| {:-<code_w$} | {:-<desc_w$} |", "", ""),
        ];

        for (code, desc) in rows {
            lines.push(format!("| {code:<code_w$} | {desc:<desc_w$} |"));
        }
        lines.join("\n")
    }
}