binance-api-client 0.1.0

Async Rust client for Binance Spot REST and WebSocket APIs.
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
//! Wallet API endpoints (SAPI).
//!
//! This module provides access to Binance Wallet SAPI endpoints for:
//! - System status
//! - Coin information
//! - Deposit/withdrawal operations
//! - Asset management
//! - Universal transfers

use crate::client::Client;
use crate::error::Result;
use crate::models::wallet::{
    AccountSnapshot, AccountSnapshotType, AccountStatus, ApiKeyPermissions, ApiTradingStatus,
    AssetDetail, CoinInfo, DepositAddress, DepositRecord, FundingAsset, SystemStatus, TradeFee,
    TransferHistory, TransferResponse, UniversalTransferType, WalletBalance, WithdrawRecord,
    WithdrawResponse,
};

// SAPI endpoints.
const SAPI_V1_SYSTEM_STATUS: &str = "/sapi/v1/system/status";
const SAPI_V1_CAPITAL_CONFIG_GETALL: &str = "/sapi/v1/capital/config/getall";
const SAPI_V1_ACCOUNT_SNAPSHOT: &str = "/sapi/v1/accountSnapshot";
const SAPI_V1_CAPITAL_DEPOSIT_HISREC: &str = "/sapi/v1/capital/deposit/hisrec";
const SAPI_V1_CAPITAL_DEPOSIT_ADDRESS: &str = "/sapi/v1/capital/deposit/address";
const SAPI_V1_CAPITAL_WITHDRAW_APPLY: &str = "/sapi/v1/capital/withdraw/apply";
const SAPI_V1_CAPITAL_WITHDRAW_HISTORY: &str = "/sapi/v1/capital/withdraw/history";
const SAPI_V1_ASSET_ASSET_DETAIL: &str = "/sapi/v1/asset/assetDetail";
const SAPI_V1_ASSET_TRADE_FEE: &str = "/sapi/v1/asset/tradeFee";
const SAPI_V1_ASSET_TRANSFER: &str = "/sapi/v1/asset/transfer";
const SAPI_V1_ASSET_GET_FUNDING_ASSET: &str = "/sapi/v1/asset/get-funding-asset";
const SAPI_V1_ASSET_WALLET_BALANCE: &str = "/sapi/v1/asset/wallet/balance";
const SAPI_V1_ACCOUNT_STATUS: &str = "/sapi/v1/account/status";
const SAPI_V1_ACCOUNT_API_TRADING_STATUS: &str = "/sapi/v1/account/apiTradingStatus";
const SAPI_V1_ACCOUNT_API_RESTRICTIONS: &str = "/sapi/v1/account/apiRestrictions";

/// Wallet API client.
///
/// Provides access to Binance Wallet SAPI endpoints for asset management,
/// deposits, withdrawals, and account status.
///
/// # Example
///
/// ```rust,ignore
/// let client = Binance::new("api_key", "secret_key")?;
///
/// // Check system status
/// let status = client.wallet().system_status().await?;
/// if status.is_normal() {
///     println!("System is operational");
/// }
///
/// // Get all coin information
/// let coins = client.wallet().all_coins().await?;
/// for coin in coins {
///     println!("{}: free={}", coin.coin, coin.free);
/// }
/// ```
#[derive(Clone)]
pub struct Wallet {
    pub(crate) client: Client,
}

impl Wallet {
    /// Create a new Wallet API client.
    pub(crate) fn new(client: Client) -> Self {
        Self { client }
    }

    // System Status.

    /// Fetch system status.
    ///
    /// Returns whether the Binance system is operational or under maintenance.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let status = client.wallet().system_status().await?;
    /// if status.is_normal() {
    ///     println!("System is operational");
    /// } else {
    ///     println!("System maintenance: {}", status.msg);
    /// }
    /// ```
    pub async fn system_status(&self) -> Result<SystemStatus> {
        self.client.get(SAPI_V1_SYSTEM_STATUS, None).await
    }

    // Coin Information.

    /// Get information of all coins (available for deposit and withdraw).
    ///
    /// Returns detailed information about all supported coins including
    /// deposit/withdraw status, fees, and network information.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let coins = client.wallet().all_coins().await?;
    /// for coin in coins {
    ///     println!("{} ({}): deposit={}, withdraw={}",
    ///         coin.coin, coin.name,
    ///         coin.deposit_all_enable, coin.withdraw_all_enable);
    /// }
    /// ```
    pub async fn all_coins(&self) -> Result<Vec<CoinInfo>> {
        self.client
            .get_signed(SAPI_V1_CAPITAL_CONFIG_GETALL, &[])
            .await
    }

    // Account Snapshots.

    /// Get daily account snapshot.
    ///
    /// Returns account balance snapshots for the specified time period.
    /// The query time period must be less than 30 days.
    /// Only supports querying within the last month.
    ///
    /// # Arguments
    ///
    /// * `snapshot_type` - Type of account (Spot, Margin, or Futures)
    /// * `start_time` - Start timestamp (optional)
    /// * `end_time` - End timestamp (optional)
    /// * `limit` - Number of records (default 7, max 30)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use binance_api_client::AccountSnapshotType;
    ///
    /// let snapshot = client.wallet()
    ///     .account_snapshot(AccountSnapshotType::Spot, None, None, Some(5))
    ///     .await?;
    /// ```
    pub async fn account_snapshot(
        &self,
        snapshot_type: AccountSnapshotType,
        start_time: Option<u64>,
        end_time: Option<u64>,
        limit: Option<u32>,
    ) -> Result<AccountSnapshot> {
        let type_str = match snapshot_type {
            AccountSnapshotType::Spot => "SPOT",
            AccountSnapshotType::Margin => "MARGIN",
            AccountSnapshotType::Futures => "FUTURES",
        };

        let mut params: Vec<(&str, String)> = vec![("type", type_str.to_string())];

        if let Some(st) = start_time {
            params.push(("startTime", st.to_string()));
        }
        if let Some(et) = end_time {
            params.push(("endTime", et.to_string()));
        }
        if let Some(l) = limit {
            params.push(("limit", l.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .get_signed(SAPI_V1_ACCOUNT_SNAPSHOT, &params_ref)
            .await
    }

    // Deposit.

    /// Get deposit address for a coin.
    ///
    /// # Arguments
    ///
    /// * `coin` - Coin symbol (e.g., "BTC")
    /// * `network` - Network to use (optional, uses default if not specified)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let address = client.wallet().deposit_address("BTC", None).await?;
    /// println!("Deposit to: {}", address.address);
    /// ```
    pub async fn deposit_address(
        &self,
        coin: &str,
        network: Option<&str>,
    ) -> Result<DepositAddress> {
        let mut params: Vec<(&str, String)> = vec![("coin", coin.to_string())];

        if let Some(n) = network {
            params.push(("network", n.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .get_signed(SAPI_V1_CAPITAL_DEPOSIT_ADDRESS, &params_ref)
            .await
    }

    /// Get deposit history.
    ///
    /// # Arguments
    ///
    /// * `coin` - Filter by coin (optional)
    /// * `status` - Filter by status: 0=pending, 6=credited, 1=success (optional)
    /// * `start_time` - Start timestamp (optional)
    /// * `end_time` - End timestamp (optional)
    /// * `offset` - Pagination offset (optional)
    /// * `limit` - Number of records (default 1000, max 1000)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let deposits = client.wallet()
    ///     .deposit_history(Some("BTC"), None, None, None, None, Some(10))
    ///     .await?;
    /// for deposit in deposits {
    ///     println!("{}: {} {}", deposit.tx_id, deposit.amount, deposit.coin);
    /// }
    /// ```
    pub async fn deposit_history(
        &self,
        coin: Option<&str>,
        status: Option<u32>,
        start_time: Option<u64>,
        end_time: Option<u64>,
        offset: Option<u32>,
        limit: Option<u32>,
    ) -> Result<Vec<DepositRecord>> {
        let mut params: Vec<(&str, String)> = vec![];

        if let Some(c) = coin {
            params.push(("coin", c.to_string()));
        }
        if let Some(s) = status {
            params.push(("status", s.to_string()));
        }
        if let Some(st) = start_time {
            params.push(("startTime", st.to_string()));
        }
        if let Some(et) = end_time {
            params.push(("endTime", et.to_string()));
        }
        if let Some(o) = offset {
            params.push(("offset", o.to_string()));
        }
        if let Some(l) = limit {
            params.push(("limit", l.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .get_signed(SAPI_V1_CAPITAL_DEPOSIT_HISREC, &params_ref)
            .await
    }

    // Withdrawal.

    /// Submit a withdrawal request.
    ///
    /// # Arguments
    ///
    /// * `coin` - Coin symbol
    /// * `address` - Withdrawal address
    /// * `amount` - Amount to withdraw
    /// * `network` - Network to use (optional)
    /// * `address_tag` - Secondary address identifier (memo/tag, optional)
    /// * `withdraw_order_id` - Client ID for the withdrawal (optional)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let response = client.wallet()
    ///     .withdraw("USDT", "0x1234...", "100.0", Some("ETH"), None, None)
    ///     .await?;
    /// println!("Withdrawal ID: {}", response.id);
    /// ```
    pub async fn withdraw(
        &self,
        coin: &str,
        address: &str,
        amount: &str,
        network: Option<&str>,
        address_tag: Option<&str>,
        withdraw_order_id: Option<&str>,
    ) -> Result<WithdrawResponse> {
        let mut params: Vec<(&str, String)> = vec![
            ("coin", coin.to_string()),
            ("address", address.to_string()),
            ("amount", amount.to_string()),
        ];

        if let Some(n) = network {
            params.push(("network", n.to_string()));
        }
        if let Some(tag) = address_tag {
            params.push(("addressTag", tag.to_string()));
        }
        if let Some(id) = withdraw_order_id {
            params.push(("withdrawOrderId", id.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .post_signed(SAPI_V1_CAPITAL_WITHDRAW_APPLY, &params_ref)
            .await
    }

    /// Get withdrawal history.
    ///
    /// # Arguments
    ///
    /// * `coin` - Filter by coin (optional)
    /// * `withdraw_order_id` - Filter by client withdrawal ID (optional)
    /// * `status` - Filter by status (optional)
    /// * `start_time` - Start timestamp (optional)
    /// * `end_time` - End timestamp (optional)
    /// * `offset` - Pagination offset (optional)
    /// * `limit` - Number of records (default 1000, max 1000)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let withdrawals = client.wallet()
    ///     .withdraw_history(None, None, None, None, None, None, Some(10))
    ///     .await?;
    /// ```
    #[allow(clippy::too_many_arguments)]
    pub async fn withdraw_history(
        &self,
        coin: Option<&str>,
        withdraw_order_id: Option<&str>,
        status: Option<u32>,
        start_time: Option<u64>,
        end_time: Option<u64>,
        offset: Option<u32>,
        limit: Option<u32>,
    ) -> Result<Vec<WithdrawRecord>> {
        let mut params: Vec<(&str, String)> = vec![];

        if let Some(c) = coin {
            params.push(("coin", c.to_string()));
        }
        if let Some(id) = withdraw_order_id {
            params.push(("withdrawOrderId", id.to_string()));
        }
        if let Some(s) = status {
            params.push(("status", s.to_string()));
        }
        if let Some(st) = start_time {
            params.push(("startTime", st.to_string()));
        }
        if let Some(et) = end_time {
            params.push(("endTime", et.to_string()));
        }
        if let Some(o) = offset {
            params.push(("offset", o.to_string()));
        }
        if let Some(l) = limit {
            params.push(("limit", l.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .get_signed(SAPI_V1_CAPITAL_WITHDRAW_HISTORY, &params_ref)
            .await
    }

    // Asset Management.

    /// Get asset detail (deposit/withdraw fees and status).
    ///
    /// # Arguments
    ///
    /// * `asset` - Asset symbol (optional, returns all if not specified)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let details = client.wallet().asset_detail(Some("BTC")).await?;
    /// ```
    pub async fn asset_detail(
        &self,
        asset: Option<&str>,
    ) -> Result<std::collections::HashMap<String, AssetDetail>> {
        let mut params: Vec<(&str, String)> = vec![];

        if let Some(a) = asset {
            params.push(("asset", a.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .get_signed(SAPI_V1_ASSET_ASSET_DETAIL, &params_ref)
            .await
    }

    /// Get trade fee for symbols.
    ///
    /// # Arguments
    ///
    /// * `symbol` - Trading pair symbol (optional, returns all if not specified)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let fees = client.wallet().trade_fee(Some("BTCUSDT")).await?;
    /// for fee in fees {
    ///     println!("{}: maker={}, taker={}",
    ///         fee.symbol, fee.maker_commission, fee.taker_commission);
    /// }
    /// ```
    pub async fn trade_fee(&self, symbol: Option<&str>) -> Result<Vec<TradeFee>> {
        let mut params: Vec<(&str, String)> = vec![];

        if let Some(s) = symbol {
            params.push(("symbol", s.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .get_signed(SAPI_V1_ASSET_TRADE_FEE, &params_ref)
            .await
    }

    // Universal Transfer.

    /// Execute a universal transfer between accounts.
    ///
    /// # Arguments
    ///
    /// * `transfer_type` - Type of transfer
    /// * `asset` - Asset to transfer
    /// * `amount` - Amount to transfer
    /// * `from_symbol` - Required for isolated margin transfers
    /// * `to_symbol` - Required for isolated margin transfers
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use binance_api_client::UniversalTransferType;
    ///
    /// let response = client.wallet()
    ///     .universal_transfer(
    ///         UniversalTransferType::MainFunding,
    ///         "USDT",
    ///         "100.0",
    ///         None,
    ///         None,
    ///     )
    ///     .await?;
    /// println!("Transfer ID: {}", response.tran_id);
    /// ```
    pub async fn universal_transfer(
        &self,
        transfer_type: UniversalTransferType,
        asset: &str,
        amount: &str,
        from_symbol: Option<&str>,
        to_symbol: Option<&str>,
    ) -> Result<TransferResponse> {
        let type_str = transfer_type.as_str().to_string();

        let mut params: Vec<(&str, String)> = vec![
            ("type", type_str),
            ("asset", asset.to_string()),
            ("amount", amount.to_string()),
        ];

        if let Some(from) = from_symbol {
            params.push(("fromSymbol", from.to_string()));
        }
        if let Some(to) = to_symbol {
            params.push(("toSymbol", to.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .post_signed(SAPI_V1_ASSET_TRANSFER, &params_ref)
            .await
    }

    /// Get universal transfer history.
    ///
    /// # Arguments
    ///
    /// * `transfer_type` - Type of transfer to query
    /// * `start_time` - Start timestamp (optional)
    /// * `end_time` - End timestamp (optional)
    /// * `current` - Page number (default 1)
    /// * `size` - Page size (default 10, max 100)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use binance_api_client::UniversalTransferType;
    ///
    /// let history = client.wallet()
    ///     .transfer_history(UniversalTransferType::MainFunding, None, None, None, Some(10))
    ///     .await?;
    /// ```
    pub async fn transfer_history(
        &self,
        transfer_type: UniversalTransferType,
        start_time: Option<u64>,
        end_time: Option<u64>,
        current: Option<u32>,
        size: Option<u32>,
    ) -> Result<TransferHistory> {
        let type_str = transfer_type.as_str().to_string();

        let mut params: Vec<(&str, String)> = vec![("type", type_str)];

        if let Some(st) = start_time {
            params.push(("startTime", st.to_string()));
        }
        if let Some(et) = end_time {
            params.push(("endTime", et.to_string()));
        }
        if let Some(c) = current {
            params.push(("current", c.to_string()));
        }
        if let Some(s) = size {
            params.push(("size", s.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .get_signed(SAPI_V1_ASSET_TRANSFER, &params_ref)
            .await
    }

    // Wallet Balances.

    /// Get funding wallet balance.
    ///
    /// # Arguments
    ///
    /// * `asset` - Asset to query (optional, returns all if not specified)
    /// * `need_btc_valuation` - Whether to include BTC valuation (optional)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let assets = client.wallet().funding_wallet(None, Some(true)).await?;
    /// for asset in assets {
    ///     println!("{}: {}", asset.asset, asset.free);
    /// }
    /// ```
    pub async fn funding_wallet(
        &self,
        asset: Option<&str>,
        need_btc_valuation: Option<bool>,
    ) -> Result<Vec<FundingAsset>> {
        let mut params: Vec<(&str, String)> = vec![];

        if let Some(a) = asset {
            params.push(("asset", a.to_string()));
        }
        if let Some(btc) = need_btc_valuation {
            params.push(("needBtcValuation", btc.to_string()));
        }

        let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.client
            .post_signed(SAPI_V1_ASSET_GET_FUNDING_ASSET, &params_ref)
            .await
    }

    /// Get wallet balance for all asset wallets.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let balances = client.wallet().wallet_balance().await?;
    /// for balance in balances {
    ///     if balance.balance > 0.0 {
    ///         println!("{}: {}", balance.wallet_name, balance.balance);
    ///     }
    /// }
    /// ```
    pub async fn wallet_balance(&self) -> Result<Vec<WalletBalance>> {
        self.client
            .get_signed(SAPI_V1_ASSET_WALLET_BALANCE, &[])
            .await
    }

    // Account Status.

    /// Get account status.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let status = client.wallet().account_status().await?;
    /// println!("Account status: {}", status.data);
    /// ```
    pub async fn account_status(&self) -> Result<AccountStatus> {
        self.client.get_signed(SAPI_V1_ACCOUNT_STATUS, &[]).await
    }

    /// Get API trading status.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let status = client.wallet().api_trading_status().await?;
    /// if status.data.is_locked {
    ///     println!("Trading is locked!");
    /// }
    /// ```
    pub async fn api_trading_status(&self) -> Result<ApiTradingStatus> {
        self.client
            .get_signed(SAPI_V1_ACCOUNT_API_TRADING_STATUS, &[])
            .await
    }

    /// Get API key permissions.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let permissions = client.wallet().api_key_permissions().await?;
    /// println!("Can trade: {}", permissions.enable_spot_and_margin_trading);
    /// println!("Can withdraw: {}", permissions.enable_withdrawals);
    /// ```
    pub async fn api_key_permissions(&self) -> Result<ApiKeyPermissions> {
        self.client
            .get_signed(SAPI_V1_ACCOUNT_API_RESTRICTIONS, &[])
            .await
    }
}