rustrade-execution 0.10.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
//! 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 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;
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)
    ///
    /// # 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,
        }
    }
}

/// 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.
    /// Some exchanges provide a `Retry-After` header or similar hint; the client
    /// may incorporate this into internal retry logic before surfacing this error.
    ///
    /// Transient — retry with backoff. Typical backoff is 10-60 seconds, but
    /// respect exchange-specific guidance if available.
    #[error("rate limit exceeded")]
    RateLimit,

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

/// 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.
    #[error("connectivity: {0}")]
    Connectivity(#[from] ConnectivityError),

    /// 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.
    ///
    /// Non-transient — the connector does not support this order type (e.g.,
    /// trailing stop orders on a connector that only supports market/limit).
    #[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 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"),
        }
    }
}

/// A value of an order request, as named by a [`PrecisionViolation`].
#[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,
}

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

/// 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,
}

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)
    ///
    /// # Non-transient errors
    /// - Other [`Rejected`](Self::Rejected) errors (invalid instrument, insufficient balance, etc.)
    /// - [`UnsupportedOrderType`](Self::UnsupportedOrderType) and
    ///   [`InvalidPrecision`](Self::InvalidPrecision)
    pub fn is_transient(&self) -> bool {
        match self {
            Self::Connectivity(e) => e.is_transient(),
            Self::Rejected(ApiError::RateLimit) => true,
            Self::Rejected(_) => false,
            Self::UnsupportedOrderType(_) | Self::InvalidPrecision(_) => false,
        }
    }
}

/// 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. `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's internal
    /// reconnection gave up and closed the channel), 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),
}

/// 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),
}

/// 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)]
mod tests {
    use super::*;

    #[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::RateLimit);
        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);
    }

    #[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_is_transient_rate_limit() {
        let err: UnindexedOrderError = OrderError::Rejected(ApiError::RateLimit);
        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::BalanceInsufficient(
            Some(AssetNameExchange::from("BTC")),
            "insufficient".into(),
        ));
        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
    }
}