rustrade-execution 0.17.0

Stream private account data from financial venues, and execute (live or mock) orders.
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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
//! Error types for [`ExecutionClient`](super::client::ExecutionClient) operations.
//!
//! # Retry Semantics
//!
//! Use [`ClientError::is_transient`] to determine if an operation should be retried.
//! Transient errors (connectivity issues, rate limits) may succeed on retry with
//! appropriate backoff. Non-transient errors (invalid instrument, insufficient
//! balance) will fail identically on retry — the caller must change the request.
//!
//! The `is_transient()` method is the stable contract for retry decisions. Prefer
//! it over pattern matching on specific variants, as the internal taxonomy may
//! evolve while `is_transient()` semantics remain stable.

use crate::margin::MarginEffect;
use derive_more::Constructor;
use rust_decimal::Decimal;
use rustrade_instrument::{
    asset::{AssetIndex, name::AssetNameExchange},
    exchange::ExchangeId,
    index::error::IndexError,
    instrument::{InstrumentIndex, name::InstrumentNameExchange},
};
use rustrade_integration::error::SocketError;
use serde::{Deserialize, Serialize};
use std::{fmt, time::Duration};
use thiserror::Error;

/// Type alias for a [`ClientError`] that is keyed on [`AssetNameExchange`] and
/// [`InstrumentNameExchange`] (yet to be indexed).
pub type UnindexedClientError = ClientError<AssetNameExchange, InstrumentNameExchange>;

/// Type alias for a [`ApiError`] that is keyed on [`AssetNameExchange`] and
/// [`InstrumentNameExchange`] (yet to be indexed).
pub type UnindexedApiError = ApiError<AssetNameExchange, InstrumentNameExchange>;

/// Type alias for a [`OrderError`] that is keyed on [`AssetNameExchange`] and
/// [`InstrumentNameExchange`] (yet to be indexed).
pub type UnindexedOrderError = OrderError<AssetNameExchange, InstrumentNameExchange>;

/// Represents all errors produced by an [`ExecutionClient`](super::client::ExecutionClient).
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
pub enum ClientError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
    /// Connectivity based error.
    ///
    /// eg/ Timeout.
    #[error("Connectivity: {0}")]
    Connectivity(#[from] ConnectivityError),

    /// API based error.
    ///
    /// eg/ RateLimit.
    #[error("API: {0}")]
    Api(#[from] ApiError<AssetKey, InstrumentKey>),

    /// A background task panicked or was cancelled during an operation.
    ///
    /// This indicates a bug or unexpected runtime condition (e.g., a tokio
    /// `spawn_blocking` task panicked). The operation was not retried and
    /// the caller should treat this as non-recoverable, requiring operator
    /// attention.
    #[error("task failed: {0}")]
    TaskFailed(String),

    /// An opaque error from an upstream library that cannot be further classified.
    ///
    /// This is a catch-all for errors that don't fit into [`Self::Connectivity`] or
    /// [`Self::Api`] categories — typically because the upstream library (e.g., ibapi,
    /// binance-sdk) returns unstructured errors.
    ///
    /// Conservatively treated as non-transient. If you encounter this error
    /// frequently, consider filing an issue to improve error classification.
    #[error("internal error: {0}")]
    Internal(String),

    /// A bounded read of fills could not advance past its start: more fills share the span's
    /// first moment than one call can read, so a read from the same start would stop at the same
    /// place.
    ///
    /// [`ExecutionClient::fetch_trades`](crate::client::ExecutionClient::fetch_trades) returns it
    /// rather than a [`TradesRead`](crate::trade::TradesRead) whose `resume` could only loop. The
    /// fills it read are not returned. Callers should alert operators and reconcile the span
    /// another way.
    #[error("trade read stopped after {fills_read} fills without advancing past its start")]
    Truncated {
        /// How many fills the read returned before it stopped.
        fills_read: usize,
    },

    /// Open orders snapshot was truncated at the API's row limit.
    ///
    /// Unlike [`Self::Truncated`] (which applies to paginated fill reads), this
    /// error indicates a single-request endpoint hit its maximum row count.
    /// Alpaca's `/v2/orders` endpoint caps results at 500; accounts with more
    /// concurrent open orders will have an incomplete snapshot.
    ///
    /// Callers should alert operators — an incomplete order snapshot can cause
    /// duplicate submissions, missed cancellations, or incorrect position sizing.
    #[error("open orders snapshot truncated at {limit} results — data may be incomplete")]
    TruncatedSnapshot {
        /// Maximum number of rows returned by the single-request endpoint.
        limit: usize,
    },
}

impl<AssetKey, InstrumentKey> ClientError<AssetKey, InstrumentKey> {
    /// Returns `true` if this error is likely transient and the operation
    /// may succeed if retried after a suitable backoff.
    ///
    /// The caller is responsible for retry limits and backoff strategy.
    /// This method classifies the error only — it does not implement policy.
    ///
    /// # Transient errors
    /// - [`Connectivity`](Self::Connectivity) errors (timeout, socket, offline)
    /// - [`Api::RateLimit`](ApiError::RateLimit), though not before its `retry_after`
    ///
    /// # Non-transient errors
    /// - Other [`Api`](Self::Api) errors (invalid instrument, insufficient balance, etc.)
    /// - [`TaskFailed`](Self::TaskFailed) (indicates a bug)
    /// - [`Internal`](Self::Internal) (unknown — conservatively non-transient)
    /// - [`Truncated`](Self::Truncated) / [`TruncatedSnapshot`](Self::TruncatedSnapshot)
    pub fn is_transient(&self) -> bool {
        match self {
            Self::Connectivity(e) => e.is_transient(),
            Self::Api(ApiError::RateLimit { .. }) => true,
            Self::Api(_) => false,
            Self::TaskFailed(_) => false,
            Self::Internal(_) => false,
            Self::Truncated { .. } => false,
            Self::TruncatedSnapshot { .. } => false,
        }
    }

    /// The venue's minimum wait before a retry: `Some` only for an
    /// [`Api::RateLimit`](ApiError::RateLimit) whose venue sent a hint the client could read. See
    /// [`ApiError::retry_after`].
    pub fn retry_after(&self) -> Option<Duration> {
        match self {
            Self::Api(error) => error.retry_after(),
            _ => None,
        }
    }
}

/// Represents all connectivity-centric errors.
///
/// Connectivity errors are generally intermittent / non-deterministic (eg/ Timeout).
/// All variants are transient — retry with exponential backoff (typically 1-30s).
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
pub enum ConnectivityError {
    /// Exchange is offline, likely due to scheduled maintenance.
    ///
    /// Transient — retry with backoff. Maintenance windows typically last minutes
    /// to hours; consider longer backoff intervals (30s-5min) to avoid log spam.
    #[error("Exchange offline: {0}")]
    ExchangeOffline(ExchangeId),

    /// Request timed out before a response was received.
    ///
    /// Transient — retry with backoff. May indicate network congestion, server
    /// overload, or an overly aggressive timeout. Consider increasing timeout
    /// on subsequent attempts.
    #[error("request timed out")]
    Timeout,

    /// Network-level socket error (connection refused, reset, DNS failure, etc.).
    ///
    /// Transient — retry with backoff. If persistent, may indicate firewall
    /// issues, incorrect endpoint configuration, or prolonged server outage.
    #[error("{0}")]
    Socket(String),
}

impl From<SocketError> for ConnectivityError {
    fn from(value: SocketError) -> Self {
        Self::Socket(value.to_string())
    }
}

impl ConnectivityError {
    /// Returns `true` if this connectivity error is transient.
    ///
    /// All connectivity errors are considered transient — they represent
    /// temporary network or server conditions that may resolve with retry.
    pub fn is_transient(&self) -> bool {
        match self {
            Self::ExchangeOffline(_) => true,
            Self::Timeout => true,
            Self::Socket(_) => true,
        }
    }
}

/// Represents all API errors generated by an exchange.
///
/// These typically indicate a request is invalid for some reason (eg/ BalanceInsufficient).
/// Most variants are **not transient** — the same request will fail identically on retry.
/// The exception is [`RateLimit`](Self::RateLimit), which is transient.
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
pub enum ApiError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
    /// Provided asset identifier is invalid or not supported.
    ///
    /// For example:
    /// - The [`AssetNameExchange`] was an invalid format.
    ///
    /// Not transient — do not retry. The asset identifier must be corrected.
    ///
    /// Indexed only when the [`ExecutionInstrumentMap`] holds the asset. Otherwise there is no
    /// index to carry, and [`AccountEventIndexer`] reports it as
    /// [`OrderRejected`](Self::OrderRejected) (from an order request) or
    /// [`RequestRejected`](Self::RequestRejected) (from any other request), holding this error's
    /// own message.
    ///
    /// [`ExecutionInstrumentMap`]: crate::map::ExecutionInstrumentMap
    /// [`AccountEventIndexer`]: crate::indexer::AccountEventIndexer
    #[error("asset {0} invalid: {1}")]
    AssetInvalid(AssetKey, String),

    /// Provided instrument identifier is invalid or not supported.
    ///
    /// For example:
    /// - The exchange does not have a market for an instrument.
    /// - The [`InstrumentNameExchange`] was an invalid format.
    ///
    /// Not transient — do not retry. The instrument identifier must be corrected.
    ///
    /// Indexed only when the [`ExecutionInstrumentMap`] holds the instrument; otherwise reported
    /// as [`AssetInvalid`](Self::AssetInvalid) describes.
    ///
    /// [`ExecutionInstrumentMap`]: crate::map::ExecutionInstrumentMap
    #[error("instrument {0} invalid: {1}")]
    InstrumentInvalid(InstrumentKey, String),

    /// Request was rejected due to rate limiting.
    ///
    /// The exchange enforces request quotas and the caller has exceeded them. The client may
    /// already have waited and retried within its own bounded retries before surfacing this.
    ///
    /// `retry_after` is the venue's own minimum wait, measured from when the client read the
    /// refusal: do not retry sooner. `None` means the venue sent no hint, or the client cannot
    /// read it, and is not permission to retry at once. Which clients fill it:
    /// - **Alpaca:** from a 429's `Retry-After`, or else `X-RateLimit-Reset`, once the client's
    ///   own retries are exhausted.
    /// - **Binance:** from a REST 429's or 418's `Retry-After`, or the time a WebSocket API
    ///   refusal's `retryAfter` names, measured against the local clock. Uncapped, since a ban can
    ///   last days, so add it to an `Instant` with `checked_add`. A request the client held back
    ///   unsent, because an earlier refusal's wait had longer left than the client sleeps
    ///   through, reports the time left.
    /// - **Hyperliquid:** never: its SDK keeps no headers, and Hyperliquid documents no hint.
    ///
    /// A venue ban (Binance's HTTP 418) is reported the same way: its hint, when readable, says
    /// how long it lasts.
    ///
    /// Transient — retry after `retry_after` when given, otherwise with backoff.
    ///
    /// The variant is `#[non_exhaustive]`: outside this crate, build one with
    /// [`ApiError::rate_limited`], match it as `RateLimit { .. }`, and read the wait with
    /// [`ApiError::retry_after`].
    #[error("rate limit exceeded{}", RetryAfter(*retry_after))]
    #[non_exhaustive]
    RateLimit { retry_after: Option<Duration> },

    /// The venue refused because a cap on something held at once is full, such as IBKR's market
    /// data lines, which every TWS session and API client on the account shares.
    ///
    /// Unlike [`RateLimit`](Self::RateLimit), waiting does not clear it: releasing something
    /// does, such as cancelling another subscription, whether this client holds it or another
    /// session on the same account does. The message carries the venue's words.
    ///
    /// Not transient: the same request retried with backoff alone meets the same refusal while
    /// the cap stays full.
    #[error("venue capacity exceeded: {0}")]
    CapacityExceeded(String),

    /// Authentication failed (invalid credentials, expired key, bad signature).
    ///
    /// Unlike other API errors which affect a single request, authentication
    /// failures indicate that **all** subsequent requests will fail until
    /// credentials are corrected. Callers should halt trading and alert operators.
    ///
    /// Not transient — do not retry. Fix credentials and restart.
    #[error("authentication failed: {0}")]
    Unauthenticated(String),

    /// Balance of an asset is insufficient to execute the requested operation.
    ///
    /// The asset is `None` when it is not known which asset ran short:
    /// - the venue's rejection does not name it (e.g. Binance's "Account has insufficient
    ///   balance for requested action", or any Hyperliquid margin or spot-balance refusal), and
    ///   a client does not guess it from the order;
    /// - the venue named an asset that the [`ExecutionInstrumentMap`] does not hold, so it has no
    ///   index. [`AccountEventIndexer::api_error`] logs the name it dropped.
    ///
    /// The `String` carries the venue's message.
    ///
    /// Not transient — do not retry the same request. Reduce order size or
    /// deposit additional funds.
    ///
    /// [`ExecutionInstrumentMap`]: crate::map::ExecutionInstrumentMap
    /// [`AccountEventIndexer::api_error`]: crate::indexer::AccountEventIndexer::api_error
    #[error(
        "balance insufficient{asset}: {1}",
        asset = .0.as_ref().map(|asset| format!(" for asset {asset}")).unwrap_or_default()
    )]
    BalanceInsufficient(Option<AssetKey>, String),

    /// Order was rejected by the exchange for a business rule violation.
    ///
    /// Common causes include: price outside allowed range, quantity below
    /// minimum, post-only order would cross, reduce-only with no position.
    ///
    /// Not transient — do not retry the same request. Adjust order parameters.
    #[error("order rejected: {0}")]
    OrderRejected(String),

    /// Cancel request failed because the order was already cancelled.
    ///
    /// This is a state conflict, not an error per se — the desired end state
    /// (order cancelled) has already been achieved.
    ///
    /// Not transient — do not retry. The order is already in the cancelled state.
    #[error("order already cancelled")]
    OrderAlreadyCancelled,

    /// Cancel request failed because the order was already fully filled.
    ///
    /// This is a state conflict — the order completed before the cancel arrived.
    /// The caller should reconcile their local state with the fill.
    ///
    /// Not transient — do not retry. The order no longer exists to cancel.
    #[error("order already fully filled")]
    OrderAlreadyFullyFilled,

    /// Cancel request failed because the order had already expired.
    ///
    /// This is a state conflict — the order's own deadline retired it before the cancel arrived,
    /// so the desired end state (order no longer working) has already been achieved. Distinct from
    /// [`OrderAlreadyCancelled`](Self::OrderAlreadyCancelled) because nobody asked for it: a
    /// time-in-force such as [`GoodTillDate`](crate::order::TimeInForce::GoodTillDate) retired it
    /// unprompted, and a caller reconciling its local state needs to know which of the two happened.
    ///
    /// Not transient — do not retry. The order no longer exists to cancel.
    #[error("order already expired")]
    OrderAlreadyExpired,

    /// Open request refused because its [`ClientOrderId`] is already in use at the venue.
    ///
    /// The refusal concerns this request alone: the order already under the id is **unaffected**,
    /// and is not reported ended by it. What "in use" means is the venue's rule. On the
    /// [`SimulatedVenue`] and the IBKR client it is an order still working under the id, and an id
    /// is free again once its order has ended. Binance documents an id as unique among open
    /// orders. The `String` carries the venue's message, or the client's own where it refused the
    /// request before sending it.
    ///
    /// Reported by the [`SimulatedVenue`], by the IBKR client, which refuses the request before it
    /// reaches TWS, since TWS never sees a client order id, and by the Binance spot and margin
    /// clients, from Binance's `"Duplicate order sent."`. Other clients report a venue's duplicate
    /// rejection as [`OrderRejected`](Self::OrderRejected) until its message has been confirmed.
    ///
    /// Not transient — the same request fails identically while the order under the id works.
    /// Use another id, or wait for that order to end.
    ///
    /// [`ClientOrderId`]: crate::order::id::ClientOrderId
    /// [`SimulatedVenue`]: crate::exchange::mock::SimulatedVenue
    #[error("client order id in use: {0}")]
    DuplicateClientOrderId(String),

    /// The exchange refused the request itself, rather than an order it carried.
    ///
    /// The request was malformed or asked for something the venue does not serve — a missing,
    /// malformed or out-of-range parameter, such as a query time window longer than the venue
    /// allows. Distinct from [`OrderRejected`](Self::OrderRejected), which is an order failing a
    /// business rule; this variant arises from queries and other non-order requests. The message
    /// carries the venue's own error code where it provides one (e.g. `-1127 ...` on Binance).
    ///
    /// Not transient — the same request fails identically on retry. Change the request.
    #[error("request rejected: {0}")]
    RequestRejected(String),

    /// Order refused because the venue would not lend what it needed: a short sale, or a margin
    /// order that borrows to cover itself.
    ///
    /// Distinct from [`OrderRejected`](Self::OrderRejected) so a caller can tell a refused borrow
    /// apart from a malformed order, and from [`BalanceInsufficient`](Self::BalanceInsufficient),
    /// which is the account's own funds running short. A borrow can be refused for a long too: on
    /// Binance margin, an order that borrows to buy is refused when the venue has too little of
    /// the asset to lend or the borrow would exceed the account's limit. [`BorrowReject`] says
    /// why.
    ///
    /// Reported by the Binance margin client, by Binance's code, by the Alpaca client, by the
    /// text of a 403 or 422, and by the
    /// [`SimulatedVenue`](crate::exchange::mock::SimulatedVenue), for a CFD short its
    /// [`ShortabilityProvider`](crate::shortability::ShortabilityProvider) does not allow. Other
    /// clients report such refusals as [`OrderRejected`](Self::OrderRejected) until their venue's
    /// wording is confirmed.
    ///
    /// Not transient — the same request fails identically until the venue's lending changes.
    #[error("borrow rejected: {0}")]
    BorrowRejected(BorrowReject),
}

impl<AssetKey, InstrumentKey> ApiError<AssetKey, InstrumentKey> {
    /// A [`RateLimit`](Self::RateLimit) refusal, with the venue's minimum wait when it sent one.
    pub fn rate_limited(retry_after: Option<Duration>) -> Self {
        Self::RateLimit { retry_after }
    }

    /// The venue's minimum wait before a retry: `Some` only for a
    /// [`RateLimit`](Self::RateLimit) whose venue sent a hint the client could read.
    pub fn retry_after(&self) -> Option<Duration> {
        match self {
            Self::RateLimit { retry_after } => *retry_after,
            _ => None,
        }
    }
}

/// Formats a [`RateLimit`](ApiError::RateLimit)'s hint for its message: nothing when there is
/// none.
struct RetryAfter(Option<Duration>);

impl fmt::Display for RetryAfter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Some(retry_after) => write!(f, "; retry after {retry_after:?}"),
            None => Ok(()),
        }
    }
}

/// Why a venue refused to lend for an order, as carried by [`ApiError::BorrowRejected`].
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub struct BorrowReject {
    /// The kind of refusal.
    pub reason: BorrowRejectReason,
    /// The venue's own code for the refusal, where it gave one (e.g. `-3045` on Binance,
    /// `40310000` on Alpaca).
    ///
    /// For diagnostics only, not a stable contract: match on [`reason`](Self::reason) instead. A
    /// venue may reuse a code for several refusals, as Alpaca's generic `40310000` is.
    pub venue_code: Option<String>,
    /// The venue's message. It may itself carry the code, as Binance's does.
    pub message: String,
    /// How much the venue could still have lent, in the units the order was sized in, where
    /// known: the most a smaller order could have sold short. Set by the simulated venue; no live
    /// client reports it yet.
    pub available: Option<Decimal>,
}

impl BorrowReject {
    /// A refusal for `reason`, with the venue's code where it gave one, and its message.
    pub fn new(reason: BorrowRejectReason, venue_code: Option<String>, message: String) -> Self {
        Self {
            reason,
            venue_code,
            message,
            available: None,
        }
    }

    /// With how much the venue could still have lent.
    #[must_use]
    pub fn with_available(mut self, available: Decimal) -> Self {
        self.available = Some(available);
        self
    }
}

impl fmt::Display for BorrowReject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            reason,
            venue_code,
            message,
            available,
        } = self;
        write!(f, "{reason}")?;
        if let Some(code) = venue_code {
            write!(f, " (code {code})")?;
        }
        write!(f, ": {message}")?;
        if let Some(available) = available {
            write!(f, " ({available} available)")?;
        }
        Ok(())
    }
}

/// The kind of borrow refusal carried by a [`BorrowReject`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub enum BorrowRejectReason {
    /// The instrument cannot be sold short at all, whoever asks (e.g. Alpaca's "asset X cannot be
    /// sold short").
    NotShortable,
    /// Borrowing is barred for this account, or for this asset on this account (e.g. Binance
    /// `-3008`, `-3012` and `-3014`, Alpaca's "account is not allowed to short").
    BorrowDisabled,
    /// The venue has too little of the asset to lend right now (e.g. Binance `-3045`). It may
    /// lend again later.
    InventoryUnavailable,
    /// The borrow would exceed what the account may borrow (e.g. Binance `-3006`).
    BorrowLimitExceeded,
    /// A short-sale restriction is in effect, such as the SEC's Rule 201 circuit breaker after a
    /// 10% fall, and the order would sell short at or below the best bid. A short sale priced
    /// above the bid may still be accepted.
    ShortSaleRestricted,
    /// A borrow refusal of a kind not listed here. The [`BorrowReject`] message says which.
    Other,
}

impl fmt::Display for BorrowRejectReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NotShortable => "not shortable",
            Self::BorrowDisabled => "borrow disabled",
            Self::InventoryUnavailable => "inventory unavailable",
            Self::BorrowLimitExceeded => "borrow limit exceeded",
            Self::ShortSaleRestricted => "short sale restricted",
            Self::Other => "other",
        })
    }
}

/// Represents all errors that can be generated when cancelling or opening orders.
///
/// This is a subset of [`ClientError`] for order-specific operations. Use
/// [`is_transient()`](Self::is_transient) to determine retry eligibility.
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
pub enum OrderError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
    /// Connectivity-based error (timeout, socket failure, exchange offline), or a venue failure
    /// that leaves the order's status unknown.
    ///
    /// Transient — retry with backoff. See [`ConnectivityError`] for details. The order may or
    /// may not have reached the matching engine, so before resubmitting an open request,
    /// reconcile its state (open orders, fills); a blind retry can place it twice.
    ///
    /// For an open request, this means **the outcome is unknown**, not that the open failed: see
    /// [`is_outcome_unknown`](Self::is_outcome_unknown). A client that knows the request never
    /// left returns [`NotPlaced`](Self::NotPlaced) instead.
    #[error("connectivity: {0}")]
    Connectivity(#[from] ConnectivityError),

    /// The order was not placed, and this is known rather than guessed: see [`NotPlacedReason`].
    ///
    /// Unlike [`Connectivity`](Self::Connectivity), it ends the order. Resubmitting the open
    /// request cannot place the order twice.
    #[error("not placed: {0}")]
    NotPlaced(NotPlacedReason),

    /// API-based error (rate limit, invalid instrument, order rejected, etc.).
    ///
    /// Retry semantics depend on the specific [`ApiError`] variant. Only
    /// [`ApiError::RateLimit`] is transient; other variants are not.
    #[error("order rejected: {0}")]
    Rejected(#[from] ApiError<AssetKey, InstrumentKey>),

    /// The order type is not supported by this connector, or the venue refused it as a type it
    /// does not take for this account or instrument.
    ///
    /// Non-transient — place a different order type. A connector usually returns this without
    /// sending the request (e.g., trailing stop orders on a connector that only supports
    /// market/limit); when the venue's own refusal says so, it can also come back after the round
    /// trip.
    #[error("unsupported order type: {0}")]
    UnsupportedOrderType(String),

    /// A quantity or price in the request has more precision than the venue accepts, so the
    /// client refused it without sending it.
    ///
    /// Non-transient — change the request. A client that refuses this way never rounds a value
    /// itself, because rounding would place a different order than the one requested; it
    /// documents how to read the venue's precision so the caller can round first.
    #[error("invalid precision: {0}")]
    InvalidPrecision(PrecisionViolation),

    /// A value in the request is outside the range the venue accepts for the instrument, so the
    /// client refused it without sending it.
    ///
    /// Non-transient — change the request. Unlike [`InvalidPrecision`](Self::InvalidPrecision),
    /// which says a value is badly formed, this says a well-formed value is too small or too
    /// large: below a minimum price, quantity or notional, or above a maximum. The error carries
    /// the limit that was broken, so the caller can resize the order. A client checks only the
    /// rules it has loaded (see [`OrderRules`](crate::rules::OrderRules)); a request that passes
    /// can still be rejected by the venue.
    #[error("out of bounds: {0}")]
    OutOfBounds(BoundsViolation),

    /// The request names a [`MarginEffect`] this client cannot honour, so it refused the order
    /// without sending it.
    ///
    /// Non-transient — drop the effect (`RequestOpen::margin_effect` of `None` takes the client's
    /// default) or send the order to a client that honours it. A client refuses rather than
    /// ignores an effect it cannot honour, because placing the order without it would borrow, or
    /// not repay, against the caller's intent. Which effects a client honours is on its type: a
    /// spot or cash account takes only [`NoSideEffect`](MarginEffect::NoSideEffect), a venue
    /// with account-level margin takes none.
    #[error("unsupported margin effect: {0:?}")]
    UnsupportedMarginEffect(MarginEffect),
}

/// How an order is known not to have been placed.
///
/// Carried by [`OrderError::NotPlaced`].
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
pub enum NotPlacedReason {
    /// The open request never left the client, because the connection failed before the send:
    /// refused, unresolved, or a closed channel to a simulated venue.
    ///
    /// A client returns this only where the failure provably came before the send. A failure it
    /// cannot place is [`OrderError::Connectivity`].
    #[error("not sent: {0}")]
    NotSent(ConnectivityError),

    /// The open's outcome was unknown, and the venue, asked about the order by its client order
    /// id several times since, does not know it.
    ///
    /// The engine's `ExecutionManager` reports this, after the lookups its policy sets out.
    #[error("unknown to the venue")]
    UnknownToVenue,
}

/// A value in an order request with more precision than the venue accepts, or that is not
/// positive.
///
/// Carried by [`OrderError::InvalidPrecision`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub struct PrecisionViolation {
    /// Which value of the request broke the rule.
    pub field: OrderField,
    /// The value as requested.
    pub value: Decimal,
    /// The rule it broke.
    pub limit: PrecisionLimit,
}

impl PrecisionViolation {
    /// The request's `field`, of `value`, breaks `limit`.
    pub fn new(field: OrderField, value: Decimal, limit: PrecisionLimit) -> Self {
        Self {
            field,
            value,
            limit,
        }
    }
}

impl fmt::Display for PrecisionViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            field,
            value,
            limit,
        } = self;
        write!(f, "{field} {value} ")?;
        match limit {
            PrecisionLimit::DecimalPlaces { max } => {
                write!(f, "has more than {max} decimal places")
            }
            PrecisionLimit::SignificantFigures { max } => {
                write!(
                    f,
                    "is not an integer and has more than {max} significant figures"
                )
            }
            PrecisionLimit::NotRepresentable => {
                write!(f, "cannot be sent exactly in the venue's number format")
            }
            PrecisionLimit::NotPositive => write!(f, "is not positive"),
            PrecisionLimit::NotOnGrid { step } => {
                write!(f, "is not a multiple of {step}")
            }
        }
    }
}

/// A value in an order request that is below a venue minimum or above a venue maximum.
///
/// Carried by [`OrderError::OutOfBounds`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub struct BoundsViolation {
    /// Which value of the request broke the bound.
    pub field: OrderField,
    /// Whether `value` is below the minimum or above the maximum.
    pub bound: Bound,
    /// The limit `value` broke.
    pub limit: Decimal,
    /// The value as requested. For [`OrderField::Notional`] it is the price times the quantity.
    pub value: Decimal,
}

impl BoundsViolation {
    /// The request's `field`, of `value`, is beyond the `bound` at `limit`.
    pub fn new(field: OrderField, bound: Bound, limit: Decimal, value: Decimal) -> Self {
        Self {
            field,
            bound,
            limit,
            value,
        }
    }
}

impl fmt::Display for BoundsViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            field,
            bound,
            limit,
            value,
        } = self;
        let (relation, name) = match bound {
            Bound::Min => ("below", "minimum"),
            Bound::Max => ("above", "maximum"),
        };
        write!(f, "{field} {value} is {relation} the {name} {limit}")
    }
}

/// Which end of a range a [`BoundsViolation`] broke.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub enum Bound {
    /// The value is below the minimum.
    Min,
    /// The value is above the maximum.
    Max,
}

/// A value of an order request, as named by a [`PrecisionViolation`] or [`BoundsViolation`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub enum OrderField {
    /// The order's quantity.
    Quantity,
    /// The order's limit price.
    Price,
    /// The price that triggers a stop or take-profit order.
    TriggerPrice,
    /// A trailing order's offset.
    TrailingOffset,
    /// The order's price times its quantity, in the quote asset. Never a request field of its
    /// own: only a [`BoundsViolation`] names it.
    Notional,
}

impl fmt::Display for OrderField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Quantity => "quantity",
            Self::Price => "price",
            Self::TriggerPrice => "trigger price",
            Self::TrailingOffset => "trailing offset",
            Self::Notional => "notional",
        })
    }
}

/// A venue's precision rule, as broken by a [`PrecisionViolation`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub enum PrecisionLimit {
    /// The value may have at most `max` decimal places.
    DecimalPlaces {
        /// The most decimal places allowed.
        max: u32,
    },
    /// The value may have at most `max` significant figures, unless it is an integer.
    SignificantFigures {
        /// The most significant figures allowed.
        max: u32,
    },
    /// The value cannot be sent exactly: the venue's client library converts it to a number
    /// format that would change it.
    NotRepresentable,
    /// The value is zero or negative. A quantity, price or trailing offset must be positive.
    NotPositive,
    /// The value is not a whole multiple of `step`: a price must sit on the instrument's tick
    /// grid and a quantity on its lot grid, counted from zero.
    NotOnGrid {
        /// The grid's step: the tick size for a price, the lot step for a quantity.
        step: Decimal,
    },
}

impl<AssetKey, InstrumentKey> OrderError<AssetKey, InstrumentKey> {
    /// Returns `true` if this error is likely transient and the operation
    /// may succeed if retried after a suitable backoff.
    ///
    /// # Transient errors
    /// - [`Connectivity`](Self::Connectivity) errors (timeout, socket, offline)
    /// - [`Rejected(ApiError::RateLimit)`](ApiError::RateLimit), though not before its
    ///   `retry_after`
    ///
    /// # Non-transient errors
    /// - Other [`Rejected`](Self::Rejected) errors (invalid instrument, insufficient balance,
    ///   refused borrow, etc.)
    /// - [`UnsupportedOrderType`](Self::UnsupportedOrderType),
    ///   [`InvalidPrecision`](Self::InvalidPrecision),
    ///   [`OutOfBounds`](Self::OutOfBounds) and
    ///   [`UnsupportedMarginEffect`](Self::UnsupportedMarginEffect)
    ///
    /// [`NotPlaced`](Self::NotPlaced) is transient when the request was not sent, since a later
    /// send may get through, and not when the venue does not know the order.
    pub fn is_transient(&self) -> bool {
        match self {
            Self::Connectivity(e) | Self::NotPlaced(NotPlacedReason::NotSent(e)) => {
                e.is_transient()
            }
            Self::NotPlaced(NotPlacedReason::UnknownToVenue) => false,
            Self::Rejected(ApiError::RateLimit { .. }) => true,
            Self::Rejected(_) => false,
            Self::UnsupportedOrderType(_)
            | Self::InvalidPrecision(_)
            | Self::OutOfBounds(_)
            | Self::UnsupportedMarginEffect(_) => false,
        }
    }

    /// Returns `true` if, as the answer to an open request, this error leaves the order's outcome
    /// unknown: the order may be live at the venue.
    ///
    /// Only [`Connectivity`](Self::Connectivity) does. Every other error says the order was not
    /// placed.
    pub fn is_outcome_unknown(&self) -> bool {
        matches!(self, Self::Connectivity(_))
    }
}

/// Why an account event stream ended.
///
/// Delivered in-band as the payload of
/// [`AccountEventKind::StreamTerminated`](crate::AccountEventKind::StreamTerminated) so that
/// stream death is a programmatic signal on the account feed rather than a log-only event. A
/// consumer can react (re-sync via REST, re-establish the stream, halt trading) according to its
/// own policy — the library reports *why* the stream ended without prescribing the response.
///
/// # Only in-band-deliverable terminations are represented
///
/// Every variant here is a termination the library can actually deliver to a consumer that is
/// still listening. A consumer-initiated drop is deliberately **not** a variant: by the time a
/// stream task observes the drop, the receiving half of the channel is already gone, so a
/// `StreamTerminated` send would be a guaranteed no-op. `StreamTerminated` therefore always means
/// "the stream died while you were still listening".
///
/// `#[non_exhaustive]` so venues may distinguish further termination causes in future without a
/// breaking change (e.g. a venue able to signal a graceful shutdown over a still-open channel).
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
pub enum StreamTerminationReason {
    /// A venue with built-in reconnection exhausted its retry budget and gave up.
    ///
    /// Emitted by venues that reconnect internally (e.g. Binance spot/margin, Alpaca) once the
    /// final attempt fails. Each client documents its budget. `last_error` is the most recent
    /// underlying failure; `attempts` is the number of reconnects tried before surrendering. The
    /// stream will not recover on its own — the consumer must re-establish it.
    #[error("reconnect budget exhausted after {attempts} attempts: {last_error}")]
    ReconnectBudgetExhausted {
        /// Number of reconnect attempts made before giving up.
        attempts: u32,
        /// The most recent underlying error that triggered surrender.
        last_error: String,
    },

    /// The stream ended on an unrecoverable error with no automatic recovery.
    ///
    /// Emitted by venues without library-managed reconnection — e.g. IBKR (the underlying
    /// subscription errored and the client does not retry), Hyperliquid (the SDK closed the
    /// subscription's channel; its own reconnection never gives up), or the mock exchange (its
    /// broadcast stream lagged past the buffer). The consumer is responsible for any
    /// re-establishment.
    #[error("unrecoverable stream error: {0}")]
    Error(String),

    /// The venue is refusing this client for exceeding its rate limits, for longer than the
    /// stream waits through in place.
    ///
    /// Emitted by venues that reconnect internally (Binance spot/margin) when a reconnect faces a
    /// rate-limit cooldown, or a ban, with more than a few seconds left. The stream ends at once
    /// rather than spend its reconnect budget against a venue that refuses every attempt, and
    /// reconnects that would lengthen a ban. `retry_after` is how long the cooldown had left: the
    /// earliest the consumer should re-establish the stream. Opening it sooner fails with
    /// [`ApiError::RateLimit`], unsent.
    ///
    /// Nothing that happens on the account until the stream is re-established reaches the
    /// consumer through this stream, as after any other termination: re-sync from the new
    /// stream's snapshot, and read fills of the gap with a trades query. An
    /// `ExecutionManager` re-opens the stream itself, no sooner than `retry_after`, and reports
    /// each refused attempt as a `ReinitFailed` carrying the time left.
    #[error("rate-limited by the venue; retry after {retry_after:?}")]
    RateLimited {
        /// How long the venue's cooldown had left when the stream ended.
        retry_after: Duration,
    },
}

/// Type alias for an [`AccountStreamInitError`] that is keyed on [`AssetNameExchange`] and
/// [`InstrumentNameExchange`] (yet to be indexed).
pub type UnindexedAccountStreamInitError =
    AccountStreamInitError<AssetNameExchange, InstrumentNameExchange>;

/// Why an attempt to initialise an account stream, its snapshot and its updates, failed.
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
pub enum AccountStreamInitError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
    /// The [`ExecutionClient`](crate::client::ExecutionClient) failed to fetch the account
    /// snapshot or to open the account stream. See [`ClientError::is_transient`].
    #[error("{0}")]
    Client(#[from] ClientError<AssetKey, InstrumentKey>),

    /// The account snapshot named an exchange, asset or instrument that is not indexed. This does
    /// not resolve on retry while the venue keeps reporting it.
    #[error("IndexError: {0}")]
    Index(#[from] IndexError),
}

impl<AssetKey, InstrumentKey> AccountStreamInitError<AssetKey, InstrumentKey> {
    /// The venue's minimum wait before the next attempt: `Some` only for a client's
    /// [`Api::RateLimit`](ApiError::RateLimit) whose venue sent a hint the client could read. See
    /// [`ClientError::retry_after`].
    pub fn retry_after(&self) -> Option<Duration> {
        match self {
            Self::Client(error) => error.retry_after(),
            Self::Index(_) => None,
        }
    }
}

/// A failed attempt to re-initialise an account stream after it ended.
///
/// Delivered in-band as the payload of
/// [`AccountEventKind::ReinitFailed`](crate::AccountEventKind::ReinitFailed), once per failed
/// attempt. Attempts continue with backoff; giving up is the consumer's decision.
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Constructor)]
pub struct AccountReinitFailure<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
    /// Consecutive failed attempts since the stream last initialised, starting at 1.
    pub attempt: u32,
    /// Why this attempt failed.
    pub error: AccountStreamInitError<AssetKey, InstrumentKey>,
}

/// Represents errors related to exchange, asset and instrument identifier key lookups.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
pub enum KeyError {
    /// Indicates an [`ExchangeId`] was encountered that was not indexed, so does not have a
    /// corresponding `ExchangeIndex`.
    #[error("ExchangeId: {0}")]
    ExchangeId(String),

    /// Indicates an [`AssetNameExchange`] was encountered that was not indexed, so does not have a
    /// corresponding [`AssetIndex`].
    #[error("AssetKey: {0}")]
    AssetKey(String),

    /// Indicates an [`InstrumentNameExchange`] was encountered that was no indexed, so does
    /// not have a corresponding [`InstrumentIndex`].
    #[error("InstrumentKey: {0}")]
    InstrumentKey(String),
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    #[test]
    fn a_rate_limit_carries_and_shows_the_venues_wait() {
        let hinted: UnindexedApiError = ApiError::rate_limited(Some(Duration::from_secs(7)));
        assert_eq!(hinted.retry_after(), Some(Duration::from_secs(7)));
        assert_eq!(hinted.to_string(), "rate limit exceeded; retry after 7s");
        assert!(UnindexedClientError::Api(hinted.clone()).is_transient());
        assert!(UnindexedOrderError::Rejected(hinted).is_transient());

        let unhinted: UnindexedApiError = ApiError::rate_limited(None);
        assert_eq!(unhinted.retry_after(), None);
        assert_eq!(unhinted.to_string(), "rate limit exceeded");

        let other: UnindexedApiError = ApiError::Unauthenticated("bad key".to_string());
        assert_eq!(other.retry_after(), None);
    }

    #[test]
    fn a_client_or_init_error_reads_the_wait_of_its_rate_limit() {
        let wait = Some(Duration::from_secs(7));
        let hinted = UnindexedClientError::Api(ApiError::rate_limited(wait));
        assert_eq!(hinted.retry_after(), wait);
        assert_eq!(
            UnindexedAccountStreamInitError::Client(hinted).retry_after(),
            wait
        );

        let unhinted = UnindexedClientError::Api(ApiError::rate_limited(None));
        assert_eq!(unhinted.retry_after(), None);
        let socket = UnindexedClientError::Connectivity(ConnectivityError::Timeout);
        assert_eq!(socket.retry_after(), None);
        assert_eq!(
            UnindexedAccountStreamInitError::Client(socket).retry_after(),
            None
        );
    }

    #[test]
    fn a_rate_limited_termination_shows_and_round_trips_its_wait() {
        let reason = StreamTerminationReason::RateLimited {
            retry_after: Duration::from_secs(120),
        };
        assert_eq!(
            reason.to_string(),
            "rate-limited by the venue; retry after 120s"
        );
        let json = serde_json::to_string(&reason).unwrap();
        assert_eq!(
            serde_json::from_str::<StreamTerminationReason>(&json).unwrap(),
            reason
        );
    }

    #[test]
    fn a_rate_limit_round_trips_through_serde() {
        for retry_after in [None, Some(Duration::from_millis(7_250))] {
            let error: UnindexedApiError = ApiError::rate_limited(retry_after);
            let json = serde_json::to_string(&error).unwrap();
            assert_eq!(
                serde_json::from_str::<UnindexedApiError>(&json).unwrap(),
                error,
                "{json}"
            );
        }
    }

    #[test]
    fn test_connectivity_error_is_transient() {
        assert!(ConnectivityError::Timeout.is_transient());
        assert!(ConnectivityError::Socket("connection refused".into()).is_transient());
        assert!(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot).is_transient());
    }

    #[test]
    fn test_client_error_is_transient_connectivity() {
        let err: ClientError = ClientError::Connectivity(ConnectivityError::Timeout);
        assert!(err.is_transient());

        let err: ClientError = ClientError::Connectivity(ConnectivityError::Socket("err".into()));
        assert!(err.is_transient());
    }

    #[test]
    fn test_client_error_is_transient_rate_limit() {
        let err: ClientError = ClientError::Api(ApiError::rate_limited(None));
        assert!(err.is_transient());
    }

    #[test]
    fn test_client_error_not_transient_api_errors() {
        let err: ClientError =
            ClientError::Api(ApiError::AssetInvalid(AssetIndex(0), "bad".into()));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError = ClientError::Api(ApiError::BalanceInsufficient(
            Some(AssetIndex(0)),
            "low".into(),
        ));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError = ClientError::Api(ApiError::InstrumentInvalid(
            InstrumentIndex(0),
            "bad".into(),
        ));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError = ClientError::Api(ApiError::OrderRejected("rejected".into()));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError = ClientError::Api(ApiError::OrderAlreadyCancelled);
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError = ClientError::Api(ApiError::OrderAlreadyFullyFilled);
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError =
            ClientError::Api(ApiError::Unauthenticated("invalid signature".into()));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError =
            ClientError::Api(ApiError::RequestRejected("-1127 More than 24 hours".into()));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError = ClientError::Api(ApiError::BorrowRejected(BorrowReject::new(
            BorrowRejectReason::InventoryUnavailable,
            Some("-3045".into()),
            "-3045 The system doesn't have enough asset now.".into(),
        )));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
    }

    #[test]
    fn borrow_rejected_shows_its_reason_and_code() {
        let coded: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
            BorrowRejectReason::BorrowDisabled,
            Some("40310000".into()),
            "account is not allowed to short".into(),
        ));
        assert_eq!(
            coded.to_string(),
            "borrow rejected: borrow disabled (code 40310000): account is not allowed to short"
        );

        let uncoded: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
            BorrowRejectReason::Other,
            None,
            "no borrow".into(),
        ));
        assert_eq!(uncoded.to_string(), "borrow rejected: other: no borrow");

        let short: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
            BorrowRejectReason::ShortSaleRestricted,
            None,
            "priced at the bid".into(),
        ));
        assert_eq!(
            short.to_string(),
            "borrow rejected: short sale restricted: priced at the bid"
        );
    }

    #[test]
    fn borrow_rejected_shows_what_is_available_only_when_known() {
        let reject = BorrowReject::new(
            BorrowRejectReason::InventoryUnavailable,
            None,
            "too little to lend".into(),
        );
        assert_eq!(reject.available, None);

        let reject = reject.with_available(dec!(2.5));
        assert_eq!(reject.available, Some(dec!(2.5)));
        assert_eq!(
            reject.to_string(),
            "inventory unavailable: too little to lend (2.5 available)"
        );
    }

    #[test]
    fn balance_insufficient_names_its_asset_only_when_known() {
        let named: UnindexedApiError =
            ApiError::BalanceInsufficient(Some(AssetNameExchange::new("BTC")), "low".to_string());
        assert_eq!(named.to_string(), "balance insufficient for asset BTC: low");

        let unnamed: UnindexedApiError = ApiError::BalanceInsufficient(None, "low".to_string());
        assert_eq!(unnamed.to_string(), "balance insufficient: low");
    }

    #[test]
    fn test_client_error_not_transient_task_failed() {
        let err: ClientError = ClientError::TaskFailed("task panicked".into());
        assert!(!err.is_transient());
    }

    #[test]
    fn test_client_error_not_transient_internal() {
        let err: ClientError = ClientError::Internal("unknown error".into());
        assert!(!err.is_transient());
    }

    #[test]
    fn test_client_error_not_transient_truncated() {
        let err: ClientError = ClientError::Truncated { fills_read: 5_000 };
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: ClientError = ClientError::TruncatedSnapshot { limit: 500 };
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
    }

    #[test]
    fn test_client_error_is_transient_exchange_offline() {
        let err: ClientError =
            ClientError::Connectivity(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot));
        assert!(err.is_transient(), "expected transient for {:?}", err);
    }

    #[test]
    fn test_order_error_is_transient_connectivity() {
        let err: UnindexedOrderError = OrderError::Connectivity(ConnectivityError::Timeout);
        assert!(err.is_transient(), "expected transient for {:?}", err);

        let err: UnindexedOrderError =
            OrderError::Connectivity(ConnectivityError::Socket("connection reset".into()));
        assert!(err.is_transient(), "expected transient for {:?}", err);

        let err: UnindexedOrderError =
            OrderError::Connectivity(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot));
        assert!(err.is_transient(), "expected transient for {:?}", err);
    }

    #[test]
    fn test_order_error_not_placed() {
        let not_sent: UnindexedOrderError = OrderError::NotPlaced(NotPlacedReason::NotSent(
            ConnectivityError::Socket("connection refused".into()),
        ));
        assert!(not_sent.is_transient(), "a later send may get through");
        assert!(!not_sent.is_outcome_unknown());

        let unknown: UnindexedOrderError = OrderError::NotPlaced(NotPlacedReason::UnknownToVenue);
        assert!(!unknown.is_transient());
        assert!(!unknown.is_outcome_unknown());
    }

    /// Only a connectivity error leaves an open's outcome unknown, and only as an open's answer
    /// does `OrderState` read it so.
    #[test]
    fn test_order_error_is_outcome_unknown() {
        use crate::order::state::{OrderState, UnindexedOrderState};

        let timeout: UnindexedOrderError = OrderError::Connectivity(ConnectivityError::Timeout);
        assert!(timeout.is_outcome_unknown());
        let rejected: UnindexedOrderError =
            OrderError::Rejected(ApiError::OrderRejected("no".into()));
        assert!(!rejected.is_outcome_unknown());

        let state: UnindexedOrderState = OrderState::inactive(timeout);
        assert!(state.is_outcome_unknown());
        assert!(state.is_failed());
        let state: UnindexedOrderState = OrderState::inactive(rejected);
        assert!(!state.is_outcome_unknown());
    }

    #[test]
    fn test_order_error_is_transient_rate_limit() {
        let err: UnindexedOrderError = OrderError::Rejected(ApiError::rate_limited(None));
        assert!(err.is_transient(), "expected transient for {:?}", err);
    }

    #[test]
    fn test_order_error_not_transient_api_errors() {
        let err: UnindexedOrderError =
            OrderError::Rejected(ApiError::OrderRejected("price out of range".into()));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: UnindexedOrderError = OrderError::Rejected(ApiError::OrderAlreadyCancelled);
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: UnindexedOrderError =
            OrderError::Rejected(ApiError::BorrowRejected(BorrowReject::new(
                BorrowRejectReason::NotShortable,
                None,
                "asset XYZ cannot be sold short".into(),
            )));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);

        let err: UnindexedOrderError = OrderError::Rejected(ApiError::BalanceInsufficient(
            Some(AssetNameExchange::from("BTC")),
            "insufficient".into(),
        ));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
    }
}