polyoxide-binance 0.45.0

Rust client library for Binance USDⓈ-M futures and spot market data and streams
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
//! Vocabulary and response rows for Binance spot.
//!
//! Prices and quantities are [`Decimal`], decoded from the decimal strings
//! Binance sends, so no value passes through an `f64`. Timestamps are Unix
//! milliseconds. Response rows carry symbols as `String`, taken as sent, so a
//! symbol [`Symbol::new`] would refuse never fails a whole response.

use rust_decimal::Decimal;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;

pub use crate::shared::symbol::{InvalidSymbol, Symbol};

/// `GET /api/v3/time`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ServerTime {
    /// Server clock, Unix milliseconds.
    pub server_time: u64,
}

/// `GET /api/v3/exchangeInfo`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ExchangeInfo {
    /// Always `UTC`.
    pub timezone: String,
    /// Server clock, Unix milliseconds.
    pub server_time: u64,
    /// The IP's request-weight, raw-request and order limits.
    pub rate_limits: Vec<RateLimit>,
    /// Exchange-wide filters.
    pub exchange_filters: Vec<Filter>,
    /// Every listed symbol, including ones that are not trading.
    pub symbols: Vec<SymbolInfo>,
    /// Smart order routing: the symbols an order for a base asset may be
    /// routed across. Absent when the host sends none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sors: Option<Vec<Sor>>,
}

/// One row of `exchangeInfo`'s `rateLimits`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RateLimit {
    /// `REQUEST_WEIGHT`, `RAW_REQUESTS` or `ORDERS`.
    pub rate_limit_type: String,
    /// `SECOND`, `MINUTE` or `DAY`.
    pub interval: String,
    /// Intervals per window.
    pub interval_num: u32,
    /// The limit per window.
    pub limit: u32,
}

/// One smart-order-routing entry in `exchangeInfo`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Sor {
    /// The base asset the routing applies to.
    pub base_asset: String,
    /// The symbols an order may be routed across.
    pub symbols: Vec<String>,
}

/// One symbol in `exchangeInfo`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SymbolInfo {
    /// The symbol, as Binance spells it.
    pub symbol: String,
    /// Trading, halted and so on.
    pub status: SymbolStatus,
    /// Base asset.
    pub base_asset: String,
    /// Decimal places of the base asset.
    pub base_asset_precision: u32,
    /// Quote asset.
    pub quote_asset: String,
    /// Decimal places of the quote asset, as Binance's older key spells it.
    pub quote_precision: u32,
    /// Decimal places of the quote asset.
    pub quote_asset_precision: u32,
    /// Decimal places of the base asset's commission.
    pub base_commission_precision: u32,
    /// Decimal places of the quote asset's commission.
    pub quote_commission_precision: u32,
    /// Order types the symbol accepts.
    pub order_types: Vec<String>,
    /// Whether iceberg orders are allowed.
    pub iceberg_allowed: bool,
    /// Whether OCO order lists are allowed.
    pub oco_allowed: bool,
    /// Whether OTO order lists are allowed.
    pub oto_allowed: bool,
    /// Whether OPO order lists are allowed. Every captured row carries the flag;
    /// it is optional so a row without it still decodes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub opo_allowed: Option<bool>,
    /// Whether a market order may name a quote quantity.
    pub quote_order_qty_market_allowed: bool,
    /// Whether trailing stops are allowed.
    pub allow_trailing_stop: bool,
    /// Whether cancel-replace is allowed.
    pub cancel_replace_allowed: bool,
    /// Whether order amendment is allowed. Every captured row carries the flag;
    /// it is optional so a row without it still decodes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub amend_allowed: Option<bool>,
    /// Whether pegged orders are allowed. Every captured row carries the flag;
    /// it is optional so a row without it still decodes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub peg_instructions_allowed: Option<bool>,
    /// Whether the symbol can be traded as spot.
    pub is_spot_trading_allowed: bool,
    /// Whether the symbol can be traded on margin.
    pub is_margin_trading_allowed: bool,
    /// Order filters.
    pub filters: Vec<Filter>,
    /// Permissions the symbol is open to (older key).
    pub permissions: Vec<String>,
    /// Permission sets: an account needs every permission of one set.
    pub permission_sets: Vec<Vec<String>>,
    /// The self-trade-prevention mode applied when an order names none.
    pub default_self_trade_prevention_mode: String,
    /// The self-trade-prevention modes an order may name.
    pub allowed_self_trade_prevention_modes: Vec<String>,
}

polyoxide_venue::open_enum! {
    /// A symbol's trading status, from `exchangeInfo`. The variants are the
    /// list in Binance's common definitions.
    pub enum SymbolStatus {
        Trading => "TRADING",
        Break => "BREAK",
        Halt => "HALT",
        PreTrading => "PRE_TRADING",
        PostTrading => "POST_TRADING",
        EndOfDay => "END_OF_DAY",
        AuctionMatch => "AUCTION_MATCH",
    }
}

/// Declares [`Filter`] and the private wire enum its serde goes through from
/// one table: each entry is a variant, its wire `filterType`, and its fields
/// (camelCase on the wire, a decimal string where `=> "..."` names the
/// `serde(with)`). Every field type is `Copy`, which the serializer relies on.
macro_rules! filters {
    ($(
        $(#[$vmeta:meta])*
        $variant:ident = $tag:literal {
            $( $field:ident : $ty:ty $(=> $with:literal)? ),* $(,)?
        }
    )+) => {
        /// An `exchangeInfo` filter, named after its wire `filterType`.
        ///
        /// A filter type this version does not know is kept whole in
        /// [`Filter::Other`], so a new one never fails the response. A known
        /// type that loses or retypes a field still fails; one that gains a
        /// field decodes without it, and the wire-agreement tests are what
        /// notice.
        #[derive(Debug, Clone, PartialEq)]
        #[non_exhaustive]
        pub enum Filter {
            $(
                $(#[$vmeta])*
                #[non_exhaustive]
                $variant { $( $field: $ty ),* },
            )+
            /// A filter type this version does not model.
            Other {
                /// The wire `filterType`.
                filter_type: String,
                /// The whole filter object, `filterType` included.
                raw: Value,
            },
        }

        /// The wire bodies of the known filters, which `Filter`'s serde goes
        /// through.
        #[derive(Serialize, Deserialize)]
        #[serde(tag = "filterType")]
        enum FilterWire {
            $(
                #[serde(rename = $tag, rename_all = "camelCase")]
                $variant { $( $(#[serde(with = $with)])? $field: $ty ),* },
            )+
        }

        impl FilterWire {
            /// Every `filterType` this version models.
            const KNOWN: &'static [&'static str] = &[$($tag),+];
        }

        impl From<FilterWire> for Filter {
            fn from(wire: FilterWire) -> Self {
                match wire {
                    $( FilterWire::$variant { $($field),* } => Self::$variant { $($field),* }, )+
                }
            }
        }

        impl<'de> Deserialize<'de> for Filter {
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let raw = Value::deserialize(deserializer)?;
                let filter_type = raw
                    .get("filterType")
                    .and_then(Value::as_str)
                    .ok_or_else(|| <D::Error as de::Error>::custom("a filter without a string filterType"))?
                    .to_owned();
                if !FilterWire::KNOWN.contains(&filter_type.as_str()) {
                    return Ok(Self::Other { filter_type, raw });
                }
                let wire: FilterWire =
                    serde_json::from_value(raw).map_err(<D::Error as de::Error>::custom)?;
                Ok(wire.into())
            }
        }

        impl Serialize for Filter {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                let wire = match self {
                    $( Self::$variant { $($field),* } => FilterWire::$variant { $($field: *$field),* }, )+
                    Self::Other { raw, .. } => return raw.serialize(serializer),
                };
                wire.serialize(serializer)
            }
        }
    };
}

filters! {
    /// `PRICE_FILTER`.
    PriceFilter = "PRICE_FILTER" {
        min_price: Decimal => "rust_decimal::serde::str",
        max_price: Decimal => "rust_decimal::serde::str",
        tick_size: Decimal => "rust_decimal::serde::str",
    }
    /// `PERCENT_PRICE_BY_SIDE`.
    PercentPriceBySide = "PERCENT_PRICE_BY_SIDE" {
        bid_multiplier_up: Decimal => "rust_decimal::serde::str",
        bid_multiplier_down: Decimal => "rust_decimal::serde::str",
        ask_multiplier_up: Decimal => "rust_decimal::serde::str",
        ask_multiplier_down: Decimal => "rust_decimal::serde::str",
        avg_price_mins: u32,
    }
    /// `LOT_SIZE`: limit orders.
    LotSize = "LOT_SIZE" {
        min_qty: Decimal => "rust_decimal::serde::str",
        max_qty: Decimal => "rust_decimal::serde::str",
        step_size: Decimal => "rust_decimal::serde::str",
    }
    /// `NOTIONAL`: the minimum and maximum order value.
    Notional = "NOTIONAL" {
        min_notional: Decimal => "rust_decimal::serde::str",
        apply_min_to_market: bool,
        max_notional: Decimal => "rust_decimal::serde::str",
        apply_max_to_market: bool,
        avg_price_mins: u32,
    }
    /// `ICEBERG_PARTS`.
    IcebergParts = "ICEBERG_PARTS" {
        limit: u32,
    }
    /// `MARKET_LOT_SIZE`: market orders.
    MarketLotSize = "MARKET_LOT_SIZE" {
        min_qty: Decimal => "rust_decimal::serde::str",
        max_qty: Decimal => "rust_decimal::serde::str",
        step_size: Decimal => "rust_decimal::serde::str",
    }
    /// `MAX_NUM_ORDERS`.
    MaxNumOrders = "MAX_NUM_ORDERS" {
        max_num_orders: u32,
    }
    /// `MAX_NUM_ALGO_ORDERS`.
    MaxNumAlgoOrders = "MAX_NUM_ALGO_ORDERS" {
        max_num_algo_orders: u32,
    }
    /// `MAX_POSITION`.
    MaxPosition = "MAX_POSITION" {
        max_position: Decimal => "rust_decimal::serde::str",
    }
    /// `TRAILING_DELTA`.
    TrailingDelta = "TRAILING_DELTA" {
        min_trailing_above_delta: u64,
        max_trailing_above_delta: u64,
        min_trailing_below_delta: u64,
        max_trailing_below_delta: u64,
    }
    /// `MAX_NUM_ORDER_AMENDS`.
    MaxNumOrderAmends = "MAX_NUM_ORDER_AMENDS" {
        max_num_order_amends: u32,
    }
    /// `MAX_NUM_ORDER_LISTS`.
    MaxNumOrderLists = "MAX_NUM_ORDER_LISTS" {
        max_num_order_lists: u32,
    }
}

pub use rows::{
    AggTrade, AvgPrice, BookTicker, Depth, Interval, Kline, Level, PriceTicker, Ticker24h, Trade,
};

/// The market routes' rows. Prices and quantities are `Decimal`, decoded from
/// the decimal strings Binance sends, so no value passes through an `f64`;
/// timestamps are Unix milliseconds. Where the wire uses one-letter keys
/// (`aggTrades`), fields take spelled-out names through serde renames.
mod rows {
    use std::fmt;

    use polyoxide_venue::positional::{drain, element, DecimalStr};
    use rust_decimal::Decimal;
    use serde::{
        de::{SeqAccess, Visitor},
        ser::SerializeSeq,
        Deserialize, Deserializer, Serialize, Serializer,
    };

    polyoxide_venue::wire_enum! {
        /// Kline width, for `klines`. This host takes `1s`, which the USDⓈ-M
        /// host refuses.
        pub enum Interval {
            /// One second.
            Second1 => "1s",
            /// One minute.
            Minute1 => "1m",
            /// Three minutes.
            Minute3 => "3m",
            /// Five minutes.
            Minute5 => "5m",
            /// Fifteen minutes.
            Minute15 => "15m",
            /// Thirty minutes.
            Minute30 => "30m",
            /// One hour.
            Hour1 => "1h",
            /// Two hours.
            Hour2 => "2h",
            /// Four hours.
            Hour4 => "4h",
            /// Six hours.
            Hour6 => "6h",
            /// Eight hours.
            Hour8 => "8h",
            /// Twelve hours.
            Hour12 => "12h",
            /// One day.
            Day1 => "1d",
            /// Three days.
            Day3 => "3d",
            /// One week.
            Week1 => "1w",
            /// One calendar month.
            Month1 => "1M",
        }
    }

    /// `GET /api/v3/depth`: an order book snapshot. It carries no time.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    #[non_exhaustive]
    pub struct Depth {
        /// Book update id of the snapshot.
        pub last_update_id: u64,
        /// Bids, best first.
        pub bids: Vec<Level>,
        /// Asks, best first.
        pub asks: Vec<Level>,
    }

    /// A price level, a `[price, quantity]` pair on the wire.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[non_exhaustive]
    pub struct Level {
        /// Price.
        pub price: Decimal,
        /// Quantity at the price.
        pub quantity: Decimal,
    }

    impl Level {
        /// A level from a price and a quantity.
        pub fn new(price: Decimal, quantity: Decimal) -> Self {
            Self { price, quantity }
        }
    }

    impl<'de> Deserialize<'de> for Level {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            struct LevelVisitor;

            impl<'de> Visitor<'de> for LevelVisitor {
                type Value = Level;

                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    f.write_str("a [price, quantity] array")
                }

                fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Level, A::Error> {
                    const WHAT: &str = "a [price, quantity] array";
                    let level = Level {
                        price: element::<DecimalStr, _>(&mut seq, 0, WHAT)?.0,
                        quantity: element::<DecimalStr, _>(&mut seq, 1, WHAT)?.0,
                    };
                    drain(&mut seq)?;
                    Ok(level)
                }
            }

            deserializer.deserialize_seq(LevelVisitor)
        }
    }

    impl Serialize for Level {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let mut seq = serializer.serialize_seq(Some(2))?;
            seq.serialize_element(&self.price.to_string())?;
            seq.serialize_element(&self.quantity.to_string())?;
            seq.end()
        }
    }

    /// One row of `GET /api/v3/trades`, oldest first.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    #[non_exhaustive]
    pub struct Trade {
        /// Trade id.
        pub id: u64,
        /// Price.
        #[serde(with = "rust_decimal::serde::str")]
        pub price: Decimal,
        /// Base-asset quantity.
        #[serde(with = "rust_decimal::serde::str")]
        pub qty: Decimal,
        /// Quote-asset quantity.
        #[serde(with = "rust_decimal::serde::str")]
        pub quote_qty: Decimal,
        /// Trade time.
        pub time: u64,
        /// Whether the buyer was the maker, so the taker sold.
        pub is_buyer_maker: bool,
        /// Whether the trade was the best price match.
        pub is_best_match: bool,
    }

    /// One row of `GET /api/v3/aggTrades`: trades at one price, taken by one
    /// order, merged.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[non_exhaustive]
    pub struct AggTrade {
        /// Aggregate trade id.
        #[serde(rename = "a")]
        pub id: u64,
        /// Price.
        #[serde(rename = "p", with = "rust_decimal::serde::str")]
        pub price: Decimal,
        /// Quantity.
        #[serde(rename = "q", with = "rust_decimal::serde::str")]
        pub quantity: Decimal,
        /// First trade id merged.
        #[serde(rename = "f")]
        pub first_trade_id: u64,
        /// Last trade id merged.
        #[serde(rename = "l")]
        pub last_trade_id: u64,
        /// Trade time.
        #[serde(rename = "T")]
        pub time: u64,
        /// Whether the buyer was the maker, so the taker sold.
        #[serde(rename = "m")]
        pub is_buyer_maker: bool,
        /// Whether the trade was the best price match.
        #[serde(rename = "M")]
        pub is_best_match: bool,
    }

    /// One candle of `GET /api/v3/klines`, a positional array on the wire.
    ///
    /// The wire sends a twelfth element Binance documents as "ignore"; it is
    /// dropped, and any further elements are tolerated.
    #[derive(Debug, Clone, PartialEq, Eq)]
    #[non_exhaustive]
    pub struct Kline {
        /// Candle start.
        pub open_time: u64,
        /// Open price.
        pub open: Decimal,
        /// High price.
        pub high: Decimal,
        /// Low price.
        pub low: Decimal,
        /// Close price.
        pub close: Decimal,
        /// Base-asset volume.
        pub volume: Decimal,
        /// Candle end, inclusive.
        pub close_time: u64,
        /// Quote-asset volume.
        pub quote_volume: Decimal,
        /// Trades in the candle.
        pub trade_count: u64,
        /// Base-asset volume bought by takers.
        pub taker_buy_base_volume: Decimal,
        /// Quote-asset volume bought by takers.
        pub taker_buy_quote_volume: Decimal,
    }

    impl<'de> Deserialize<'de> for Kline {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            struct KlineVisitor;

            impl<'de> Visitor<'de> for KlineVisitor {
                type Value = Kline;

                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    f.write_str("a kline array of at least 11 elements")
                }

                fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Kline, A::Error> {
                    const WHAT: &str = "a kline array of at least 11 elements";
                    let kline = Kline {
                        open_time: element(&mut seq, 0, WHAT)?,
                        open: element::<DecimalStr, _>(&mut seq, 1, WHAT)?.0,
                        high: element::<DecimalStr, _>(&mut seq, 2, WHAT)?.0,
                        low: element::<DecimalStr, _>(&mut seq, 3, WHAT)?.0,
                        close: element::<DecimalStr, _>(&mut seq, 4, WHAT)?.0,
                        volume: element::<DecimalStr, _>(&mut seq, 5, WHAT)?.0,
                        close_time: element(&mut seq, 6, WHAT)?,
                        quote_volume: element::<DecimalStr, _>(&mut seq, 7, WHAT)?.0,
                        trade_count: element(&mut seq, 8, WHAT)?,
                        taker_buy_base_volume: element::<DecimalStr, _>(&mut seq, 9, WHAT)?.0,
                        taker_buy_quote_volume: element::<DecimalStr, _>(&mut seq, 10, WHAT)?.0,
                    };
                    drain(&mut seq)?;
                    Ok(kline)
                }
            }

            deserializer.deserialize_seq(KlineVisitor)
        }
    }

    impl Serialize for Kline {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let mut seq = serializer.serialize_seq(Some(11))?;
            seq.serialize_element(&self.open_time)?;
            for value in [&self.open, &self.high, &self.low, &self.close, &self.volume] {
                seq.serialize_element(&value.to_string())?;
            }
            seq.serialize_element(&self.close_time)?;
            seq.serialize_element(&self.quote_volume.to_string())?;
            seq.serialize_element(&self.trade_count)?;
            seq.serialize_element(&self.taker_buy_base_volume.to_string())?;
            seq.serialize_element(&self.taker_buy_quote_volume.to_string())?;
            seq.end()
        }
    }

    /// `GET /api/v3/avgPrice`: the average price over the last `mins` minutes.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    #[non_exhaustive]
    pub struct AvgPrice {
        /// The window, in minutes.
        pub mins: u32,
        /// The average price.
        #[serde(with = "rust_decimal::serde::str")]
        pub price: Decimal,
        /// When the average was computed.
        pub close_time: u64,
    }

    /// `GET /api/v3/ticker/24hr`: rolling 24-hour statistics.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    #[non_exhaustive]
    pub struct Ticker24h {
        /// The pair.
        pub symbol: String,
        /// Last price less the open price.
        #[serde(with = "rust_decimal::serde::str")]
        pub price_change: Decimal,
        /// The change as a percentage.
        #[serde(with = "rust_decimal::serde::str")]
        pub price_change_percent: Decimal,
        /// Volume-weighted average price.
        #[serde(with = "rust_decimal::serde::str")]
        pub weighted_avg_price: Decimal,
        /// The previous day's close.
        #[serde(with = "rust_decimal::serde::str")]
        pub prev_close_price: Decimal,
        /// Last traded price.
        #[serde(with = "rust_decimal::serde::str")]
        pub last_price: Decimal,
        /// Last traded quantity.
        #[serde(with = "rust_decimal::serde::str")]
        pub last_qty: Decimal,
        /// Best bid price.
        #[serde(with = "rust_decimal::serde::str")]
        pub bid_price: Decimal,
        /// Quantity at the best bid.
        #[serde(with = "rust_decimal::serde::str")]
        pub bid_qty: Decimal,
        /// Best ask price.
        #[serde(with = "rust_decimal::serde::str")]
        pub ask_price: Decimal,
        /// Quantity at the best ask.
        #[serde(with = "rust_decimal::serde::str")]
        pub ask_qty: Decimal,
        /// Price 24 hours ago.
        #[serde(with = "rust_decimal::serde::str")]
        pub open_price: Decimal,
        /// Highest price.
        #[serde(with = "rust_decimal::serde::str")]
        pub high_price: Decimal,
        /// Lowest price.
        #[serde(with = "rust_decimal::serde::str")]
        pub low_price: Decimal,
        /// Base-asset volume.
        #[serde(with = "rust_decimal::serde::str")]
        pub volume: Decimal,
        /// Quote-asset volume.
        #[serde(with = "rust_decimal::serde::str")]
        pub quote_volume: Decimal,
        /// Window start.
        pub open_time: u64,
        /// Window end.
        pub close_time: u64,
        /// First trade id in the window, `-1` when there is none.
        pub first_id: i64,
        /// Last trade id in the window, `-1` when there is none.
        pub last_id: i64,
        /// Trades in the window.
        pub count: u64,
    }

    /// `GET /api/v3/ticker/price`: the last price.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[non_exhaustive]
    pub struct PriceTicker {
        /// The pair.
        pub symbol: String,
        /// Last traded price.
        #[serde(with = "rust_decimal::serde::str")]
        pub price: Decimal,
    }

    /// `GET /api/v3/ticker/bookTicker`: the best bid and ask. It carries no
    /// time.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    #[non_exhaustive]
    pub struct BookTicker {
        /// The pair.
        pub symbol: String,
        /// Best bid price.
        #[serde(with = "rust_decimal::serde::str")]
        pub bid_price: Decimal,
        /// Quantity at the best bid.
        #[serde(with = "rust_decimal::serde::str")]
        pub bid_qty: Decimal,
        /// Best ask price.
        #[serde(with = "rust_decimal::serde::str")]
        pub ask_price: Decimal,
        /// Quantity at the best ask.
        #[serde(with = "rust_decimal::serde::str")]
        pub ask_qty: Decimal,
    }
}

#[cfg(test)]
mod tests {
    use polyoxide_test_support::{agreement, fixtures};

    use super::*;

    fn text(name: &str) -> String {
        fixtures!("spot/rest").text(name)
    }

    #[test]
    fn the_exchange_info_capture_agrees_with_its_types() {
        let text = text("exchange_info");
        let diff = agreement::compare::<ExchangeInfo>("exchange_info", &text);
        assert!(
            diff.unmodelled.is_empty(),
            "the server sent {:?}, which the types do not model",
            diff.unmodelled
        );
        assert!(
            diff.invented.is_empty(),
            "the types emit {:?}, which the server did not send",
            diff.invented
        );
    }

    #[test]
    fn every_symbol_and_filter_serializes_back_to_what_the_server_sent() {
        let text = text("exchange_info");
        let raw: Value = serde_json::from_str(&text).unwrap();
        let info: ExchangeInfo = serde_json::from_str(&text).unwrap();
        assert_eq!(
            serde_json::to_value(&info.rate_limits).unwrap(),
            raw["rateLimits"]
        );
        assert_eq!(
            serde_json::to_value(&info.exchange_filters).unwrap(),
            raw["exchangeFilters"]
        );
        let wire = raw["symbols"].as_array().unwrap();
        assert_eq!(info.symbols.len(), wire.len());
        for (symbol, sent) in info.symbols.iter().zip(wire) {
            assert_eq!(
                serde_json::to_value(symbol).unwrap(),
                *sent,
                "{}",
                symbol.symbol
            );
        }
    }

    #[test]
    fn the_capture_holds_the_cases_the_types_exist_for() {
        let info: ExchangeInfo = serde_json::from_str(&text("exchange_info")).unwrap();
        assert!(info.symbols.len() >= 2, "BTCUSDT and a non-trading symbol");
        assert!(
            info.symbols
                .iter()
                .any(|s| s.symbol == "BTCUSDT" && s.status == SymbolStatus::Trading),
            "BTCUSDT, trading"
        );
        assert!(
            info.symbols
                .iter()
                .any(|s| s.status != SymbolStatus::Trading),
            "a symbol that is not trading"
        );
        // An unknown value would land in `Other` and decode fine; failing here
        // is how a value Binance adds gets modelled instead of passing silently.
        let unnamed: Vec<_> = info
            .symbols
            .iter()
            .filter(|s| matches!(s.status, SymbolStatus::Other(_)))
            .map(|s| (&s.symbol, &s.status))
            .collect();
        assert!(
            unnamed.is_empty(),
            "statuses the enum does not name: {unnamed:?}"
        );
        // The same for filters: a misspelled tag would turn a PRICE_FILTER into
        // `Other`, and every other test would still pass.
        let unnamed: Vec<&Filter> = info
            .symbols
            .iter()
            .flat_map(|s| &s.filters)
            .chain(&info.exchange_filters)
            .filter(|f| matches!(f, Filter::Other { .. }))
            .collect();
        assert!(
            unnamed.is_empty(),
            "filter types Filter does not name, add them to `filters!`: {unnamed:?}"
        );
    }

    #[test]
    fn the_captured_btcusdt_filters_decode_to_their_values() {
        let text = text("exchange_info");
        let raw: Value = serde_json::from_str(&text).unwrap();
        let info: ExchangeInfo = serde_json::from_str(&text).unwrap();
        let btc = info.symbols.iter().find(|s| s.symbol == "BTCUSDT").unwrap();
        let wire = raw["symbols"]
            .as_array()
            .unwrap()
            .iter()
            .find(|s| s["symbol"] == "BTCUSDT")
            .unwrap();
        let sent = |filter_type: &str, key: &str| -> String {
            wire["filters"]
                .as_array()
                .unwrap()
                .iter()
                .find(|f| f["filterType"] == filter_type)
                .unwrap_or_else(|| panic!("no {filter_type}"))[key]
                .as_str()
                .unwrap()
                .to_owned()
        };
        let price = btc
            .filters
            .iter()
            .find_map(|f| match f {
                Filter::PriceFilter { tick_size, .. } => Some(*tick_size),
                _ => None,
            })
            .expect("a PRICE_FILTER");
        assert_eq!(price.to_string(), sent("PRICE_FILTER", "tickSize"));
        let lot = btc
            .filters
            .iter()
            .find_map(|f| match f {
                Filter::LotSize { step_size, .. } => Some(*step_size),
                _ => None,
            })
            .expect("a LOT_SIZE");
        assert_eq!(lot.to_string(), sent("LOT_SIZE", "stepSize"));
        let market = btc
            .filters
            .iter()
            .find_map(|f| match f {
                Filter::MarketLotSize { step_size, .. } => Some(*step_size),
                _ => None,
            })
            .expect("a MARKET_LOT_SIZE");
        assert_eq!(market.to_string(), sent("MARKET_LOT_SIZE", "stepSize"));
        let notional = btc
            .filters
            .iter()
            .find_map(|f| match f {
                Filter::Notional { min_notional, .. } => Some(*min_notional),
                _ => None,
            })
            .expect("a NOTIONAL");
        assert_eq!(notional.to_string(), sent("NOTIONAL", "minNotional"));
    }

    #[test]
    fn the_time_capture_agrees_with_its_type() {
        let text = text("time");
        let diff = agreement::compare::<ServerTime>("time", &text);
        assert!(diff.unmodelled.is_empty(), "{:?}", diff.unmodelled);
        assert!(diff.invented.is_empty(), "{:?}", diff.invented);
        let time: ServerTime = serde_json::from_str(&text).unwrap();
        assert!(time.server_time > 1_790_000_000_000);
    }

    #[test]
    fn an_unknown_filter_type_is_kept_whole() {
        let raw = serde_json::json!({"filterType": "A_FILTER_FROM_THE_FUTURE", "limit": 7});
        let filter: Filter = serde_json::from_value(raw.clone()).unwrap();
        assert!(matches!(
            &filter,
            Filter::Other { filter_type, raw: kept }
                if filter_type == "A_FILTER_FROM_THE_FUTURE" && *kept == raw
        ));
        assert_eq!(serde_json::to_value(&filter).unwrap(), raw);
    }

    #[test]
    fn a_known_filter_that_loses_a_field_fails() {
        let raw = serde_json::json!({"filterType": "PRICE_FILTER", "minPrice": "0.01000000"});
        assert!(serde_json::from_value::<Filter>(raw).is_err());
    }

    #[test]
    fn a_filter_without_a_type_fails() {
        let raw = serde_json::json!({"minPrice": "0.01000000"});
        let err = serde_json::from_value::<Filter>(raw).unwrap_err();
        assert!(err.to_string().contains("filterType"), "{err}");
    }

    #[test]
    fn a_status_keeps_an_unknown_spelling() {
        assert_eq!(SymbolStatus::from_wire("TRADING"), SymbolStatus::Trading);
        assert_eq!(
            SymbolStatus::from_wire("PRE_TRADING"),
            SymbolStatus::PreTrading
        );
        let unknown = SymbolStatus::from_wire("A_NEW_STATE");
        assert_eq!(unknown, SymbolStatus::Other("A_NEW_STATE".into()));
        assert_eq!(unknown.as_str(), "A_NEW_STATE");
    }

    #[test]
    fn the_status_spellings_are_binance_s() {
        let table = [
            (SymbolStatus::Trading, "TRADING"),
            (SymbolStatus::Break, "BREAK"),
            (SymbolStatus::Halt, "HALT"),
            (SymbolStatus::PreTrading, "PRE_TRADING"),
            (SymbolStatus::PostTrading, "POST_TRADING"),
            (SymbolStatus::EndOfDay, "END_OF_DAY"),
            (SymbolStatus::AuctionMatch, "AUCTION_MATCH"),
        ];
        for (status, wire) in table {
            assert_eq!(status.as_str(), wire);
        }
    }
}