maxt 0.2.1

One Rust API for Upbit, Bithumb, Binance, and Hyperliquid market data, accounts, and orders.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! The contract every exchange adapter implements.

use std::future::Future;
use std::pin::Pin;

use crate::error::{Error, Result};
use crate::feature::Feature;
use crate::request::{
    CancelOrdersRequest, CandleRequest, DepositAddressRequest, HistoryRequest, MarginRequest,
    OrderHistoryRequest, OrderLookupRequest, OrderRequest, TransferHistoryRequest,
    TransferLookupRequest, WithdrawRequest,
};
use crate::stream::{AccountStream, MarketStream};
use crate::types::{
    AssetNetwork, Balance, CancelOrdersResult, Candle, Deposit, DepositAddress,
    DepositAddressEntry, Exchange, Feed, FundingPayment, FundingRate, MarginSummary, Market,
    MarketInfo, MarketKind, Order, OrderBook, OrderRules, Page, Position, StreamConfig,
    Subscription, Ticker, Trade, Withdrawal, WithdrawalQuote,
};

/// A boxed future used to keep [`Adapter`] dyn-compatible.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Exchange adapter contract used by [`Client`](crate::Client).
///
/// Implementations must preserve the ordering, validation, and normalization
/// documented by the corresponding [`Client`](crate::Client) methods. All
/// optional methods default to [`Error::Unsupported`].
///
/// External implementations can provide mocks, backtests, or recorded-data
/// adapters. A new real exchange also requires a new [`Exchange`] variant.
pub trait Adapter: Send + Sync + 'static {
    /// Which exchange this adapter talks to.
    fn exchange(&self) -> Exchange;

    /// Whether this configured adapter can use a feature.
    ///
    /// Structural absence is returned from the corresponding method as
    /// [`Error::Unsupported`]. A supported private endpoint without usable
    /// credentials returns [`Error::Auth`](crate::Error::Auth).
    fn supports(&self, feature: Feature) -> bool;

    /// Lists the exchange's markets of one kind.
    fn markets(&self, kind: MarketKind) -> BoxFuture<'_, Result<Vec<MarketInfo>>> {
        let _ = kind;
        unsupported(self.exchange(), Feature::Markets)
    }

    /// Reads the most recent trades on a market.
    fn trades(&self, market: &Market, limit: Option<u32>) -> BoxFuture<'_, Result<Vec<Trade>>> {
        let _ = (market, limit);
        unsupported(self.exchange(), Feature::Trades)
    }

    /// Reads an order book snapshot.
    fn order_book(&self, market: &Market, depth: Option<u32>) -> BoxFuture<'_, Result<OrderBook>> {
        let _ = (market, depth);
        unsupported(self.exchange(), Feature::OrderBook)
    }

    /// Reads a provider ticker summary for one market.
    fn ticker(&self, market: &Market) -> BoxFuture<'_, Result<Ticker>> {
        let _ = market;
        unsupported(self.exchange(), Feature::Ticker)
    }

    /// Reads historical candles.
    fn candles(&self, request: &CandleRequest) -> BoxFuture<'_, Result<Vec<Candle>>> {
        let _ = request;
        unsupported(self.exchange(), Feature::Candles)
    }

    /// Opens a live market-data subscription.
    ///
    /// The default rejects empty markets or feeds, then returns
    /// [`Error::Unsupported`] for the first requested feed. Implementors build
    /// streams with [`MarketStream::new`] and handle reconnects.
    fn subscribe(
        &self,
        subscription: &Subscription,
        config: &StreamConfig,
    ) -> BoxFuture<'_, Result<MarketStream>> {
        if subscription.markets().is_empty() {
            return Box::pin(async {
                Err(Error::invalid_request(
                    "markets",
                    "a subscription needs at least one market",
                ))
            });
        }
        if subscription.feeds().is_empty() {
            return Box::pin(async {
                Err(Error::invalid_request(
                    "feeds",
                    "a subscription needs at least one feed",
                ))
            });
        }
        let _ = config;
        let feature = match subscription.feeds()[0] {
            Feed::Trades => Feature::TradeStream,
            Feed::OrderBook => Feature::OrderBookStream,
            Feed::Ticker => Feature::TickerStream,
            Feed::Candles(_) => Feature::CandleStream,
        };
        unsupported(self.exchange(), feature)
    }

    /// Reads the account's balances.
    fn balances(&self) -> BoxFuture<'_, Result<Vec<Balance>>> {
        unsupported(self.exchange(), Feature::Balances)
    }

    /// Reads current order fees, limits, supported combinations, and balances.
    fn order_rules(&self, market: &Market) -> BoxFuture<'_, Result<OrderRules>> {
        let _ = market;
        unsupported(self.exchange(), Feature::Trading)
    }

    /// Reads live transfer rules for one asset.
    fn asset_networks(&self, asset: &str) -> BoxFuture<'_, Result<Vec<AssetNetwork>>> {
        let _ = asset;
        unsupported(self.exchange(), Feature::AssetNetworks)
    }

    /// Lists all exchange-issued deposit addresses for this account.
    ///
    /// A provider can omit network metadata, and an address can be absent
    /// while issuance is still pending.
    fn deposit_addresses(&self) -> BoxFuture<'_, Result<Vec<DepositAddressEntry>>> {
        unsupported(self.exchange(), Feature::DepositAddresses)
    }

    /// Reads an exchange-issued deposit address.
    fn deposit_address(
        &self,
        request: &DepositAddressRequest,
    ) -> BoxFuture<'_, Result<DepositAddress>> {
        let _ = request;
        unsupported(self.exchange(), Feature::DepositAddresses)
    }

    /// Requests creation of an exchange-issued deposit address.
    ///
    /// Some exchanges generate addresses asynchronously. In that case the
    /// returned address is `None`; callers should poll [`Self::deposit_address`]
    /// until the address is issued.
    fn create_deposit_address(
        &self,
        request: &DepositAddressRequest,
    ) -> BoxFuture<'_, Result<DepositAddress>> {
        let _ = request;
        unsupported(self.exchange(), Feature::DepositAddresses)
    }

    /// Performs live source-account checks without submitting a withdrawal.
    fn prepare_withdrawal(
        &self,
        request: &WithdrawRequest,
    ) -> BoxFuture<'_, Result<WithdrawalQuote>> {
        let _ = request;
        unsupported(self.exchange(), Feature::WithdrawalQuotes)
    }

    /// Submits one withdrawal without automatic retry.
    fn withdraw(&self, request: &WithdrawRequest) -> BoxFuture<'_, Result<Withdrawal>> {
        let _ = request;
        unsupported(self.exchange(), Feature::Withdrawals)
    }

    /// Looks up one deposit by exchange UUID or transaction ID.
    fn deposit(&self, request: &TransferLookupRequest) -> BoxFuture<'_, Result<Deposit>> {
        let _ = request;
        unsupported(self.exchange(), Feature::DepositLookup)
    }

    /// Looks up one withdrawal by exchange UUID or transaction ID.
    fn withdrawal(&self, request: &TransferLookupRequest) -> BoxFuture<'_, Result<Withdrawal>> {
        let _ = request;
        unsupported(self.exchange(), Feature::WithdrawalLookup)
    }

    /// Cancels a withdrawal that the exchange still permits to be cancelled.
    fn cancel_withdrawal(&self, withdrawal_id: &str) -> BoxFuture<'_, Result<()>> {
        let _ = withdrawal_id;
        unsupported(self.exchange(), Feature::WithdrawalCancellation)
    }

    /// Reads one page of deposit history.
    fn deposits(&self, request: &TransferHistoryRequest) -> BoxFuture<'_, Result<Page<Deposit>>> {
        let _ = request;
        unsupported(self.exchange(), Feature::DepositHistory)
    }

    /// Reads one page of withdrawal history.
    fn withdrawals(
        &self,
        request: &TransferHistoryRequest,
    ) -> BoxFuture<'_, Result<Page<Withdrawal>>> {
        let _ = request;
        unsupported(self.exchange(), Feature::WithdrawalHistory)
    }

    /// Reads the account's open orders, optionally narrowed to one market.
    fn open_orders(&self, market: Option<&Market>) -> BoxFuture<'_, Result<Vec<Order>>> {
        let _ = market;
        unsupported(self.exchange(), Feature::OpenOrders)
    }

    /// Reads one order by the exchange's own identifier.
    fn order(&self, market: &Market, order_id: &str) -> BoxFuture<'_, Result<Order>> {
        let _ = (market, order_id);
        unsupported(self.exchange(), Feature::OrderHistory)
    }

    /// Reads one order by the caller-assigned identifier supplied at placement.
    fn order_by_client_id(&self, market: &Market, client_id: &str) -> BoxFuture<'_, Result<Order>> {
        let _ = (market, client_id);
        unsupported(self.exchange(), Feature::OrderHistory)
    }

    /// Looks up up to 100 orders by exchange or caller-assigned identifiers.
    fn orders_by_ids(&self, request: &OrderLookupRequest) -> BoxFuture<'_, Result<Vec<Order>>> {
        let _ = request;
        unsupported(self.exchange(), Feature::OrderHistory)
    }

    /// Reads one newest-first page of completed or cancelled orders.
    fn order_history(&self, request: &OrderHistoryRequest) -> BoxFuture<'_, Result<Page<Order>>> {
        let _ = request;
        unsupported(self.exchange(), Feature::OrderHistory)
    }

    /// Opens a live private account subscription.
    ///
    /// Implementors build streams with [`AccountStream::new`] and report
    /// credential-renewal failures as `Err` stream items.
    fn subscribe_account(&self, config: &StreamConfig) -> BoxFuture<'_, Result<AccountStream>> {
        let _ = config;
        unsupported(self.exchange(), Feature::AccountStream)
    }

    /// Places an order.
    fn place_order(&self, request: &OrderRequest) -> BoxFuture<'_, Result<Order>> {
        let _ = request;
        unsupported(self.exchange(), Feature::Trading)
    }

    /// Cancels an order by the exchange's own identifier.
    fn cancel_order(&self, market: &Market, order_id: &str) -> BoxFuture<'_, Result<()>> {
        let _ = (market, order_id);
        unsupported(self.exchange(), Feature::Trading)
    }

    /// Cancels an order by the caller-assigned identifier supplied at placement.
    fn cancel_order_by_client_id(
        &self,
        market: &Market,
        client_id: &str,
    ) -> BoxFuture<'_, Result<()>> {
        let _ = (market, client_id);
        unsupported(self.exchange(), Feature::Trading)
    }

    /// Cancels multiple orders and returns every per-order outcome.
    fn cancel_orders(
        &self,
        request: &CancelOrdersRequest,
    ) -> BoxFuture<'_, Result<CancelOrdersResult>> {
        let _ = request;
        unsupported(self.exchange(), Feature::Trading)
    }

    /// Reads open positions, optionally narrowed to one market.
    fn positions(&self, market: Option<&Market>) -> BoxFuture<'_, Result<Vec<Position>>> {
        let _ = market;
        unsupported(self.exchange(), Feature::Positions)
    }

    /// Reads account-wide margin state.
    fn margin_summary(&self) -> BoxFuture<'_, Result<MarginSummary>> {
        unsupported(self.exchange(), Feature::Margin)
    }

    /// Reads a market's funding rate history.
    fn funding_rates(&self, request: &HistoryRequest) -> BoxFuture<'_, Result<Page<FundingRate>>> {
        let _ = request;
        unsupported(self.exchange(), Feature::FundingRates)
    }

    /// Reads the account's funding payment history.
    fn funding_payments(
        &self,
        request: &HistoryRequest,
    ) -> BoxFuture<'_, Result<Page<FundingPayment>>> {
        let _ = request;
        unsupported(self.exchange(), Feature::FundingPayments)
    }

    /// Sets leverage or margin mode on a market.
    fn set_margin(&self, request: &MarginRequest) -> BoxFuture<'_, Result<()>> {
        let _ = request;
        unsupported(self.exchange(), Feature::MarginConfig)
    }
}

/// Builds the failed future a missing feature produces.
///
/// A free function, because a generic trait method would cost [`Adapter`] its
/// `dyn` compatibility.
fn unsupported<'a, T: Send + 'a>(exchange: Exchange, feature: Feature) -> BoxFuture<'a, Result<T>> {
    let exchange = exchange.id();
    Box::pin(async move {
        Err(Error::unsupported(
            feature,
            exchange,
            format!("{exchange} has no endpoint for {feature}"),
        ))
    })
}

impl Adapter for Box<dyn Adapter> {
    fn exchange(&self) -> Exchange {
        (**self).exchange()
    }

    fn supports(&self, feature: Feature) -> bool {
        (**self).supports(feature)
    }

    fn markets(&self, kind: MarketKind) -> BoxFuture<'_, Result<Vec<MarketInfo>>> {
        (**self).markets(kind)
    }

    fn trades(&self, market: &Market, limit: Option<u32>) -> BoxFuture<'_, Result<Vec<Trade>>> {
        (**self).trades(market, limit)
    }

    fn order_book(&self, market: &Market, depth: Option<u32>) -> BoxFuture<'_, Result<OrderBook>> {
        (**self).order_book(market, depth)
    }

    fn ticker(&self, market: &Market) -> BoxFuture<'_, Result<Ticker>> {
        (**self).ticker(market)
    }

    fn candles(&self, request: &CandleRequest) -> BoxFuture<'_, Result<Vec<Candle>>> {
        (**self).candles(request)
    }

    fn subscribe(
        &self,
        subscription: &Subscription,
        config: &StreamConfig,
    ) -> BoxFuture<'_, Result<MarketStream>> {
        (**self).subscribe(subscription, config)
    }

    fn balances(&self) -> BoxFuture<'_, Result<Vec<Balance>>> {
        (**self).balances()
    }

    fn order_rules(&self, market: &Market) -> BoxFuture<'_, Result<OrderRules>> {
        (**self).order_rules(market)
    }

    fn asset_networks(&self, asset: &str) -> BoxFuture<'_, Result<Vec<AssetNetwork>>> {
        (**self).asset_networks(asset)
    }

    fn deposit_addresses(&self) -> BoxFuture<'_, Result<Vec<DepositAddressEntry>>> {
        (**self).deposit_addresses()
    }

    fn deposit_address(
        &self,
        request: &DepositAddressRequest,
    ) -> BoxFuture<'_, Result<DepositAddress>> {
        (**self).deposit_address(request)
    }

    fn create_deposit_address(
        &self,
        request: &DepositAddressRequest,
    ) -> BoxFuture<'_, Result<DepositAddress>> {
        (**self).create_deposit_address(request)
    }

    fn prepare_withdrawal(
        &self,
        request: &WithdrawRequest,
    ) -> BoxFuture<'_, Result<WithdrawalQuote>> {
        (**self).prepare_withdrawal(request)
    }

    fn withdraw(&self, request: &WithdrawRequest) -> BoxFuture<'_, Result<Withdrawal>> {
        (**self).withdraw(request)
    }

    fn deposit(&self, request: &TransferLookupRequest) -> BoxFuture<'_, Result<Deposit>> {
        (**self).deposit(request)
    }

    fn withdrawal(&self, request: &TransferLookupRequest) -> BoxFuture<'_, Result<Withdrawal>> {
        (**self).withdrawal(request)
    }

    fn cancel_withdrawal(&self, withdrawal_id: &str) -> BoxFuture<'_, Result<()>> {
        (**self).cancel_withdrawal(withdrawal_id)
    }

    fn deposits(&self, request: &TransferHistoryRequest) -> BoxFuture<'_, Result<Page<Deposit>>> {
        (**self).deposits(request)
    }

    fn withdrawals(
        &self,
        request: &TransferHistoryRequest,
    ) -> BoxFuture<'_, Result<Page<Withdrawal>>> {
        (**self).withdrawals(request)
    }

    fn open_orders(&self, market: Option<&Market>) -> BoxFuture<'_, Result<Vec<Order>>> {
        (**self).open_orders(market)
    }

    fn order(&self, market: &Market, order_id: &str) -> BoxFuture<'_, Result<Order>> {
        (**self).order(market, order_id)
    }

    fn order_by_client_id(&self, market: &Market, client_id: &str) -> BoxFuture<'_, Result<Order>> {
        (**self).order_by_client_id(market, client_id)
    }

    fn orders_by_ids(&self, request: &OrderLookupRequest) -> BoxFuture<'_, Result<Vec<Order>>> {
        (**self).orders_by_ids(request)
    }

    fn order_history(&self, request: &OrderHistoryRequest) -> BoxFuture<'_, Result<Page<Order>>> {
        (**self).order_history(request)
    }

    fn subscribe_account(&self, config: &StreamConfig) -> BoxFuture<'_, Result<AccountStream>> {
        (**self).subscribe_account(config)
    }

    fn place_order(&self, request: &OrderRequest) -> BoxFuture<'_, Result<Order>> {
        (**self).place_order(request)
    }

    fn cancel_order(&self, market: &Market, order_id: &str) -> BoxFuture<'_, Result<()>> {
        (**self).cancel_order(market, order_id)
    }

    fn cancel_order_by_client_id(
        &self,
        market: &Market,
        client_id: &str,
    ) -> BoxFuture<'_, Result<()>> {
        (**self).cancel_order_by_client_id(market, client_id)
    }

    fn cancel_orders(
        &self,
        request: &CancelOrdersRequest,
    ) -> BoxFuture<'_, Result<CancelOrdersResult>> {
        (**self).cancel_orders(request)
    }

    fn positions(&self, market: Option<&Market>) -> BoxFuture<'_, Result<Vec<Position>>> {
        (**self).positions(market)
    }

    fn margin_summary(&self) -> BoxFuture<'_, Result<MarginSummary>> {
        (**self).margin_summary()
    }

    fn funding_rates(&self, request: &HistoryRequest) -> BoxFuture<'_, Result<Page<FundingRate>>> {
        (**self).funding_rates(request)
    }

    fn funding_payments(
        &self,
        request: &HistoryRequest,
    ) -> BoxFuture<'_, Result<Page<FundingPayment>>> {
        (**self).funding_payments(request)
    }

    fn set_margin(&self, request: &MarginRequest) -> BoxFuture<'_, Result<()>> {
        (**self).set_margin(request)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct MarketDataOnly;

    impl Adapter for MarketDataOnly {
        fn exchange(&self) -> Exchange {
            Exchange::Upbit
        }

        fn supports(&self, feature: Feature) -> bool {
            matches!(feature, Feature::Markets | Feature::Ticker)
        }
    }

    #[tokio::test]
    async fn unimplemented_methods_report_the_missing_feature_by_name() {
        let error = MarketDataOnly.balances().await.unwrap_err();

        let Error::Unsupported {
            feature, exchange, ..
        } = error
        else {
            panic!("expected an unsupported-feature error");
        };
        assert_eq!(feature, Feature::Balances);
        assert_eq!(exchange, "upbit");
    }

    #[tokio::test]
    async fn an_adapter_survives_being_held_behind_dyn() {
        let adapters: Vec<Box<dyn Adapter>> = vec![Box::new(MarketDataOnly)];

        for adapter in &adapters {
            assert_eq!(adapter.exchange(), Exchange::Upbit);
            assert!(adapter.supports(Feature::Ticker));
            assert!(adapter.positions(None).await.is_err());
        }
    }

    #[test]
    fn supports_reflects_the_adapter_not_the_trait_defaults() {
        assert!(MarketDataOnly.supports(Feature::Markets));
        assert!(!MarketDataOnly.supports(Feature::Trading));
    }
}