nautilus-model 0.62.0

Domain model for the Nautilus trading engine
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
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
// -------------------------------------------------------------------------------------------------
//  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 when
//! applicable by the diagnostic suffix documented on [`OrderDeniedReason`]. 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, Price, Quantity},
};

/// The order price field being validated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderPriceField {
    /// The order's `price` field.
    Price,
    /// The order's `trigger_price` field.
    TriggerPrice,
}

/// 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`].
///
/// Rendered messages use these forms:
///
/// - `CODE` when the denial needs no diagnostic suffix.
/// - `CODE: value` for one typed value or an opaque diagnostic detail.
/// - `CODE: key=value, key=value` when multiple typed values need disambiguation.
/// - `CODE: value; free text` when one typed value precedes an opaque detail.
///
/// Only the leading code is canonical. Consumers must not recover classification or control flow
/// from the diagnostic suffix.
///
/// Variants progress from direct field checks and required context through single-order,
/// cumulative, policy, routing, and downstream validation failures. Declaration order does not
/// define validation precedence.
#[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 price precision exceeds the instrument maximum.
    #[error(
        "PRICE_PRECISION_EXCEEDS_MAXIMUM: field={field}, price={price}, precision={price_precision}, max_precision={max_precision}"
    )]
    PricePrecisionExceedsMaximum {
        /// The price field being validated.
        field: OrderPriceField,
        /// The submitted price.
        price: Price,
        /// The submitted price precision.
        price_precision: u8,
        /// The instrument's maximum price precision.
        max_precision: u8,
    },
    /// The price is not positive for an instrument that disallows negative prices.
    #[error("PRICE_NOT_POSITIVE: field={field}, price={price}")]
    PriceNotPositive {
        /// The price field being validated.
        field: OrderPriceField,
        /// The submitted price.
        price: Price,
    },
    /// The quantity precision exceeds the instrument maximum.
    #[error(
        "QUANTITY_PRECISION_EXCEEDS_MAXIMUM: quantity={quantity}, precision={quantity_precision}, max_precision={max_precision}"
    )]
    QuantityPrecisionExceedsMaximum {
        /// The submitted quantity.
        quantity: Quantity,
        /// The submitted quantity precision.
        quantity_precision: u8,
        /// The instrument's maximum quantity precision.
        max_precision: u8,
    },
    /// The order quantity could not be converted for risk checks.
    #[error("QUANTITY_CONVERSION_FAILED: {detail}")]
    QuantityConversionFailed {
        /// The underlying conversion error.
        detail: String,
    },
    /// The effective order quantity exceeds the instrument maximum.
    #[error("QUANTITY_EXCEEDS_MAXIMUM: effective={effective_quantity}, max={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={effective_quantity}, min={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 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}")]
    ExpireTimeInPast {
        /// The expire time that has already elapsed.
        expire_time: String,
    },
    /// 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 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 instrument was not found in the cache.
    #[error("INSTRUMENT_NOT_FOUND: {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}")]
    PositionNotFound {
        /// The position that was not found.
        position_id: PositionId,
    },
    /// No market price is available for the order risk check.
    #[error("MARKET_PRICE_UNAVAILABLE: order_type={order_type}, instrument_id={instrument_id}")]
    MarketPriceUnavailable {
        /// The order type requiring a market price.
        order_type: OrderType,
        /// The instrument with no available market price.
        instrument_id: InstrumentId,
    },

    /// The trailing stop trigger price could not be calculated.
    #[error("TRAILING_STOP_CALCULATION_FAILED: {detail}")]
    TrailingStopCalculationFailed {
        /// The underlying calculation error.
        detail: String,
    },
    /// The order notional value could not be calculated.
    #[error("NOTIONAL_CALCULATION_FAILED: {detail}")]
    NotionalCalculationFailed {
        /// The underlying calculation error.
        detail: String,
    },
    /// The order notional is below the instrument minimum.
    #[error("NOTIONAL_BELOW_MINIMUM: min={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 instrument maximum.
    #[error("NOTIONAL_EXCEEDS_MAXIMUM: max={max_notional}, notional={notional}")]
    NotionalExceedsMaximum {
        /// The instrument's maximum notional.
        max_notional: Money,
        /// The order's notional value.
        notional: Money,
    },
    /// The order notional exceeds the configured maximum per order.
    #[error("NOTIONAL_EXCEEDS_MAX_PER_ORDER: max={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 account free balance.
    #[error("NOTIONAL_EXCEEDS_FREE_BALANCE: free={free_balance}, notional={notional}")]
    NotionalExceedsFreeBalance {
        /// The account's free balance.
        free_balance: Money,
        /// The order's notional value.
        notional: Money,
    },
    /// The order initial margin could not be calculated.
    #[error("INITIAL_MARGIN_CALCULATION_FAILED: {detail}")]
    InitialMarginCalculationFailed {
        /// The underlying calculation error.
        detail: String,
    },
    /// The order initial margin exceeds the account free balance.
    #[error("INITIAL_MARGIN_EXCEEDS_FREE_BALANCE: free={free_balance}, margin={initial_margin}")]
    InitialMarginExceedsFreeBalance {
        /// The account's free balance.
        free_balance: Money,
        /// The initial margin required for the order.
        initial_margin: Money,
    },
    /// The balance to lock for the betting order could not be calculated.
    #[error("BETTING_BALANCE_LOCKED_CALCULATION_FAILED: {detail}")]
    BettingBalanceLockedCalculationFailed {
        /// The underlying calculation error.
        detail: String,
    },

    /// The cumulative order notional exceeds the account free balance.
    #[error(
        "CUMULATIVE_NOTIONAL_EXCEEDS_FREE_BALANCE: free={free_balance}, notional={cumulative_notional}"
    )]
    CumulativeNotionalExceedsFreeBalance {
        /// The account's free balance.
        free_balance: Money,
        /// The cumulative notional across the checked orders.
        cumulative_notional: Money,
    },
    /// The cumulative initial margin could not be calculated.
    #[error("CUMULATIVE_INITIAL_MARGIN_CALCULATION_FAILED: {detail}")]
    CumulativeInitialMarginCalculationFailed {
        /// The underlying calculation error.
        detail: String,
    },
    /// The cumulative initial margin exceeds the account free balance.
    #[error(
        "CUMULATIVE_INITIAL_MARGIN_EXCEEDS_FREE_BALANCE: free={free_balance}, margin={cumulative_initial_margin}"
    )]
    CumulativeInitialMarginExceedsFreeBalance {
        /// The account's free balance.
        free_balance: Money,
        /// The cumulative initial margin across the checked orders.
        cumulative_initial_margin: Money,
    },

    /// A reduce-only order would increase the position.
    #[error("REDUCE_ONLY_WOULD_INCREASE_POSITION: {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}")]
    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}")]
    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: 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,
    /// The execution stream is unavailable or recovering; retry after recovery.
    #[error("STREAM_RECONCILING: execution stream unavailable or recovering, retry after recovery")]
    StreamReconciling,

    /// No execution client was found for the routed command.
    #[error(
        "NO_EXECUTION_CLIENT: client_id={client}, {routing_context}",
        client = .client_id.as_ref().map_or("NONE", ClientId::as_str),
    )]
    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 client order ID is invalid for the venue.
    #[error("INVALID_CLIENT_ORDER_ID: {detail}")]
    InvalidClientOrderId {
        /// The validation failure detail.
        detail: String,
    },
    /// The supplied position ID is invalid for the order submission.
    #[error("INVALID_POSITION_ID: {position_id}; {detail}")]
    InvalidPositionId {
        /// The invalid position ID.
        position_id: PositionId,
        /// 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.
    #[error("UNSUPPORTED_ORDER_TYPE: {order_type}")]
    UnsupportedOrderType {
        /// The unsupported order type.
        order_type: OrderType,
    },
    /// The order's time in force is not supported.
    #[error("UNSUPPORTED_TIME_IN_FORCE: {0}")]
    UnsupportedTimeInForce(TimeInForce),
    /// 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 validation before submission.
    #[error("VALIDATION_FAILED: {detail}")]
    ValidationFailed {
        /// The validation failure detail.
        detail: String,
    },
}

impl OrderDeniedCode {
    /// Returns a one-line description of this denial code.
    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            Self::PricePrecisionExceedsMaximum => {
                "The price precision exceeds the instrument maximum."
            }
            Self::PriceNotPositive => "The price is not positive.",
            Self::QuantityPrecisionExceedsMaximum => {
                "The quantity precision exceeds the instrument maximum."
            }
            Self::QuantityConversionFailed => {
                "The order quantity could not be converted for risk checks."
            }
            Self::QuantityExceedsMaximum => {
                "The effective order quantity exceeds the instrument maximum."
            }
            Self::QuantityBelowMinimum => {
                "The effective order quantity is below the instrument minimum."
            }
            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::MissingTrailingOffsetType => {
                "The order is missing a required trailing offset type."
            }
            Self::UnsupportedTrailingOffsetType => {
                "The order's trailing offset type is not supported."
            }
            Self::MissingTriggerType => "The order is missing a required trigger type.",
            Self::MissingTrailingOffset => "The order is missing a required trailing offset.",
            Self::InstrumentNotFound => "The instrument was not found in the cache.",
            Self::PositionNotFound => "The position for a reduce‑only order was not found.",
            Self::MarketPriceUnavailable => {
                "No market price is available for the order risk check."
            }
            Self::TrailingStopCalculationFailed => {
                "The trailing stop trigger price could not be calculated."
            }
            Self::NotionalCalculationFailed => "The order notional value could not be calculated.",
            Self::NotionalBelowMinimum => "The order notional is below the instrument minimum.",
            Self::NotionalExceedsMaximum => "The order notional exceeds the instrument maximum.",
            Self::NotionalExceedsMaxPerOrder => {
                "The order notional exceeds the configured maximum per order."
            }
            Self::NotionalExceedsFreeBalance => {
                "The order notional exceeds the account free balance."
            }
            Self::InitialMarginCalculationFailed => {
                "The order initial margin could not be calculated."
            }
            Self::InitialMarginExceedsFreeBalance => {
                "The order initial margin exceeds the account free balance."
            }
            Self::BettingBalanceLockedCalculationFailed => {
                "The balance to lock for the betting order could not be calculated."
            }
            Self::CumulativeNotionalExceedsFreeBalance => {
                "The cumulative order notional exceeds the account free balance."
            }
            Self::CumulativeInitialMarginCalculationFailed => {
                "The cumulative initial margin could not be calculated."
            }
            Self::CumulativeInitialMarginExceedsFreeBalance => {
                "The cumulative initial margin exceeds the account free balance."
            }
            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::StreamReconciling => {
                "The execution stream is unavailable or recovering; retry after recovery."
            }
            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::InvalidClientOrderId => "The client order ID is invalid for the venue.",
            Self::InvalidPositionId => {
                "The supplied position ID is invalid for the order submission."
            }
            Self::UnsupportedOrderList => "The venue does not support the requested order list.",
            Self::UnsupportedOrderType => "The order type is not supported.",
            Self::UnsupportedTimeInForce => "The order's time in force is not supported.",
            Self::UnsupportedTpSl => {
                "The venue does not support the requested take‑profit/stop‑loss parameters."
            }
            Self::ValidationFailed => "The order failed validation before submission.",
        }
    }
}

#[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=15, max=10"
        );
        assert_eq!(
            below.to_string(),
            "QUANTITY_BELOW_MINIMUM: effective=1, min=5"
        );
        assert_eq!(
            notional.to_string(),
            "NOTIONAL_BELOW_MINIMUM: min=1.00 USD, notional=0.90 USD"
        );
    }

    #[rstest]
    fn renders_standardized_risk_messages() {
        assert_eq!(
            OrderDeniedReason::PricePrecisionExceedsMaximum {
                field: OrderPriceField::Price,
                price: Price::from("1.234"),
                price_precision: 3,
                max_precision: 2,
            }
            .to_string(),
            "PRICE_PRECISION_EXCEEDS_MAXIMUM: field=PRICE, price=1.234, precision=3, max_precision=2"
        );
        assert_eq!(
            OrderDeniedReason::PriceNotPositive {
                field: OrderPriceField::TriggerPrice,
                price: Price::from("-0.1"),
            }
            .to_string(),
            "PRICE_NOT_POSITIVE: field=TRIGGER_PRICE, price=-0.1"
        );
        assert_eq!(
            OrderDeniedReason::QuantityConversionFailed {
                detail: "value exceeds MoneyRaw bounds".to_string(),
            }
            .to_string(),
            "QUANTITY_CONVERSION_FAILED: value exceeds MoneyRaw bounds"
        );
        assert_eq!(
            OrderDeniedReason::UnsupportedTrailingOffsetType {
                offset_type: TrailingOffsetType::PriceTier,
            }
            .to_string(),
            "UNSUPPORTED_TRAILING_OFFSET_TYPE: PRICE_TIER"
        );
        assert_eq!(
            OrderDeniedReason::NotionalCalculationFailed {
                detail: "value exceeds Money bounds".to_string(),
            }
            .to_string(),
            "NOTIONAL_CALCULATION_FAILED: value exceeds Money bounds"
        );
        assert_eq!(
            OrderDeniedReason::InitialMarginCalculationFailed {
                detail: "margin model unavailable".to_string(),
            }
            .to_string(),
            "INITIAL_MARGIN_CALCULATION_FAILED: margin model unavailable"
        );
        assert_eq!(
            OrderDeniedReason::NotionalExceedsMaxPerOrder {
                max_notional: Money::from("10.00 USD"),
                notional: Money::from("11.00 USD"),
            }
            .to_string(),
            "NOTIONAL_EXCEEDS_MAX_PER_ORDER: max=10.00 USD, notional=11.00 USD"
        );
        assert_eq!(
            OrderDeniedReason::NotionalExceedsMaximum {
                max_notional: Money::from("12.00 USD"),
                notional: Money::from("13.00 USD"),
            }
            .to_string(),
            "NOTIONAL_EXCEEDS_MAXIMUM: max=12.00 USD, notional=13.00 USD"
        );
        assert_eq!(
            OrderDeniedReason::NotionalExceedsFreeBalance {
                free_balance: Money::from("10.00 USD"),
                notional: Money::from("11.00 USD"),
            }
            .to_string(),
            "NOTIONAL_EXCEEDS_FREE_BALANCE: free=10.00 USD, notional=11.00 USD"
        );
        assert_eq!(
            OrderDeniedReason::CumulativeNotionalExceedsFreeBalance {
                free_balance: Money::from("10.00 USD"),
                cumulative_notional: Money::from("12.00 USD"),
            }
            .to_string(),
            "CUMULATIVE_NOTIONAL_EXCEEDS_FREE_BALANCE: free=10.00 USD, notional=12.00 USD"
        );
        assert_eq!(
            OrderDeniedReason::InitialMarginExceedsFreeBalance {
                free_balance: Money::from("10.00 USD"),
                initial_margin: Money::from("13.00 USD"),
            }
            .to_string(),
            "INITIAL_MARGIN_EXCEEDS_FREE_BALANCE: free=10.00 USD, margin=13.00 USD"
        );
        assert_eq!(
            OrderDeniedReason::CumulativeInitialMarginExceedsFreeBalance {
                free_balance: Money::from("10.00 USD"),
                cumulative_initial_margin: Money::from("14.00 USD"),
            }
            .to_string(),
            "CUMULATIVE_INITIAL_MARGIN_EXCEEDS_FREE_BALANCE: free=10.00 USD, margin=14.00 USD"
        );
        assert_eq!(
            OrderDeniedReason::CumulativeInitialMarginCalculationFailed {
                detail: "total exceeds Money bounds".to_string(),
            }
            .to_string(),
            "CUMULATIVE_INITIAL_MARGIN_CALCULATION_FAILED: total exceeds Money bounds"
        );
        assert_eq!(
            OrderDeniedReason::BettingBalanceLockedCalculationFailed {
                detail: "invalid liability".to_string(),
            }
            .to_string(),
            "BETTING_BALANCE_LOCKED_CALCULATION_FAILED: invalid liability"
        );
        assert_eq!(
            OrderDeniedReason::TrailingStopCalculationFailed {
                detail: "missing market price".to_string(),
            }
            .to_string(),
            "TRAILING_STOP_CALCULATION_FAILED: missing market price"
        );
    }

    #[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: AUD/USD.SIM");
        assert_eq!(
            OrderDeniedReason::ExpireTimeInPast {
                expire_time: "1970-01-01T00:00:00Z".to_string(),
            }
            .to_string(),
            "EXPIRE_TIME_IN_PAST: 1970-01-01T00:00:00Z"
        );
        assert_eq!(
            OrderDeniedReason::PositionNotFound {
                position_id: PositionId::from("P-1"),
            }
            .to_string(),
            "POSITION_NOT_FOUND: P-1"
        );
        assert_eq!(
            OrderDeniedReason::ReduceOnlyWouldIncreasePosition {
                position_id: PositionId::from("P-2"),
            }
            .to_string(),
            "REDUCE_ONLY_WOULD_INCREASE_POSITION: P-2"
        );
        assert_eq!(
            OrderDeniedReason::OrderListIncomplete {
                order_list_id: OrderListId::from("OL-1"),
            }
            .to_string(),
            "ORDER_LIST_INCOMPLETE: OL-1"
        );
        assert_eq!(
            OrderDeniedReason::OrderListDenied {
                order_list_id: OrderListId::from("OL-2"),
            }
            .to_string(),
            "ORDER_LIST_DENIED: OL-2"
        );
        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: 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=SIM, 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: P-1; 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: execution stream unavailable or recovering, retry after recovery"
        );
    }

    // 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::PricePrecisionExceedsMaximum {
                field: OrderPriceField::Price,
                price: Price::from("1.00"),
                price_precision: 2,
                max_precision: 1,
            },
            OrderDeniedReason::PriceNotPositive {
                field: OrderPriceField::TriggerPrice,
                price: Price::from("0.00"),
            },
            OrderDeniedReason::QuantityPrecisionExceedsMaximum {
                quantity: Quantity::from("1.00"),
                quantity_precision: 2,
                max_precision: 1,
            },
            OrderDeniedReason::QuantityConversionFailed {
                detail: "boom".to_string(),
            },
            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::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::MissingTrailingOffsetType,
            OrderDeniedReason::UnsupportedTrailingOffsetType {
                offset_type: TrailingOffsetType::Price,
            },
            OrderDeniedReason::MissingTriggerType,
            OrderDeniedReason::MissingTrailingOffset,
            OrderDeniedReason::InstrumentNotFound {
                instrument_id: InstrumentId::from("AUD/USD.SIM"),
            },
            OrderDeniedReason::PositionNotFound {
                position_id: PositionId::from("P-1"),
            },
            OrderDeniedReason::MarketPriceUnavailable {
                order_type: OrderType::Market,
                instrument_id: InstrumentId::from("AUD/USD.SIM"),
            },
            OrderDeniedReason::TrailingStopCalculationFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::NotionalCalculationFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::NotionalBelowMinimum {
                min_notional: usd(),
                notional: usd(),
            },
            OrderDeniedReason::NotionalExceedsMaximum {
                max_notional: usd(),
                notional: usd(),
            },
            OrderDeniedReason::NotionalExceedsMaxPerOrder {
                max_notional: usd(),
                notional: usd(),
            },
            OrderDeniedReason::NotionalExceedsFreeBalance {
                free_balance: usd(),
                notional: usd(),
            },
            OrderDeniedReason::InitialMarginCalculationFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::InitialMarginExceedsFreeBalance {
                free_balance: usd(),
                initial_margin: usd(),
            },
            OrderDeniedReason::BettingBalanceLockedCalculationFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::CumulativeNotionalExceedsFreeBalance {
                free_balance: usd(),
                cumulative_notional: usd(),
            },
            OrderDeniedReason::CumulativeInitialMarginCalculationFailed {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::CumulativeInitialMarginExceedsFreeBalance {
                free_balance: usd(),
                cumulative_initial_margin: usd(),
            },
            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::StreamReconciling,
            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::InvalidClientOrderId {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::InvalidPositionId {
                position_id: PositionId::from("P-1"),
                detail: "boom".to_string(),
            },
            OrderDeniedReason::UnsupportedOrderList {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::UnsupportedOrderType {
                order_type: OrderType::TrailingStopMarket,
            },
            OrderDeniedReason::UnsupportedTimeInForce(TimeInForce::Gtd),
            OrderDeniedReason::UnsupportedTpSl {
                detail: "boom".to_string(),
            },
            OrderDeniedReason::ValidationFailed {
                detail: "boom".to_string(),
            },
        ];

        assert_eq!(samples.len(), OrderDeniedCode::iter().count());
        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";

        // Declaration order carries the public table's abstraction hierarchy
        let rows: Vec<(String, &'static str)> = OrderDeniedCode::iter()
            .map(|code| (format!("`{code}`"), code.description()))
            .collect();
        // Width counts characters, matching the padding applied by `format!` and the
        // column width the Markdown table hook normalizes to. Descriptions carry
        // non-breaking hyphens, so byte length would over-pad the column.
        let code_w = rows
            .iter()
            .map(|(code, _)| code.chars().count())
            .max()
            .unwrap_or(0)
            .max(CODE_HEADER.chars().count());
        let desc_w = rows
            .iter()
            .map(|(_, desc)| desc.chars().count())
            .max()
            .unwrap_or(0)
            .max(DESC_HEADER.chars().count());

        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")
    }
}