cexy 0.1.0-dev.16

Official Rust SDK for the CEXY.io exchange API (REST + WebSocket)
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
//! The REST services: public market data, account, exports, wallet reads, trading and pools.

use std::time::Duration;

use crate::amount::check_amounts;
use crate::batch::{
    BatchCancelResult, BatchOrderInput, BatchOrderOutcome, BatchPlaceResult, CancelEntryOutcome,
    CancelOutcome, PlaceOutcome, cancel_from_result, cancel_matches, cancel_result, check_cancel,
    check_place, needs_lookup, new_client_order_id, place_from_result, place_matches, place_result,
};
use crate::client::Client;
use crate::error::{ApiError, Error, ErrorCategory, Result};
use crate::models_gen::*;
use crate::operations_gen::*;
use crate::pagination::{HistoryPage, ItemStream, Page, paginate, paginate_history};
use crate::transport::{Attempt, Call, decode, decode_data, new_id};

fn q<P>(
    params: Option<&P>,
    f: fn(&P) -> Vec<(&'static str, String)>,
) -> Vec<(&'static str, String)> {
    params.map(f).unwrap_or_default()
}

impl Client {
    pub(crate) async fn page<T: serde::de::DeserializeOwned>(&self, c: Call) -> Result<Page<T>> {
        let op = c.op;
        let raw = self.t.request(c, &self.resolved()).await?;
        decode(op, &raw)
    }

    pub(crate) async fn text(&self, mut c: Call) -> Result<String> {
        c.text = true;
        let raw = self.t.request(c, &self.resolved()).await?;
        Ok(String::from_utf8_lossy(&raw.body).into_owned())
    }
}

/// Defines `all_*`: every item of a listing, following the cursor.
macro_rules! all_items {
    ($(#[$m:meta])* $name:ident, $page:ident, $params:ty, $item:ty) => {
        $(#[$m])*
        /// `max_items` stops the stream after that many items in total.
        pub fn $name(&self, params: Option<&$params>, max_items: Option<usize>) -> ItemStream<'a, $item> {
            let base = params.cloned().unwrap_or_default();
            let this = Self { c: self.c };
            paginate(base.cursor.clone(), max_items, move |cursor| {
                let mut p = base.clone();
                p.cursor = cursor;
                async move { this.$page(Some(&p)).await }
            })
        }
    };
}

// ---------------------------------------------------------------------------------------
// Public market data (no credentials)
// ---------------------------------------------------------------------------------------

/// Markets, tickers, order books, public trades and candles.
#[derive(Clone, Copy)]
pub struct Markets<'a> {
    pub(crate) c: &'a Client,
}

impl<'a> Markets<'a> {
    /// Every market with its current ticker.
    pub async fn list(&self) -> Result<Vec<Market>> {
        self.c.get(Call::new(OperationId::ListMarkets)).await
    }

    /// One market, such as `"BTC/USDT"`.
    pub async fn get(&self, symbol: &str) -> Result<Market> {
        self.c
            .get(Call::new(OperationId::GetMarket).path("symbol", symbol))
            .await
    }

    /// An order-book snapshot aggregated by price, with the realtime sequence it is current as
    /// of. To follow a book live, use [`crate::WebSocket::order_book`], which applies the sync rules.
    pub async fn order_book(
        &self,
        symbol: &str,
        params: Option<&GetOrderBookParams>,
    ) -> Result<OrderBook> {
        let c = Call::new(OperationId::GetOrderBook)
            .path("symbol", symbol)
            .query(q(params, GetOrderBookParams::query));
        self.c.get(c).await
    }

    /// One page of recent public trades.
    pub async fn trades(
        &self,
        symbol: &str,
        params: Option<&GetMarketTradesParams>,
    ) -> Result<Page<PublicTrade>> {
        let c = Call::new(OperationId::GetMarketTrades)
            .path("symbol", symbol)
            .query(q(params, GetMarketTradesParams::query));
        self.c.page(c).await
    }

    /// Every public trade of a market, following the cursor. `max_items` stops the stream after
    /// that many items in total.
    pub fn all_trades(
        &self,
        symbol: &'a str,
        params: Option<&GetMarketTradesParams>,
        max_items: Option<usize>,
    ) -> ItemStream<'a, PublicTrade> {
        let base = params.cloned().unwrap_or_default();
        let this = *self;
        paginate(base.cursor.clone(), max_items, move |cursor| {
            let mut p = base.clone();
            p.cursor = cursor;
            async move { this.trades(symbol, Some(&p)).await }
        })
    }

    /// OHLCV candles; `params.interval` is required.
    pub async fn candles(&self, symbol: &str, params: &GetCandlesParams) -> Result<Vec<Candle>> {
        let c = Call::new(OperationId::GetCandles)
            .path("symbol", symbol)
            .query(params.query());
        self.c.get(c).await
    }
}

/// The asset catalogue.
pub struct Assets<'a> {
    pub(crate) c: &'a Client,
}

impl Assets<'_> {
    /// Every asset.
    pub async fn list(&self) -> Result<Vec<Asset>> {
        self.c.get(Call::new(OperationId::ListAssets)).await
    }

    /// One asset.
    pub async fn get(&self, symbol: &str) -> Result<Asset> {
        self.c
            .get(Call::new(OperationId::GetAsset).path("symbol", symbol))
            .await
    }
}

/// Blockchain networks.
pub struct Networks<'a> {
    pub(crate) c: &'a Client,
}

impl Networks<'_> {
    /// Every network.
    pub async fn list(&self) -> Result<Vec<Network>> {
        self.c.get(Call::new(OperationId::ListNetworks)).await
    }
}

/// Fee schedules.
pub struct Fees<'a> {
    pub(crate) c: &'a Client,
}

impl Fees<'_> {
    /// The fee schedules (maker and taker rates by tier).
    pub async fn list(&self) -> Result<Vec<FeeSchedule>> {
        self.c.get(Call::new(OperationId::ListFeeSchedules)).await
    }
}

/// Liquidity pools. Join and exit need an API key with the trade scope.
pub struct Pools<'a> {
    pub(crate) c: &'a Client,
}

impl Pools<'_> {
    /// Every pool.
    pub async fn list(&self) -> Result<Vec<Pool>> {
        self.c.get(Call::new(OperationId::ListPools)).await
    }

    /// One pool.
    pub async fn get(&self, symbol: &str) -> Result<Pool> {
        self.c
            .get(Call::new(OperationId::GetPool).path("symbol", symbol))
            .await
    }

    /// Adds liquidity. Amounts are decimal strings. The Idempotency-Key (generated, or set with
    /// [`crate::CallOptions::idempotency_key`]) makes retries safe.
    pub async fn join(&self, symbol: &str, req: &JoinPoolRequest) -> Result<JoinPoolResult> {
        check_amounts(
            "pools.join",
            &[
                ("base_amount", Some(&req.base_amount)),
                ("quote_amount", Some(&req.quote_amount)),
                (
                    "max_ratio_deviation_percent",
                    req.max_ratio_deviation_percent.as_ref(),
                ),
            ],
        )?;
        self.c
            .get(
                Call::new(OperationId::JoinPool)
                    .path("symbol", symbol)
                    .json(req)?,
            )
            .await
    }

    /// Removes liquidity. The Idempotency-Key makes retries safe.
    pub async fn exit(&self, symbol: &str, req: &ExitPoolRequest) -> Result<ExitPoolResult> {
        check_amounts("pools.exit", &[("shares", Some(&req.shares))])?;
        self.c
            .get(
                Call::new(OperationId::ExitPool)
                    .path("symbol", symbol)
                    .json(req)?,
            )
            .await
    }
}

// ---------------------------------------------------------------------------------------
// Private (API key; read scope unless stated)
// ---------------------------------------------------------------------------------------

/// Balances, ledger, notifications, sub-accounts and API keys.
#[derive(Clone, Copy)]
pub struct Account<'a> {
    pub(crate) c: &'a Client,
}

impl<'a> Account<'a> {
    /// The id of the account this API key belongs to (the same hex as the WebSocket's
    /// `authenticated` user id). [`crate::WebSocket::live_balances`] uses it to check that REST
    /// snapshots and WebSocket events belong to the same account.
    pub async fn id(&self) -> Result<String> {
        let r: crate::models_gen::AccountId =
            self.c.get(Call::new(OperationId::GetAccountId)).await?;
        Ok(r.user_id)
    }

    /// Every balance.
    ///
    /// [`Balance::held_incoming`] lists incoming internal transfers still held. Their sum is
    /// ALREADY INCLUDED in `locked`: never add them to `locked` or `total` again. At most 100
    /// entries, soonest `available_at` first (millisecond precision), with no sender identity. An
    /// entry disappears once the transfer is released (its amount moves to `available`) or
    /// cancelled by the exchange. It is empty, never missing, when a server omits the field.
    pub async fn balances(&self) -> Result<Vec<Balance>> {
        self.c.get(Call::new(OperationId::ListBalances)).await
    }

    /// The balance of one asset. See [`Account::balances`] for `held_incoming`.
    pub async fn balance(&self, asset: &str) -> Result<Balance> {
        self.c
            .get(Call::new(OperationId::GetBalance).path("asset", asset))
            .await
    }

    /// One page of ledger entries.
    pub async fn ledger(&self, params: Option<&GetLedgerParams>) -> Result<Page<LedgerEntry>> {
        self.c
            .page(Call::new(OperationId::GetLedger).query(q(params, GetLedgerParams::query)))
            .await
    }

    all_items!(
        /// Every ledger entry.
        all_ledger, ledger, GetLedgerParams, LedgerEntry
    );

    /// One page of notifications.
    pub async fn notifications(
        &self,
        params: Option<&ListNotificationsParams>,
    ) -> Result<Page<Notification>> {
        self.c
            .page(
                Call::new(OperationId::ListNotifications)
                    .query(q(params, ListNotificationsParams::query)),
            )
            .await
    }

    all_items!(
        /// Every notification.
        all_notifications, notifications, ListNotificationsParams, Notification
    );

    /// The sub-accounts.
    pub async fn sub_accounts(&self) -> Result<Vec<SubAccount>> {
        self.c.get(Call::new(OperationId::ListSubAccounts)).await
    }

    /// A sub-account's balances, read by its PARENT account: the same shape as
    /// [`Account::balances`] (zero balances omitted), including `held_incoming`, whose sum is
    /// already inside `locked`. The server currently returns them ordered by asset symbol; don't
    /// rely on the order. An id that is not one of the caller's sub-accounts (or a call made with
    /// the sub-account's own key) is an API error in
    /// [`ErrorCategory::NotFound`](crate::ErrorCategory::NotFound) and is not retried; a
    /// sub-account's own key reads its balances with [`Account::balances`]. A malformed id gets
    /// 400 ([`ErrorCategory::Validation`](crate::ErrorCategory::Validation)); a key without the
    /// read scope gets 403 `FORBIDDEN` ([`ErrorCategory::Forbidden`](crate::ErrorCategory::Forbidden)).
    /// `id` must be non-empty and not `"."` or `".."` (a config error before any request); it is
    /// sent as one URL path segment.
    pub async fn sub_account_balances(&self, id: &str) -> Result<Vec<Balance>> {
        self.c
            .get(Call::new(OperationId::SubAccountBalances).path("id", id))
            .await
    }

    /// Your API keys (metadata only; secrets are never returned).
    pub async fn api_keys(&self) -> Result<Vec<ApiKey>> {
        self.c.get(Call::new(OperationId::ListApiKeys)).await
    }
}

/// CSV exports. Each method returns the CSV text.
pub struct Exports<'a> {
    pub(crate) c: &'a Client,
}

impl Exports<'_> {
    async fn export(&self, op: OperationId, params: Option<&ExportParams>) -> Result<String> {
        self.c
            .text(Call::new(op).query(q(params, ExportParams::query)))
            .await
    }
    /// Deposits as CSV.
    pub async fn deposits(&self, params: Option<&ExportParams>) -> Result<String> {
        self.export(OperationId::ExportDeposits, params).await
    }
    /// The ledger as CSV.
    pub async fn ledger(&self, params: Option<&ExportParams>) -> Result<String> {
        self.export(OperationId::ExportLedger, params).await
    }
    /// Orders as CSV.
    pub async fn orders(&self, params: Option<&ExportParams>) -> Result<String> {
        self.export(OperationId::ExportOrders, params).await
    }
    /// Your trades as CSV.
    pub async fn trades(&self, params: Option<&ExportParams>) -> Result<String> {
        self.export(OperationId::ExportTrades, params).await
    }
    /// Withdrawals as CSV.
    pub async fn withdrawals(&self, params: Option<&ExportParams>) -> Result<String> {
        self.export(OperationId::ExportWithdrawals, params).await
    }
}

/// Wallet reads. API keys can never withdraw or transfer; there are no such methods.
#[derive(Clone, Copy)]
pub struct Wallet<'a> {
    pub(crate) c: &'a Client,
}

impl<'a> Wallet<'a> {
    /// One page of deposits.
    pub async fn deposits(&self, params: Option<&ListDepositsParams>) -> Result<Page<Deposit>> {
        self.c
            .page(Call::new(OperationId::ListDeposits).query(q(params, ListDepositsParams::query)))
            .await
    }

    all_items!(
        /// Every deposit.
        all_deposits, deposits, ListDepositsParams, Deposit
    );

    /// One deposit.
    pub async fn deposit(&self, deposit_id: &str) -> Result<Deposit> {
        self.c
            .get(Call::new(OperationId::GetDeposit).path("deposit_id", deposit_id))
            .await
    }

    /// One page of withdrawals.
    pub async fn withdrawals(
        &self,
        params: Option<&ListWithdrawalsParams>,
    ) -> Result<Page<Withdrawal>> {
        self.c
            .page(
                Call::new(OperationId::ListWithdrawals)
                    .query(q(params, ListWithdrawalsParams::query)),
            )
            .await
    }

    all_items!(
        /// Every withdrawal.
        all_withdrawals, withdrawals, ListWithdrawalsParams, Withdrawal
    );

    /// One withdrawal.
    pub async fn withdrawal(&self, withdrawal_id: &str) -> Result<Withdrawal> {
        self.c
            .get(Call::new(OperationId::GetWithdrawal).path("withdrawal_id", withdrawal_id))
            .await
    }

    /// The saved withdrawal addresses.
    pub async fn withdrawal_addresses(&self) -> Result<Vec<WithdrawalAddress>> {
        self.c
            .get(Call::new(OperationId::ListWithdrawalAddresses))
            .await
    }

    /// Your deposit address for an asset on a network.
    ///
    /// Side effect: the first call for an asset and network CREATES the address, and it is
    /// permanent; later calls return the same address. Always send the memo too when the
    /// response has one, or the deposit may be unrecoverable.
    pub async fn deposit_address(&self, params: &DepositAddressParams) -> Result<DepositAddress> {
        if params.asset.is_empty() || params.network.is_empty() {
            return Err(Error::config(
                "wallet.deposit_address: asset and network are required",
            ));
        }
        self.c
            .get(Call::new(OperationId::DepositAddress).query(params.query()))
            .await
    }
}

// ---------------------------------------------------------------------------------------
// Trading
// ---------------------------------------------------------------------------------------

/// Orders and your trades. Placing and cancelling need the trade scope.
#[derive(Clone, Copy)]
pub struct Trading<'a> {
    pub(crate) c: &'a Client,
}

/// What [`Trading::place_order`] returns.
#[derive(Debug, Clone, PartialEq)]
pub struct PlaceOrderResult {
    /// The order and anything it executed immediately.
    pub response: PlaceOrderResponse,
    /// The `client_order_id` that was sent (generated when you did not set one).
    pub client_order_id: String,
    /// True when the POST failed ambiguously and the order was then found by
    /// `client_order_id`. `response.fills` is empty then; use `trades` for the executions.
    pub recovered: bool,
}

impl<'a> Trading<'a> {
    /// Open orders, optionally filtered by market or status.
    pub async fn open_orders(&self, params: Option<&ListOpenOrdersParams>) -> Result<Vec<Order>> {
        self.c
            .get(
                Call::new(OperationId::ListOpenOrders)
                    .query(q(params, ListOpenOrdersParams::query)),
            )
            .await
    }

    /// One order.
    pub async fn order(&self, order_id: &str) -> Result<Order> {
        self.c
            .get(Call::new(OperationId::GetOrder).path("order_id", order_id))
            .await
    }

    /// The order with your `client_order_id`.
    pub async fn order_by_client_id(&self, client_order_id: &str) -> Result<Order> {
        self.c
            .get(
                Call::new(OperationId::GetOrderByClientId).path("client_order_id", client_order_id),
            )
            .await
    }

    /// One page of past orders.
    pub async fn order_history(&self, params: Option<&OrderHistoryParams>) -> Result<Page<Order>> {
        self.c
            .page(Call::new(OperationId::OrderHistory).query(q(params, OrderHistoryParams::query)))
            .await
    }

    all_items!(
        /// Every past order.
        all_order_history, order_history, OrderHistoryParams, Order
    );

    /// One page of your executions.
    pub async fn trades(&self, params: Option<&TradeHistoryParams>) -> Result<Page<Fill>> {
        self.c
            .page(Call::new(OperationId::TradeHistory).query(q(params, TradeHistoryParams::query)))
            .await
    }

    all_items!(
        /// Every execution.
        all_trades, trades, TradeHistoryParams, Fill
    );

    /// Places a REAL order (needs the trade scope). Amounts are decimal strings.
    ///
    /// Retry safety rests on `client_order_id` (a UUID is generated when absent): it is unique
    /// per account, and the server refuses a repeat before any funds move. The server does NOT
    /// honour Idempotency-Key on orders. After an ambiguous failure (connection error, timeout or
    /// 5xx) the SDK first looks the order up by `client_order_id` and returns it if it exists
    /// (`recovered`); only if it does not exist is the order sent again, with the same
    /// `client_order_id`, so a late first attempt makes the resend fail as a duplicate, which
    /// the lookup resolves again. It returns [`Error::OrderStateUnknown`] when even the lookup
    /// fails.
    pub async fn place_order(&self, order: &PlaceOrderRequest) -> Result<PlaceOrderResult> {
        if order.symbol.is_empty() {
            return Err(Error::config("trading.place_order: symbol is required"));
        }
        check_amounts(
            "trading.place_order",
            &[
                ("price", order.price.as_ref()),
                ("quantity", order.quantity.as_ref()),
                ("quote_quantity", order.quote_quantity.as_ref()),
                ("stop_price", order.stop_price.as_ref()),
            ],
        )?;
        let mut order = order.clone();
        let client_order_id = order
            .client_order_id
            .clone()
            .filter(|s| !s.is_empty())
            .unwrap_or_else(new_id);
        order.client_order_id = Some(client_order_id.clone());
        let o = self.c.resolved();
        // No Idempotency-Key: the server does not honour one on orders (client_order_id does the job).
        let call = Call::new(OperationId::PlaceOrder)
            .order_actions(1)
            .json(&order)?;

        let mut attempt = 0;
        loop {
            let err = match self.c.t.attempt(&call, &o).await {
                Ok(raw) => {
                    // The order was accepted: an unreadable response must still say which
                    // client_order_id to look up.
                    let response: PlaceOrderResponse = decode_data(OperationId::PlaceOrder, &raw)
                        .map_err(|e| Error::OrderStateUnknown {
                        client_order_id: client_order_id.clone(),
                        source: Box::new(e),
                    })?;
                    return Ok(PlaceOrderResult {
                        response,
                        client_order_id,
                        recovered: false,
                    });
                }
                Err(e) => e,
            };
            let duplicate_after_retry = attempt > 0
                && err.is(ErrorCategory::Conflict)
                && err.api().is_some_and(|a| {
                    a.code == ErrorCode::AlreadyExists
                        || a.code == ErrorCode::IdempotencyKeyConflict
                });
            if err.is_ambiguous() || duplicate_after_retry {
                if let Some(existing) = self.lookup(&client_order_id, &err, o.timeout).await? {
                    return Ok(PlaceOrderResult {
                        response: PlaceOrderResponse {
                            order: existing,
                            fills: vec![],
                        },
                        client_order_id,
                        recovered: true,
                    });
                }
                if duplicate_after_retry || attempt >= o.max_retries || err.server_wait_too_long() {
                    return Err(err);
                }
            } else if !err.is_retryable() || attempt >= o.max_retries {
                // Definitive refusals that did not execute (such as 429) are resent below.
                return Err(err);
            }
            self.c
                .t
                .backoff(OperationId::PlaceOrder, attempt, &err, None)
                .await;
            attempt += 1;
        }
    }

    async fn lookup(
        &self,
        client_order_id: &str,
        original: &Error,
        timeout: std::time::Duration,
    ) -> Result<Option<Order>> {
        let c = self.c.with_options(crate::CallOptions {
            timeout: Some(timeout),
            ..self.c.opts.clone()
        });
        match c.trading().order_by_client_id(client_order_id).await {
            Ok(o) => Ok(Some(o)),
            Err(e) if e.is(ErrorCategory::NotFound) => Ok(None),
            Err(_) => Err(Error::OrderStateUnknown {
                client_order_id: client_order_id.to_string(),
                source: Box::new(clone_error(original)),
            }),
        }
    }

    /// Cancels one order (needs the trade scope). It is retried on connection errors and
    /// retryable responses. If a RETRY gets `INVALID_STATE` (the order is no longer open,
    /// typically because the first attempt did cancel it), the cancel is treated as done and
    /// the order is fetched and returned. `INVALID_STATE` on the first attempt is returned as an
    /// error (for example, the order was already filled).
    ///
    /// Check the returned order's `status`: after a retry it is whatever state the order is in,
    /// which is `cancelled` in the usual case but can be `filled` (or partially filled and
    /// cancelled) if it traded before the cancel landed.
    pub async fn cancel_order(&self, order_id: &str) -> Result<Order> {
        let o = self.c.resolved();
        // No Idempotency-Key: the server does not honour one on cancels.
        let call = Call::new(OperationId::CancelOrder).path("order_id", order_id);
        let mut attempt = 0;
        loop {
            let err = match self.c.t.attempt(&call, &o).await {
                Ok(raw) => return decode_data(OperationId::CancelOrder, &raw),
                Err(e) => e,
            };
            if attempt > 0 && err.api().is_some_and(|a| a.code == ErrorCode::InvalidState) {
                return self.order(order_id).await;
            }
            if !err.is_retryable() || attempt >= o.max_retries {
                return Err(err);
            }
            self.c
                .t
                .backoff(OperationId::CancelOrder, attempt, &err, None)
                .await;
            attempt += 1;
        }
    }

    /// Cancels one order named by your `client_order_id` (needs the trade scope). It is retried
    /// like [`Trading::cancel_order`]: if a RETRY gets `INVALID_STATE`, the order is fetched by
    /// `client_order_id` and returned instead of the error. Check the returned order's `status`.
    /// The id is percent-encoded in the path.
    pub async fn cancel_order_by_client_id(&self, client_order_id: &str) -> Result<Order> {
        let o = self.c.resolved();
        // No Idempotency-Key: the server does not honour one on cancels.
        let call =
            Call::new(OperationId::CancelOrderByClientId).path("client_order_id", client_order_id);
        let mut attempt = 0;
        loop {
            let err = match self.c.t.attempt(&call, &o).await {
                Ok(raw) => return decode_data(OperationId::CancelOrderByClientId, &raw),
                Err(e) => e,
            };
            if attempt > 0 && err.api().is_some_and(|a| a.code == ErrorCode::InvalidState) {
                return self.order_by_client_id(client_order_id).await;
            }
            if !err.is_retryable() || attempt >= o.max_retries {
                return Err(err);
            }
            self.c
                .t
                .backoff(OperationId::CancelOrderByClientId, attempt, &err, None)
                .await;
            attempt += 1;
        }
    }

    /// Places 1 to 20 REAL orders in one market (needs the trade scope), each on its own: the
    /// batch is not atomic, and one refusal does not stop the rest.
    ///
    /// A `client_order_id` (a UUID) is generated for each order without one; your own ids must
    /// be 1 to 64 characters of `A-Z a-z 0-9 _ - . :`, not `.` or `..`, and distinct. These
    /// checks fail locally, before anything is sent. To reconcile after an error, or after
    /// dropping the future (which returns nothing), set and save your own ids before the call,
    /// for example with [`crate::new_client_order_id`].
    ///
    /// Retry safety: the body, ids included, is built once and every retry resends it
    /// unchanged. The server refuses a repeated id, so nothing is placed twice. After a lost
    /// answer, an order that the earlier attempt placed comes back as
    /// [`PlaceOutcome::Recovered`] with its `order_id` and `status` (`rejected` means refused for
    /// funds; its id is spent). An item error that names an order (`MARKET_UNAVAILABLE` with
    /// `details.order_id`) is `Recovered` too, and an item `INTERNAL` is looked up once. A 429 is
    /// waited out and the same body resent; a 400, 403 or 404 is not retried; a batch larger
    /// than the key's whole budget (400 with a number in `details["limit"]`) must be split by the
    /// caller. Results are in request order; the counts are computed from them. An `Unknown`
    /// item must be reconciled with [`Trading::order_by_client_id`] before it is placed again.
    ///
    /// Any failure after the request is built is [`Error::BatchPlace`], with every id sent and
    /// `maybe_placed`: a refusal of the whole batch means nothing was placed only when no
    /// earlier attempt was lost. A 200 that is not usable (no `data`, undecodable, or results
    /// that do not match the orders sent) is such a failure with `maybe_placed` true.
    pub async fn place_orders(
        &self,
        symbol: &str,
        orders: &[BatchOrderInput],
    ) -> Result<BatchPlaceResult> {
        if symbol.is_empty() {
            return Err(Error::config("trading.place_orders: symbol is required"));
        }
        check_place(orders)?;
        let mut items = Vec::with_capacity(orders.len());
        for (i, o) in orders.iter().enumerate() {
            check_amounts(
                &format!("trading.place_orders: orders[{i}]"),
                &[
                    ("price", o.price.as_ref()),
                    ("quantity", o.quantity.as_ref()),
                    ("quote_quantity", o.quote_quantity.as_ref()),
                    ("stop_price", o.stop_price.as_ref()),
                ],
            )?;
            items.push(BatchOrderItem {
                // Generated once, here: every attempt sends the same ids.
                client_order_id: o
                    .client_order_id
                    .clone()
                    .unwrap_or_else(new_client_order_id),
                side: o.side.clone(),
                r#type: o.r#type.clone(),
                price: o.price.clone(),
                quantity: o.quantity.clone(),
                quote_quantity: o.quote_quantity.clone(),
                stop_price: o.stop_price.clone(),
                time_in_force: o.time_in_force.clone(),
                trigger_direction: o.trigger_direction.clone(),
            });
        }
        let n = items.len() as u32;
        let sent: Vec<String> = items.iter().map(|i| i.client_order_id.clone()).collect();
        let body = BatchOrderRequest {
            symbol: symbol.to_string(),
            orders: items,
        };
        let mut call = Call::new(OperationId::PlaceBatch)
            .cost(n)
            .order_actions(n)
            .json(&body)?;
        // No Idempotency-Key: the server does not honour one here (client_order_id does the job).
        call.no_idempotency_key = true;
        let mut attempts = Vec::new();
        // From here on the request may have been sent: every failure carries the ids.
        let failed = |source: Error, attempts: &[Attempt]| {
            let maybe_placed = attempts.contains(&Attempt::Ambiguous)
                || !matches!(source, Error::Api(_) | Error::Config(_));
            Error::BatchPlace {
                client_order_ids: sent.clone(),
                maybe_placed,
                source: Box::new(source),
            }
        };
        let raw = match self
            .c
            .t
            .request_noting(call, &self.c.resolved(), &mut attempts)
            .await
        {
            Ok(raw) => raw,
            Err(e) => return Err(failed(e, &attempts)),
        };
        // A 200 that cannot be used is ambiguous: the orders may have been placed.
        let data = match decode_data::<BatchOrder>(OperationId::PlaceBatch, &raw) {
            Ok(d) if place_matches(&sent, &d.results) => d,
            Ok(_) => {
                let e =
                    Error::Decode("place_batch: the results do not match the orders sent".into());
                return Err(failed(e, &attempts));
            }
            Err(e) => return Err(failed(e, &attempts)),
        };
        let after_ambiguous = attempts.contains(&Attempt::Ambiguous);
        let mut results = Vec::with_capacity(data.results.len());
        for r in data.results {
            let mut o = place_from_result(r, after_ambiguous);
            if needs_lookup(&o) {
                o = self.recover_placed(o).await;
            }
            results.push(o);
        }
        Ok(place_result(results))
    }

    /// The server could not say what took this id: read it once, and never place it again.
    async fn recover_placed(&self, mut o: BatchOrderOutcome) -> BatchOrderOutcome {
        match self
            .once()
            .trading()
            .order_by_client_id(&o.client_order_id)
            .await
        {
            Ok(order) => {
                o.order_id = Some(order.id.clone());
                o.status = Some(order.status.clone());
                o.order = Some(order);
            }
            Err(_) => {
                o.outcome = PlaceOutcome::Unknown;
                o.order_id = None;
                o.status = None;
            }
        }
        o
    }

    /// Cancels 1 to 50 orders (needs the trade scope), each named by
    /// [`CancelBatchItem::by_order_id`] or [`CancelBatchItem::by_client_order_id`]. Each entry
    /// is cancelled on its own, in order; a failure does not stop the rest.
    ///
    /// Retried like [`Trading::cancel_order`]: after a lost answer, an entry refused with
    /// `INVALID_STATE` (an earlier attempt may have cancelled it) is looked up once and comes back
    /// as [`CancelOutcome::Recovered`] with its current `status`. Results are in request order;
    /// the counts are computed from them.
    pub async fn cancel_orders(&self, orders: &[CancelBatchItem]) -> Result<BatchCancelResult> {
        let entries = check_cancel(orders)?;
        let n = entries.len() as u32;
        let mut call = Call::new(OperationId::CancelBatch)
            .cost(n)
            .json(&CancelBatchRequest {
                orders: entries.clone(),
            })?;
        // No Idempotency-Key: the server does not honour one on cancels.
        call.no_idempotency_key = true;
        let mut attempts = Vec::new();
        let raw = self
            .c
            .t
            .request_noting(call, &self.c.resolved(), &mut attempts)
            .await?;
        let data: CancelBatch = decode_data(OperationId::CancelBatch, &raw)?;
        if !cancel_matches(&entries, &data.results) {
            return Err(Error::Decode(
                "cancel_batch: the results do not match the entries sent".into(),
            ));
        }
        let after_ambiguous = attempts.contains(&Attempt::Ambiguous);
        let mut results = Vec::with_capacity(data.results.len());
        for r in data.results {
            let mut o = cancel_from_result(r, after_ambiguous);
            if o.outcome == CancelOutcome::Recovered {
                o = self.recover_cancelled(o).await;
            }
            results.push(o);
        }
        Ok(cancel_result(results))
    }

    async fn recover_cancelled(&self, mut o: CancelEntryOutcome) -> CancelEntryOutcome {
        let c = self.once();
        let t = c.trading();
        let found = match (&o.order_id, &o.client_order_id) {
            (Some(id), _) => t.order(id).await,
            (None, Some(cid)) => t.order_by_client_id(cid).await,
            (None, None) => Err(Error::config("no id to look up")),
        };
        match found {
            Ok(order) => {
                o.order_id = Some(order.id.clone());
                o.status = Some(order.status.clone());
                o.order = Some(order);
            }
            Err(_) => o.outcome = CancelOutcome::Unknown,
        }
        o
    }

    /// This service on a client that sends each call once (a batch's lookups are never retried).
    fn once(&self) -> Client {
        self.c.with_options(crate::CallOptions {
            max_retries: Some(0),
            ..self.c.opts.clone()
        })
    }

    /// Cancels every open order in ONE market, such as `"BTC/USDT"`, in one request. An empty
    /// symbol is an error, so an account-wide cancel never happens by accident; use
    /// [`Trading::cancel_all_markets`] for that. An unknown symbol is an API error in the
    /// `NotFound` category.
    ///
    /// It also cancels stop orders that have not triggered yet (status `pending_trigger`) and
    /// releases their reservations, so nothing fires into the market after the call.
    ///
    /// One call handles at most 500 orders. Every order it handled is in exactly one of
    /// `cancelled`, `already_closed` (it closed on its own first: not a failure) and `failed`
    /// (with the reason in `failures`; `INVALID_STATE` means it was taken off the book and cannot be
    /// cancelled yet). A pending order is cancelled at once by the server.
    /// `has_more` means there are more: call again, or use [`Trading::cancel_all_until_done`].
    ///
    /// The server limits cancel-all to 30 calls a minute per account (retried after the server's
    /// wait by the normal retry policy). It is naturally repeatable, so it is retried after
    /// connection errors; a retry reports only what that retry did. No Idempotency-Key is sent:
    /// the server does not honour one here.
    pub async fn cancel_all(&self, symbol: &str) -> Result<CancelAllResult> {
        if symbol.is_empty() {
            return Err(Error::config(
                "trading.cancel_all: symbol is required (\"BASE/QUOTE\"); use cancel_all_markets to cancel in every market",
            ));
        }
        self.cancel_all_once(Some(symbol)).await
    }

    /// Cancels every open order in EVERY market, in one request. See [`Trading::cancel_all`].
    pub async fn cancel_all_markets(&self) -> Result<CancelAllResult> {
        self.cancel_all_once(None).await
    }

    /// Arms, re-arms or disarms the dead-man switch for ONE market, such as `"BTC/USDT"` (needs
    /// the trade scope): if it is not armed again within `timeout`, the server cancels every
    /// open order in that market. An empty or blank symbol is an error (it would mean every
    /// market on the server); use [`Trading::cancel_all_after_markets`] for that.
    ///
    /// `Duration::ZERO` disarms this scope only. Any other value is sent as whole milliseconds
    /// and the SERVER checks the range (5 s to 10 min). The SDK never rounds: a non-zero
    /// duration below 1 ms, a duration that is not a whole number of milliseconds, or one too
    /// large for the request is an error, so a non-zero timeout can never turn into a disarm.
    ///
    /// Using it:
    /// - Arm again about every 2 s with a 10 s timeout, so a few missed calls do not fire it.
    /// - Take your local deadline from when the call STARTED, not from when it returned, and
    ///   never compare the local clock with the returned `deadline` (the clocks differ; use
    ///   `server_time` only to measure the deadline against).
    /// - A switch that has fired is cleared. To keep quoting you need a new arm first.
    /// - The per-market switch and the all-markets switch are separate: each fires on its own,
    ///   and `ZERO` disarms only the scope given.
    /// - Arming is repeat-safe, so it is retried after connection errors and retryable
    ///   responses (no Idempotency-Key is sent). An arm still in flight can land after a later
    ///   disarm and arm it again: if the switch must be off, disarm once more after any
    ///   retried arm.
    /// - No endpoint reads the switch; the response to the call is all you get.
    /// - `DEAD_MAN_NOT_ARMED` (409, not retryable) on order placement means the switch is not
    ///   armed for that market: stop quoting and arm it. Never retry the placement.
    pub async fn cancel_all_after(
        &self,
        symbol: &str,
        timeout: Duration,
    ) -> Result<CancelAllAfter> {
        if symbol.trim().is_empty() {
            return Err(Error::config(
                "trading.cancel_all_after: symbol is required (\"BASE/QUOTE\"); use cancel_all_after_markets for every market",
            ));
        }
        self.cancel_all_after_once(Some(symbol), timeout).await
    }

    /// Arms, re-arms or disarms the dead-man switch for EVERY market, with an explicit
    /// `"symbol": null`. It is separate from the per-market switches. See
    /// [`Trading::cancel_all_after`] for the timeout rules and how to use the switch.
    pub async fn cancel_all_after_markets(&self, timeout: Duration) -> Result<CancelAllAfter> {
        self.cancel_all_after_once(None, timeout).await
    }

    async fn cancel_all_after_once(
        &self,
        symbol: Option<&str>,
        timeout: Duration,
    ) -> Result<CancelAllAfter> {
        let timeout_ms = timeout_to_ms(timeout)?;
        // The server treats an omitted symbol as every market too, but null is explicit.
        let body = serde_json::json!({ "timeout_ms": timeout_ms, "symbol": symbol });
        let mut call = Call::new(OperationId::CancelAllAfter).json(&body)?;
        call.no_idempotency_key = true;
        self.c.get(call).await
    }

    pub(crate) async fn cancel_all_once(&self, symbol: Option<&str>) -> Result<CancelAllResult> {
        self.c.get(cancel_all_call(symbol)?).await
    }

    /// One cancel-all request with no transport retries: `cancel_all_until_done` owns the
    /// retries, so each of its rounds is exactly one HTTP request.
    pub(crate) async fn cancel_all_single_request(
        &self,
        symbol: Option<&str>,
    ) -> Result<CancelAllResult> {
        let o = self.c.resolved();
        let raw = self.c.t.attempt(&cancel_all_call(symbol)?, &o).await?;
        decode_data(OperationId::CancelAll, &raw)
    }
}

/// Whole milliseconds of `d` for the dead-man switch. Zero is the only value that maps to 0.
fn timeout_to_ms(d: Duration) -> Result<i64> {
    if d.is_zero() {
        return Ok(0);
    }
    if !d.subsec_nanos().is_multiple_of(1_000_000) {
        return Err(Error::config(
            "trading.cancel_all_after: timeout must be a whole number of milliseconds (at least 1 ms); use Duration::ZERO to disarm",
        ));
    }
    i64::try_from(d.as_millis())
        .map_err(|_| Error::config("trading.cancel_all_after: timeout is too large"))
}

fn cancel_all_call(symbol: Option<&str>) -> Result<Call> {
    let mut call = Call::new(OperationId::CancelAll).json(&CancelAllRequest {
        symbol: symbol.map(str::to_string),
    })?;
    call.no_idempotency_key = true;
    Ok(call)
}

// ---------------------------------------------------------------------------------------
// Futures data (read only)
// ---------------------------------------------------------------------------------------

/// Futures market data (public) and the account's own futures data (API key with the read
/// scope). Read only: nothing here places orders or moves funds.
///
/// Every market-data answer carries `as_of` and `stale`. When nothing usable is cached and the
/// provider cannot be read, the answer is 503 `SERVICE_UNAVAILABLE` (retryable, with
/// Retry-After), retried by the normal retry policy (the iterate-all helpers treat the
/// `futures_data_unavailable` 503 as a busy answer instead, see [`Futures::all_fills`]). Without a futures account, the account
/// reads answer `has_account: false`.
#[derive(Clone, Copy)]
pub struct Futures<'a> {
    pub(crate) c: &'a Client,
    pub(crate) max_busy_retries: u32,
}

/// How many times [`Futures::all_fills`] and [`Futures::all_funding`] ask again for the same
/// cursor while the provider is busy, unless [`Futures::with_max_busy_retries`] says otherwise.
pub const DEFAULT_MAX_BUSY_RETRIES: u32 = 3;

impl<'a> Futures<'a> {
    /// The same service, with `n` busy retries for [`Futures::all_fills`] and
    /// [`Futures::all_funding`] (default [`DEFAULT_MAX_BUSY_RETRIES`]). It is a setting of its
    /// own: the client's `max_retries` (request retries) does not change it, so a client with
    /// retries disabled still rides out a busy provider.
    pub fn with_max_busy_retries(self, n: u32) -> Futures<'a> {
        Futures {
            max_busy_retries: n,
            ..self
        }
    }

    /// Every listed futures market and its current figures.
    pub async fn markets(&self) -> Result<FuturesMarkets> {
        self.c.get(Call::new(OperationId::FuturesMarkets)).await
    }

    /// One futures market, by the provider's coin name, such as `"BTC"`.
    pub async fn market(&self, coin: &str) -> Result<FuturesMarket> {
        self.c
            .get(Call::new(OperationId::FuturesMarket).path("coin", coin))
            .await
    }

    /// A market's book, `depth` levels a side (1 to 20; `None`: the server's default, 20).
    /// `stale` is the live feed's health, not the book's age.
    pub async fn order_book(&self, coin: &str, depth: Option<u32>) -> Result<FuturesBook> {
        let p = FuturesOrderbookParams {
            depth: depth.map(i64::from),
        };
        self.c
            .get(
                Call::new(OperationId::FuturesOrderbook)
                    .path("coin", coin)
                    .query(p.query()),
            )
            .await
    }

    /// 500 candles: the latest, or the window holding `params.before`.
    pub async fn candles(
        &self,
        coin: &str,
        params: &FuturesCandlesParams,
    ) -> Result<FuturesCandles> {
        self.c
            .get(
                Call::new(OperationId::FuturesCandles)
                    .path("coin", coin)
                    .query(params.query()),
            )
            .await
    }

    /// Recent public trades, newest first: `limit` of them (1 to 100; `None`: the server's
    /// default, 50).
    pub async fn trades(&self, coin: &str, limit: Option<u32>) -> Result<FuturesTrades> {
        let p = FuturesTradesParams {
            limit: limit.map(i64::from),
        };
        self.c
            .get(
                Call::new(OperationId::FuturesTrades)
                    .path("coin", coin)
                    .query(p.query()),
            )
            .await
    }

    /// The account's margin summary and open positions.
    pub async fn positions(&self) -> Result<FuturesPositions> {
        self.c.get(Call::new(OperationId::FuturesPositions)).await
    }

    /// The account's open futures orders.
    pub async fn open_orders(&self) -> Result<FuturesOpenOrders> {
        self.c.get(Call::new(OperationId::FuturesOpenOrders)).await
    }

    /// One page of the account's fills, newest first (30 days back). `cursor` is the previous
    /// page's `next_cursor`, passed back exactly as given (it is opaque); `None` for the newest.
    /// A page can be short, even empty, and still have a `next_cursor`: keep paging until it is
    /// `None`, or use [`Futures::all_fills`].
    pub async fn fills(&self, cursor: Option<&str>) -> Result<FuturesFills> {
        self.c.get(Self::fills_call(cursor)).await
    }

    fn fills_call(cursor: Option<&str>) -> Call {
        let p = FuturesFillsParams {
            cursor: cursor.map(str::to_string),
        };
        Call::new(OperationId::FuturesFills).query(p.query())
    }

    /// One page of the account's funding payments, newest first; paged like [`Futures::fills`].
    pub async fn funding(&self, cursor: Option<&str>) -> Result<FuturesFunding> {
        self.c.get(Self::funding_call(cursor)).await
    }

    fn funding_call(cursor: Option<&str>) -> Call {
        let p = FuturesFundingParams {
            cursor: cursor.map(str::to_string),
        };
        Call::new(OperationId::FuturesFunding).query(p.query())
    }

    /// Every fill (30 days back), newest first, paging until `next_cursor` is `None`.
    ///
    /// The provider is busy when a page is empty and its `next_cursor` is the cursor just sent, or
    /// when the request gets a 503 with `details.reason` `futures_data_unavailable` (also on the
    /// first request). The SDK waits (the server's Retry-After, else `details.retry_after_seconds`,
    /// used as given; else its retry backoff) and asks again with the same cursor, at most 3 times
    /// in a row ([`Futures::with_max_busy_retries`]; both kinds share the count, an advancing page
    /// resets it), then yields [`Error::PagingStalled`] (retryable; the rows before it are not the
    /// whole history; for a 503 it is the error's `source`). The request retries do not apply to
    /// that 503, so a cursor is asked at most 1 + 3 times whatever `max_retries` is, and a hint
    /// of up to 30 s from the server means at most about 90 s of waiting. Any other retryable
    /// error (another 503, a 5xx, a 429) is retried by the request retries. A page with rows whose `next_cursor` is the cursor just
    /// sent yields its rows, then [`Error::PagingCursorRepeated`] (not retryable). Without a futures
    /// account the stream is empty. `max_items` stops the stream after that many items in total.
    pub fn all_fills(&self, max_items: Option<usize>) -> ItemStream<'a, FuturesFill> {
        let this = *self;
        self.all(
            OperationId::FuturesFills,
            max_items,
            move |cursor| async move {
                let p: FuturesFills = this
                    .c
                    .get(Self::fills_call(cursor.as_deref()).busy_not_retried())
                    .await?;
                Ok(HistoryPage {
                    rows: p.fills,
                    has_account: p.has_account,
                    next_cursor: p.next_cursor,
                })
            },
        )
    }

    /// Every funding payment (30 days back), newest first; see [`Futures::all_fills`].
    pub fn all_funding(&self, max_items: Option<usize>) -> ItemStream<'a, Funding> {
        let this = *self;
        self.all(
            OperationId::FuturesFunding,
            max_items,
            move |cursor| async move {
                let p: FuturesFunding = this
                    .c
                    .get(Self::funding_call(cursor.as_deref()).busy_not_retried())
                    .await?;
                Ok(HistoryPage {
                    rows: p.funding,
                    has_account: p.has_account,
                    next_cursor: p.next_cursor,
                })
            },
        )
    }

    fn all<T, F, Fut>(
        &self,
        op: OperationId,
        max_items: Option<usize>,
        fetch: F,
    ) -> ItemStream<'a, T>
    where
        T: Send + 'a,
        F: FnMut(Option<String>) -> Fut + Send + 'a,
        Fut: std::future::Future<Output = Result<HistoryPage<T>>> + Send + 'a,
    {
        let c = self.c;
        paginate_history(
            op.as_str(),
            self.max_busy_retries,
            max_items,
            fetch,
            move |attempt, cause| async move {
                // A server hint is waited exactly (no jitter); without one, the normal backoff.
                match cause.api().and_then(ApiError::busy_hint) {
                    Some(d) => c.t.wait(op, attempt, &cause, None, d).await,
                    None => c.t.backoff(op, attempt, &cause, None).await,
                }
            },
        )
    }
}

/// A copy of an error for wrapping (errors hold no resources).
pub(crate) fn clone_error(e: &Error) -> Error {
    match e {
        Error::Api(a) => Error::Api(a.clone()),
        Error::Connection(c) => Error::Connection(c.clone()),
        Error::WebSocket(w) => Error::WebSocket(w.clone()),
        Error::PagingStalled {
            operation,
            cursor,
            retries,
            source,
        } => Error::PagingStalled {
            operation,
            cursor: cursor.clone(),
            retries: *retries,
            source: source
                .as_ref()
                .and_then(|s| s.downcast_ref::<ApiError>())
                .map(|a| Box::new(a.clone()) as _),
        },
        Error::PagingCursorRepeated { operation, cursor } => Error::PagingCursorRepeated {
            operation,
            cursor: cursor.clone(),
        },
        other => Error::Decode(other.to_string()),
    }
}