Binance

Struct Binance 

Source
pub struct Binance { /* private fields */ }
Expand description

Binance exchange structure.

Implementations§

Source§

impl Binance

Source

pub async fn get_signing_timestamp(&self) -> Result<i64, Error>

Gets the server timestamp for signing requests.

This method uses the cached time offset if available, otherwise fetches the server time directly. It also triggers a background resync if needed.

§Optimization

By caching the time offset between local and server time, this method reduces the number of network round-trips for signed API requests from 2 to 1. Instead of fetching server time before every signed request, we calculate the server timestamp locally using: server_timestamp = local_time + cached_offset

§Returns

Returns the estimated server timestamp in milliseconds.

§Errors

Returns an error if:

  • The time sync manager is not initialized and the server time fetch fails
  • Network errors occur during time synchronization
§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Get timestamp for signing (uses cached offset if available)
let timestamp = binance.get_signing_timestamp().await?;
println!("Server timestamp: {}", timestamp);

Requirements: 1.2, 2.3, 6.4

Source

pub async fn sync_time(&self) -> Result<(), Error>

Synchronizes local time with Binance server time.

This method fetches the current server time from Binance and updates the cached time offset. The offset is calculated as: offset = server_time - local_time

§When to Use
  • Called automatically by get_signing_timestamp() when resync is needed
  • Can be called manually to force a time synchronization
  • Useful after receiving timestamp-related errors from the API
§Returns

Returns Ok(()) on successful synchronization.

§Errors

Returns an error if the server time fetch fails due to network issues.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Manually sync time with server
binance.sync_time().await?;

// Check the current offset
let offset = binance.time_sync().get_offset();
println!("Time offset: {}ms", offset);

Requirements: 2.1, 2.2, 6.3

Source

pub fn is_timestamp_error(&self, error: &Error) -> bool

Checks if an error is related to timestamp validation.

Binance returns specific error codes and messages when the request timestamp is outside the acceptable window (recvWindow). This method detects such errors to enable automatic retry with a fresh timestamp.

§Binance Timestamp Error Codes
Error CodeMessageMeaning
-1021“Timestamp for this request is outside of the recvWindow”Timestamp too old or too new
-1022“Signature for this request is not valid”May be caused by wrong timestamp
§Arguments
  • error - The error to check
§Returns

Returns true if the error is related to timestamp validation, false otherwise.

§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::{ExchangeConfig, Error};

let binance = Binance::new(ExchangeConfig::default()).unwrap();

// Simulate a timestamp error
let err = Error::exchange("-1021", "Timestamp for this request is outside of the recvWindow");
assert!(binance.is_timestamp_error(&err));

// Non-timestamp error
let err = Error::exchange("-1100", "Illegal characters found in parameter");
assert!(!binance.is_timestamp_error(&err));

Requirements: 4.1

Source

pub async fn execute_signed_request_with_retry<T, F, Fut>( &self, request_fn: F, ) -> Result<T, Error>
where F: Fn(i64) -> Fut, Fut: Future<Output = Result<T, Error>>,

Executes a signed request with automatic timestamp error recovery.

This method wraps a signed request operation and automatically handles timestamp-related errors by resyncing time and retrying the request once.

§Error Recovery Flow
  1. Execute the request with the current timestamp
  2. If the request fails with a timestamp error: a. Resync time with the server b. Retry the request with a fresh timestamp
  3. If the retry also fails, return the error
§Retry Limit

To prevent infinite retry loops, this method limits automatic retries to exactly 1 retry per request. If the retry also fails, the error is returned.

§Type Parameters
  • T - The return type of the request
  • F - The async function that performs the signed request
§Arguments
  • request_fn - An async function that takes a timestamp (i64) and returns a Result<T>. This function should perform the actual signed API request.
§Returns

Returns Ok(T) on success, or Err if the request fails after retry.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Execute a signed request with automatic retry on timestamp error
let result = binance.execute_signed_request_with_retry(|timestamp| {
    Box::pin(async move {
        // Perform signed request using the provided timestamp
        // ... actual request logic here ...
        Ok(())
    })
}).await?;

Requirements: 4.1, 4.2, 4.3, 4.4

Source

pub async fn handle_timestamp_error_and_resync(&self, error: &Error) -> bool

Helper method to handle timestamp errors and trigger resync.

This method checks if an error is a timestamp error and, if so, triggers a time resync. It’s useful for manual error handling when you want more control over the retry logic.

§Arguments
  • error - The error to check
§Returns

Returns true if the error was a timestamp error and resync was triggered, false otherwise.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Manual error handling with resync
let result = some_signed_request().await;
if let Err(ref e) = result {
    if binance.handle_timestamp_error_and_resync(e).await {
        // Timestamp error detected and resync triggered
        // You can now retry the request
    }
}

Requirements: 4.1, 4.2

Source§

impl Binance

Source

pub async fn fetch_balance_simple(&self) -> Result<Balance, Error>

Fetch account balance.

§Returns

Returns the account Balance information.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_balance( &self, account_type: Option<AccountType>, ) -> Result<Balance, Error>

Fetch account balance with optional account type parameter.

Query for balance and get the amount of funds available for trading or funds locked in orders.

§Arguments
  • account_type - Optional account type. Supported values:
    • Spot - Spot trading account (default)
    • Margin - Cross margin account
    • IsolatedMargin - Isolated margin account
    • Futures - USDT-margined futures (linear)
    • Delivery - Coin-margined futures (inverse)
    • Funding - Funding wallet
    • Option - Options account
§Returns

Returns the account Balance information.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;

// Fetch spot balance (default)
let balance = binance.fetch_balance(None).await?;

// Fetch futures balance
let futures_balance = binance.fetch_balance(Some(AccountType::Futures)).await?;
Source

pub async fn fetch_balance_with_params( &self, params: BalanceFetchParams, ) -> Result<Balance, Error>

Fetch account balance with detailed parameters.

This method provides full control over balance fetching, supporting all Binance account types and margin modes.

§Arguments
  • params - Balance fetch parameters including:
    • account_type - Account type (spot, margin, futures, etc.)
    • margin_mode - “cross” or “isolated” for margin trading
    • symbols - Symbols for isolated margin queries
    • portfolio_margin - Use Portfolio Margin API
    • sub_type - “linear” or “inverse” for futures
§Returns

Returns the account Balance information.

§Errors

Returns an error if authentication fails or the API request fails.

§API Endpoints
  • Spot: GET /api/v3/account
  • Cross Margin: GET /sapi/v1/margin/account
  • Isolated Margin: GET /sapi/v1/margin/isolated/account
  • Funding Wallet: POST /sapi/v1/asset/get-funding-asset
  • USDT-M Futures: GET /fapi/v2/balance
  • COIN-M Futures: GET /dapi/v1/balance
  • Options: GET /eapi/v1/account
  • Portfolio Margin: GET /papi/v1/balance
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;

// Fetch cross margin balance
let margin_balance = binance.fetch_balance_with_params(
    BalanceFetchParams::cross_margin()
).await?;

// Fetch isolated margin balance for specific symbols
let isolated_balance = binance.fetch_balance_with_params(
    BalanceFetchParams::isolated_margin(Some(vec!["BTC/USDT".to_string()]))
).await?;

// Fetch USDT-margined futures balance
let futures_balance = binance.fetch_balance_with_params(
    BalanceFetchParams::linear_futures()
).await?;

// Fetch portfolio margin balance
let pm_balance = binance.fetch_balance_with_params(
    BalanceFetchParams::portfolio_margin()
).await?;
Source

pub async fn fetch_my_trades( &self, symbol: &str, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<Trade>, Error>

Fetch user’s trade history.

§Arguments
  • symbol - Trading pair symbol.
  • since - Optional start timestamp.
  • limit - Optional limit on number of trades.
§Returns

Returns a vector of Trade structures for the user’s trades.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

Source

pub async fn fetch_my_recent_trades( &self, symbol: &str, since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Trade>, Error>

Fetch user’s recent trade history with additional parameters.

This method is similar to fetch_my_trades but accepts additional parameters for more flexible querying.

§Arguments
  • symbol - Trading pair symbol.
  • since - Optional start timestamp in milliseconds.
  • limit - Optional limit on number of trades (default: 500, max: 1000).
  • params - Optional additional parameters that may include:
    • orderId: Filter by order ID.
    • fromId: Start from specific trade ID.
    • endTime: End timestamp in milliseconds.
§Returns

Returns a vector of Trade structures for the user’s trades.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;
let my_trades = binance.fetch_my_recent_trades("BTC/USDT", None, Some(50), None).await?;
for trade in &my_trades {
    println!("Trade: {} {} @ {}", trade.side, trade.amount, trade.price);
}
Source

pub async fn fetch_currencies(&self) -> Result<Vec<Currency>, Error>

Fetch all currency information.

§Returns

Returns a vector of Currency structures.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_trading_fee( &self, symbol: &str, params: Option<HashMap<String, String>>, ) -> Result<TradingFee, Error>

Fetch trading fees for a symbol.

§Arguments
  • symbol - Trading pair symbol.
  • params - Optional parameters. Supports portfolioMargin key for Portfolio Margin mode.
§Returns

Returns trading fee information for the symbol as a FeeTradingFee structure.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;
let fee = binance.fetch_trading_fee("BTC/USDT", None).await?;
println!("Maker: {}, Taker: {}", fee.maker, fee.taker);
Source

pub async fn fetch_trading_fees( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, String>>, ) -> Result<HashMap<String, TradingFee>, Error>

Fetch trading fees for multiple symbols.

§Arguments
  • symbols - Optional list of trading pair symbols. None fetches all pairs.
  • params - Optional parameters.
§Returns

Returns a HashMap of trading fees keyed by symbol.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;
let fees = binance.fetch_trading_fees(None, None).await?;
for (symbol, fee) in &fees {
    println!("{}: maker={}, taker={}", symbol, fee.maker, fee.taker);
}
Source

pub async fn create_listen_key(&self) -> Result<String, Error>

Create a listen key for user data stream.

Creates a new listen key that can be used to subscribe to user data streams via WebSocket. The listen key is valid for 60 minutes.

§Returns

Returns the listen key string.

§Errors

Returns an error if:

  • API credentials are not configured
  • API request fails
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;

let listen_key = binance.create_listen_key().await?;
println!("Listen Key: {}", listen_key);
Source

pub async fn refresh_listen_key(&self, listen_key: &str) -> Result<(), Error>

Refresh listen key to extend validity.

Extends the listen key validity by 60 minutes. Recommended to call every 30 minutes to maintain the connection.

§Arguments
  • listen_key - The listen key to refresh.
§Returns

Returns Ok(()) on success.

§Errors

Returns an error if:

  • API credentials are not configured
  • Listen key is invalid or expired
  • API request fails
Source

pub async fn delete_listen_key(&self, listen_key: &str) -> Result<(), Error>

Delete listen key to close user data stream.

Closes the user data stream connection and invalidates the listen key.

§Arguments
  • listen_key - The listen key to delete.
§Returns

Returns Ok(()) on success.

§Errors

Returns an error if:

  • API credentials are not configured
  • API request fails
Source§

impl Binance

Source

pub async fn set_position_mode_dapi( &self, dual_side: bool, params: Option<Value>, ) -> Result<Value, Error>

Set position mode for coin-margined futures (DAPI).

This method sets the position mode (hedge mode or one-way mode) specifically for coin-margined (inverse) futures contracts using the DAPI endpoint.

§Arguments
  • dual_side - true for hedge mode (dual-side position), false for one-way mode.
  • params - Optional additional parameters to include in the request.
§Returns

Returns the API response as a JSON Value.

§Errors

Returns an error if:

  • Authentication credentials are missing
  • The API request fails
  • The response cannot be parsed
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

// Enable hedge mode for DAPI
let result = binance.set_position_mode_dapi(true, None).await?;
println!("Result: {:?}", result);

// Switch back to one-way mode for DAPI
let result = binance.set_position_mode_dapi(false, None).await?;
§Error Handling Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

match binance.set_position_mode_dapi(true, None).await {
    Ok(result) => println!("Position mode set successfully: {:?}", result),
    Err(e) => {
        eprintln!("Failed to set position mode: {}", e);
        // Handle error - could be auth error, network error, or exchange error
    }
}
Source

pub async fn fetch_position_mode_dapi( &self, params: Option<Value>, ) -> Result<bool, Error>

Fetch current position mode for coin-margined futures (DAPI).

This method retrieves the current position mode (hedge mode or one-way mode) specifically for coin-margined (inverse) futures contracts using the DAPI endpoint.

§Arguments
  • params - Optional additional parameters to include in the request.
§Returns

Returns the current position mode:

  • true: Hedge mode (dual-side position) is enabled.
  • false: One-way mode is enabled.
§Errors

Returns an error if:

  • Authentication credentials are missing
  • The API request fails
  • The response cannot be parsed
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

let is_hedge_mode = binance.fetch_position_mode_dapi(None).await?;
if is_hedge_mode {
    println!("DAPI is in hedge mode (dual-side positions)");
} else {
    println!("DAPI is in one-way mode");
}
§Error Handling Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

match binance.fetch_position_mode_dapi(None).await {
    Ok(is_hedge) => {
        let mode = if is_hedge { "hedge" } else { "one-way" };
        println!("Current DAPI position mode: {}", mode);
    }
    Err(e) => eprintln!("Failed to fetch position mode: {}", e),
}
Source

pub async fn fetch_dapi_account( &self, params: Option<Value>, ) -> Result<Value, Error>

Fetch coin-margined futures account information.

This method retrieves account information specifically for coin-margined (inverse) futures contracts using the DAPI endpoint. The response includes wallet balance, unrealized profit, margin balance, available balance, and position information.

§Arguments
  • params - Optional additional parameters to include in the request.
§Returns

Returns the account information as a raw JSON Value. The response includes:

  • totalWalletBalance: Total wallet balance
  • totalUnrealizedProfit: Total unrealized profit
  • totalMarginBalance: Total margin balance
  • availableBalance: Available balance for new positions
  • maxWithdrawAmount: Maximum withdraw amount
  • assets: List of asset balances
  • positions: List of positions
§Errors

Returns an error if:

  • Authentication credentials are missing
  • The API request fails
  • The response cannot be parsed
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

// Fetch DAPI account information
let account = binance.fetch_dapi_account(None).await?;
println!("Account: {:?}", account);

// Access specific fields
if let Some(balance) = account.get("totalWalletBalance") {
    println!("Total wallet balance: {}", balance);
}
if let Some(positions) = account.get("positions") {
    println!("Positions: {:?}", positions);
}
§Error Handling Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

match binance.fetch_dapi_account(None).await {
    Ok(account) => {
        // Process account data
        if let Some(balance) = account.get("totalWalletBalance") {
            println!("Wallet balance: {}", balance);
        }
    }
    Err(e) => {
        eprintln!("Failed to fetch DAPI account: {}", e);
        // Could be authentication error, network error, or API error
    }
}
Source

pub async fn fetch_dapi_income( &self, symbol: Option<&str>, income_type: Option<&str>, since: Option<i64>, limit: Option<u32>, params: Option<Value>, ) -> Result<Value, Error>

Fetch income history for coin-margined futures.

This method retrieves income history specifically for coin-margined (inverse) futures contracts using the DAPI endpoint. Income types include realized PnL, funding fees, commissions, and other transaction types.

§Arguments
  • symbol - Optional symbol to filter by (e.g., “BTC/USD:BTC”).
  • income_type - Optional income type to filter by. Valid values:
    • "TRANSFER": Transfer in/out
    • "WELCOME_BONUS": Welcome bonus
    • "REALIZED_PNL": Realized profit and loss
    • "FUNDING_FEE": Funding fee
    • "COMMISSION": Trading commission
    • "INSURANCE_CLEAR": Insurance fund clear
    • "REFERRAL_KICKBACK": Referral kickback
    • "COMMISSION_REBATE": Commission rebate
    • "DELIVERED_SETTELMENT": Delivered settlement
  • since - Optional start timestamp in milliseconds.
  • limit - Optional record limit (default 100, max 1000).
  • params - Optional additional parameters. Supports:
    • endTime: End timestamp in milliseconds.
§Returns

Returns income history records as a raw JSON Value array. Each record includes:

  • symbol: Trading pair symbol
  • incomeType: Type of income
  • income: Income amount
  • asset: Asset currency
  • info: Additional information
  • time: Timestamp
  • tranId: Transaction ID
  • tradeId: Trade ID (if applicable)
§Errors

Returns an error if:

  • Authentication credentials are missing
  • The API request fails
  • The response cannot be parsed
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

// Fetch all income history
let income = binance.fetch_dapi_income(None, None, None, None, None).await?;
println!("Income history: {:?}", income);

// Fetch funding fees for a specific symbol
let funding_fees = binance.fetch_dapi_income(
    Some("BTC/USD:BTC"),
    Some("FUNDING_FEE"),
    None,
    Some(100),
    None,
).await?;

// Fetch income with time range
let params = json!({
    "endTime": 1704067200000_i64
});
let income = binance.fetch_dapi_income(
    None,
    None,
    Some(1703980800000),  // since
    Some(50),             // limit
    Some(params),
).await?;
§Error Handling Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

match binance.fetch_dapi_income(None, Some("FUNDING_FEE"), None, Some(100), None).await {
    Ok(income) => {
        if let Some(records) = income.as_array() {
            println!("Found {} income records", records.len());
            for record in records {
                println!("Income: {:?}", record.get("income"));
            }
        }
    }
    Err(e) => eprintln!("Failed to fetch income history: {}", e),
}
Source

pub async fn fetch_dapi_commission_rate( &self, symbol: &str, params: Option<Value>, ) -> Result<Value, Error>

Fetch commission rate for a coin-margined futures symbol.

This method retrieves the maker and taker commission rates for a specific coin-margined (inverse) futures symbol using the DAPI endpoint.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USD:BTC”). This parameter is required.
  • params - Optional additional parameters to include in the request.
§Returns

Returns the commission rate information as a raw JSON Value. The response includes:

  • symbol: Trading pair symbol
  • makerCommissionRate: Maker commission rate (e.g., “0.0002”)
  • takerCommissionRate: Taker commission rate (e.g., “0.0004”)
§Errors

Returns an error if:

  • Authentication credentials are missing
  • The symbol parameter is invalid or not found
  • The API request fails
  • The response cannot be parsed
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

// Fetch commission rate for BTC/USD:BTC
let commission = binance.fetch_dapi_commission_rate("BTC/USD:BTC", None).await?;
println!("Commission rate: {:?}", commission);

// Access specific fields
if let Some(maker_rate) = commission.get("makerCommissionRate") {
    println!("Maker rate: {}", maker_rate);
}
if let Some(taker_rate) = commission.get("takerCommissionRate") {
    println!("Taker rate: {}", taker_rate);
}
§Error Handling Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

match binance.fetch_dapi_commission_rate("BTC/USD:BTC", None).await {
    Ok(commission) => {
        let maker = commission.get("makerCommissionRate")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("N/A");
        let taker = commission.get("takerCommissionRate")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("N/A");
        println!("Maker: {}, Taker: {}", maker, taker);
    }
    Err(e) => eprintln!("Failed to fetch commission rate: {}", e),
}
Source

pub async fn fetch_dapi_adl_quantile( &self, symbol: Option<&str>, params: Option<Value>, ) -> Result<Value, Error>

Fetch ADL (Auto-Deleveraging) quantile for coin-margined futures.

This method retrieves the ADL quantile information for coin-margined (inverse) futures positions using the DAPI endpoint. The ADL quantile indicates the priority of a position for auto-deleveraging during extreme market conditions.

A higher quantile means a higher priority for auto-deleveraging. Traders with profitable positions and high leverage are more likely to be auto-deleveraged when the insurance fund is insufficient to cover liquidation losses.

§Arguments
  • symbol - Optional symbol to filter by (e.g., “BTC/USD:BTC”). If not provided, returns ADL quantile for all positions.
  • params - Optional additional parameters to include in the request.
§Returns

Returns the ADL quantile information as a raw JSON Value. The response includes:

  • symbol: Trading pair symbol
  • adlQuantile: ADL quantile object containing:
    • LONG: Quantile for long positions (1-5, where 5 is highest priority)
    • SHORT: Quantile for short positions (1-5, where 5 is highest priority)
    • HEDGE: Quantile for hedge mode positions (if applicable)
§Errors

Returns an error if:

  • Authentication credentials are missing
  • The symbol parameter is invalid or not found (if provided)
  • The API request fails
  • The response cannot be parsed
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

// Fetch ADL quantile for all positions
let adl = binance.fetch_dapi_adl_quantile(None, None).await?;
println!("ADL quantile: {:?}", adl);

// Fetch ADL quantile for a specific symbol
let adl = binance.fetch_dapi_adl_quantile(Some("BTC/USD:BTC"), None).await?;
println!("BTC ADL quantile: {:?}", adl);

// Access specific fields from the response
if let Some(arr) = adl.as_array() {
    for item in arr {
        if let Some(symbol) = item.get("symbol") {
            println!("Symbol: {}", symbol);
        }
        if let Some(quantile) = item.get("adlQuantile") {
            if let Some(long_q) = quantile.get("LONG") {
                println!("Long ADL quantile: {}", long_q);
            }
            if let Some(short_q) = quantile.get("SHORT") {
                println!("Short ADL quantile: {}", short_q);
            }
        }
    }
}
§Error Handling Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

match binance.fetch_dapi_adl_quantile(Some("BTC/USD:BTC"), None).await {
    Ok(adl) => {
        // Check ADL risk level
        if let Some(arr) = adl.as_array() {
            for item in arr {
                if let Some(quantile) = item.get("adlQuantile") {
                    if let Some(long_q) = quantile.get("LONG").and_then(serde_json::Value::as_i64) {
                        if long_q >= 4 {
                            println!("Warning: High ADL risk for long position!");
                        }
                    }
                }
            }
        }
    }
    Err(e) => eprintln!("Failed to fetch ADL quantile: {}", e),
}
Source

pub async fn fetch_dapi_force_orders( &self, symbol: Option<&str>, auto_close_type: Option<&str>, since: Option<i64>, limit: Option<u32>, params: Option<Value>, ) -> Result<Value, Error>

Fetch force liquidation orders for coin-margined futures.

This method retrieves force liquidation orders (liquidations and auto-deleveraging) for coin-margined (inverse) futures contracts using the DAPI endpoint.

Force orders occur when:

  • Liquidation: A position is forcibly closed due to insufficient margin
  • ADL (Auto-Deleveraging): A profitable position is reduced to cover losses from liquidated positions when the insurance fund is insufficient
§Arguments
  • symbol - Optional symbol to filter by (e.g., “BTC/USD:BTC”).
  • auto_close_type - Optional auto-close type to filter by. Valid values:
    • "LIQUIDATION": Liquidation orders
    • "ADL": Auto-deleveraging orders
  • since - Optional start timestamp in milliseconds.
  • limit - Optional record limit (default 50, max 100).
  • params - Optional additional parameters. Supports:
    • endTime: End timestamp in milliseconds.
§Returns

Returns force liquidation order records as a raw JSON Value array. Each record includes:

  • orderId: Order ID
  • symbol: Trading pair symbol
  • status: Order status
  • clientOrderId: Client order ID
  • price: Order price
  • avgPrice: Average fill price
  • origQty: Original quantity
  • executedQty: Executed quantity
  • cumBase: Cumulative base asset
  • timeInForce: Time in force
  • type: Order type
  • reduceOnly: Whether reduce-only
  • side: Order side (BUY/SELL)
  • positionSide: Position side (LONG/SHORT/BOTH)
  • origType: Original order type
  • time: Order time
  • updateTime: Last update time
§Errors

Returns an error if:

  • Authentication credentials are missing
  • The symbol parameter is invalid or not found (if provided)
  • The API request fails
  • The response cannot be parsed
§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

// Fetch all force orders
let force_orders = binance.fetch_dapi_force_orders(None, None, None, None, None).await?;
println!("Force orders: {:?}", force_orders);

// Fetch liquidation orders for a specific symbol
let liquidations = binance.fetch_dapi_force_orders(
    Some("BTC/USD:BTC"),
    Some("LIQUIDATION"),
    None,
    Some(50),
    None,
).await?;

// Fetch ADL orders with time range
let params = json!({
    "endTime": 1704067200000_i64
});
let adl_orders = binance.fetch_dapi_force_orders(
    None,
    Some("ADL"),
    Some(1703980800000),  // since
    Some(100),            // limit
    Some(params),
).await?;

// Process the results
if let Some(orders) = force_orders.as_array() {
    for order in orders {
        if let Some(order_id) = order.get("orderId") {
            println!("Order ID: {}", order_id);
        }
        if let Some(symbol) = order.get("symbol") {
            println!("Symbol: {}", symbol);
        }
        if let Some(side) = order.get("side") {
            println!("Side: {}", side);
        }
    }
}
§Error Handling Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;

match binance.fetch_dapi_force_orders(None, Some("LIQUIDATION"), None, Some(50), None).await {
    Ok(orders) => {
        if let Some(arr) = orders.as_array() {
            if arr.is_empty() {
                println!("No liquidation orders found");
            } else {
                println!("Found {} liquidation orders", arr.len());
                for order in arr {
                    println!("Order: {:?}", order.get("orderId"));
                }
            }
        }
    }
    Err(e) => eprintln!("Failed to fetch force orders: {}", e),
}
Source§

impl Binance

Source

pub async fn fetch_deposit_address( &self, code: &str, params: Option<BTreeMap<String, String>>, ) -> Result<DepositAddress, Error>

Fetch deposit address for a currency.

§Arguments
  • code - Currency code (e.g., “BTC”, “USDT”).
  • params - Optional parameters:
    • network: Network type (e.g., “ETH”, “BSC”, “TRX”).
§Returns

Returns a DepositAddress with the deposit address and optional tag.

§Errors

Returns an error if authentication fails or the API request fails.

§Notes
  • Binance automatically generates a new address if none exists.
  • Some currencies require the network parameter (e.g., USDT can be on ETH/BSC/TRX).
§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Fetch BTC deposit address
let addr = binance.fetch_deposit_address("BTC", None).await?;
println!("BTC address: {}", addr.address);

// Fetch USDT deposit address on TRX network
let mut params = BTreeMap::new();
params.insert("network".to_string(), "TRX".to_string());
let addr = binance.fetch_deposit_address("USDT", Some(params)).await?;
println!("USDT-TRX address: {}", addr.address);
Source

pub async fn withdraw( &self, code: &str, amount: &str, address: &str, params: Option<BTreeMap<String, String>>, ) -> Result<Transaction, Error>

Withdraw funds to an external address.

§Arguments
  • code - Currency code (e.g., “BTC”, “USDT”).
  • amount - Withdrawal amount.
  • address - Withdrawal address.
  • params - Optional parameters:
    • tag: Address tag (e.g., XRP tag).
    • network: Network type (e.g., “ETH”, “BSC”, “TRX”).
    • addressTag: Address tag (alias for tag).
    • name: Address memo name.
    • walletType: Wallet type (0=spot, 1=funding).
§Returns

Returns a Transaction with withdrawal details.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Basic withdrawal
let tx = binance.withdraw("USDT", "100.0", "TXxxx...", None).await?;
println!("Withdrawal ID: {}", tx.id);

// Withdrawal with specific network
let mut params = BTreeMap::new();
params.insert("network".to_string(), "TRX".to_string());
let tx = binance.withdraw("USDT", "100.0", "TXxxx...", Some(params)).await?;
Source

pub async fn fetch_deposits( &self, code: Option<&str>, since: Option<i64>, limit: Option<i64>, params: Option<BTreeMap<String, String>>, ) -> Result<Vec<Transaction>, Error>

Fetch deposit history.

§Arguments
  • code - Optional currency code (e.g., “BTC”, “USDT”).
  • since - Optional start timestamp in milliseconds.
  • limit - Optional quantity limit.
  • params - Optional parameters:
    • coin: Currency (overrides code parameter).
    • status: Status filter (0=pending, 6=credited, 1=success).
    • startTime: Start timestamp in milliseconds.
    • endTime: End timestamp in milliseconds.
    • offset: Offset for pagination.
    • txId: Transaction ID filter.
§Returns

Returns a vector of Transaction records.

§Notes
  • Maximum query range: 90 days.
  • Default returns last 90 days if no time range provided.
§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Query all deposits
let deposits = binance.fetch_deposits(None, None, Some(100), None).await?;
println!("Total deposits: {}", deposits.len());

// Query BTC deposits
let btc_deposits = binance.fetch_deposits(Some("BTC"), None, None, None).await?;
Source

pub async fn fetch_withdrawals( &self, code: Option<&str>, since: Option<i64>, limit: Option<i64>, params: Option<BTreeMap<String, String>>, ) -> Result<Vec<Transaction>, Error>

Fetch withdrawal history.

§Arguments
  • code - Optional currency code (e.g., “BTC”, “USDT”).
  • since - Optional start timestamp in milliseconds.
  • limit - Optional quantity limit.
  • params - Optional parameters:
    • coin: Currency (overrides code parameter).
    • withdrawOrderId: Withdrawal order ID.
    • status: Status filter (0=email sent, 1=cancelled, 2=awaiting approval, 3=rejected, 4=processing, 5=failure, 6=completed).
    • startTime: Start timestamp in milliseconds.
    • endTime: End timestamp in milliseconds.
    • offset: Offset for pagination.
§Returns

Returns a vector of Transaction records.

§Notes
  • Maximum query range: 90 days.
  • Default returns last 90 days if no time range provided.
§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Query all withdrawals
let withdrawals = binance.fetch_withdrawals(None, None, Some(100), None).await?;
println!("Total withdrawals: {}", withdrawals.len());

// Query USDT withdrawals
let usdt_withdrawals = binance.fetch_withdrawals(Some("USDT"), None, None, None).await?;
Source

pub async fn fetch_deposit_withdraw_fees( &self, currency: Option<&str>, params: Option<BTreeMap<String, String>>, ) -> Result<Vec<DepositWithdrawFee>, Error>

Fetch deposit and withdrawal fees for currencies.

§Arguments
  • currency - Optional currency code to filter results.
  • params - Optional additional parameters.
§Returns

Returns a vector of DepositWithdrawFee structures.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Fetch all fees
let fees = binance.fetch_deposit_withdraw_fees(None, None).await?;

// Fetch fees for specific currency
let btc_fees = binance.fetch_deposit_withdraw_fees(Some("BTC"), None).await?;
Source§

impl Binance

Source

pub async fn fetch_position( &self, symbol: &str, params: Option<Value>, ) -> Result<Position, Error>

Fetch a single position for a trading pair.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT:USDT”).
  • params - Optional additional parameters.
§Returns

Returns a Position structure for the specified symbol.

§Errors

Returns an error if authentication fails, the market is not found, or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;
let position = binance.fetch_position("BTC/USDT:USDT", None).await?;
println!("Position: {:?}", position);
Source

pub async fn fetch_positions( &self, symbols: Option<Vec<String>>, params: Option<Value>, ) -> Result<Vec<Position>, Error>

Fetch all positions.

§Arguments
  • symbols - Optional vector of trading pair symbols.
  • params - Optional parameters.
§Returns

Returns a vector of Position structures.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;
let positions = binance.fetch_positions(None, None).await?;
Source

pub async fn fetch_positions_risk( &self, symbols: Option<Vec<String>>, params: Option<Value>, ) -> Result<Vec<Position>, Error>

Fetch position risk information.

This is an alias for fetch_positions provided for CCXT naming consistency.

§Arguments
  • symbols - Optional list of trading pair symbols.
  • params - Optional additional parameters.
§Returns

Returns a vector of position risk information as Position structures.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_position_risk( &self, symbol: Option<&str>, params: Option<Value>, ) -> Result<Value, Error>

Fetch position risk information (raw JSON).

Retrieves risk information for all futures positions, including unrealized PnL, liquidation price, leverage, etc.

§Arguments
  • symbol - Optional trading pair symbol. None returns all positions.
  • params - Optional parameters.
§Returns

Returns position risk information as raw JSON.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_leverages( &self, symbols: Option<Vec<String>>, params: Option<Value>, ) -> Result<BTreeMap<String, Leverage>, Error>

Fetch leverage settings for multiple trading pairs.

§Arguments
  • symbols - Optional list of trading pairs. None queries all pairs.
  • params - Optional parameters:
    • portfolioMargin: Whether to use portfolio margin account.
§Returns

Returns a HashMap of leverage information keyed by trading pair symbol.

§Errors

Returns an error if authentication fails or the API request fails.

§Examples
// Query leverage settings for all trading pairs
let leverages = exchange.fetch_leverages(None, None).await?;

// Query leverage settings for specific pairs
let symbols = vec!["BTC/USDT:USDT".to_string(), "ETH/USDT:USDT".to_string()];
let leverages = exchange.fetch_leverages(Some(symbols), None).await?;
Source

pub async fn fetch_leverage( &self, symbol: &str, params: Option<Value>, ) -> Result<Leverage, Error>

Fetch leverage settings for a single trading pair.

§Arguments
  • symbol - Trading pair symbol.
  • params - Optional additional parameters.
§Returns

Returns leverage information for the specified trading pair.

§Errors

Returns an error if the symbol is not found or the API request fails.

§Examples
// Query leverage settings for BTC/USDT futures
let leverage = exchange.fetch_leverage("BTC/USDT:USDT", None).await?;
println!("Long leverage: {:?}", leverage.long_leverage);
println!("Short leverage: {:?}", leverage.short_leverage);
println!("Margin mode: {:?}", leverage.margin_mode);
Source

pub async fn set_leverage( &self, symbol: &str, leverage: i64, params: Option<HashMap<String, String>>, ) -> Result<HashMap<String, Value>, Error>

Set leverage multiplier for a trading pair.

§Arguments
  • symbol - Trading pair symbol.
  • leverage - Leverage multiplier (1-125).
  • params - Optional additional parameters.
§Returns

Returns the operation result as a HashMap.

§Errors

Returns an error if:

  • Authentication credentials are missing
  • Leverage is outside valid range (1-125)
  • The market is not a futures/swap market
  • The API request fails
§Examples
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;
let result = binance.set_leverage("BTC/USDT:USDT", 10, None).await?;
Source

pub async fn fetch_leverage_bracket( &self, symbol: Option<&str>, params: Option<Value>, ) -> Result<Value, Error>

Fetch leverage bracket information.

Retrieves leverage bracket information for specified or all trading pairs, showing maximum leverage for different notional value tiers.

§Arguments
  • symbol - Optional trading pair symbol. None returns all pairs.
  • params - Optional parameters.
§Returns

Returns leverage bracket information including maximum notional value and corresponding maximum leverage for each tier.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_leverage_tiers( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, String>>, ) -> Result<BTreeMap<String, Vec<LeverageTier>>, Error>

Fetch leverage tier information for trading pairs.

§Arguments
  • symbols - Optional list of trading pairs. None fetches all pairs.
  • params - Optional parameters.
§Returns

Returns a HashMap of leverage tiers keyed by symbol.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;
let tiers = binance.fetch_leverage_tiers(None, None).await?;
Source

pub async fn set_margin_mode( &self, symbol: &str, margin_mode: &str, params: Option<HashMap<String, String>>, ) -> Result<HashMap<String, Value>, Error>

Set margin mode for a trading pair.

§Arguments
  • symbol - Trading pair symbol.
  • margin_mode - Margin mode (isolated or cross).
  • params - Optional additional parameters.
§Returns

Returns the operation result as a HashMap.

§Errors

Returns an error if:

  • Authentication credentials are missing
  • Margin mode is invalid (must be isolated or cross)
  • The market is not a futures/swap market
  • The API request fails
§Examples
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new_swap(config)?;
let result = binance.set_margin_mode("BTC/USDT:USDT", "isolated", None).await?;
Source

pub async fn set_position_mode( &self, dual_side: bool, params: Option<Value>, ) -> Result<Value, Error>

Set position mode (hedge mode or one-way mode).

This method supports both FAPI (USDT-margined) and DAPI (coin-margined) futures. By default, it uses the FAPI endpoint. To set position mode for coin-margined futures, pass type: "delivery" or type: "coin_m" in the params.

§Arguments
  • dual_side - true for hedge mode (dual-side position), false for one-way mode.
  • params - Optional parameters:
    • type: Set to "delivery" or "coin_m" to use DAPI endpoint for coin-margined futures. Defaults to FAPI endpoint if not specified.
§Returns

Returns the API response.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let binance = Binance::new_swap(ExchangeConfig::default())?;

// Enable hedge mode for USDT-margined futures (FAPI)
let result = binance.set_position_mode(true, None).await?;

// Switch back to one-way mode for USDT-margined futures
let result = binance.set_position_mode(false, None).await?;

// Enable hedge mode for coin-margined futures (DAPI)
let params = json!({"type": "delivery"});
let result = binance.set_position_mode(true, Some(params)).await?;

// Alternative: use "coin_m" type
let params = json!({"type": "coin_m"});
let result = binance.set_position_mode(false, Some(params)).await?;
Source

pub async fn fetch_position_mode( &self, params: Option<Value>, ) -> Result<bool, Error>

Fetch current position mode.

This method supports both FAPI (USDT-margined) and DAPI (coin-margined) futures. By default, it uses the FAPI endpoint. To fetch position mode for coin-margined futures, pass type: "delivery" or type: "coin_m" in the params.

§Arguments
  • params - Optional parameters:
    • type: Set to "delivery" or "coin_m" to use DAPI endpoint for coin-margined futures. Defaults to FAPI endpoint if not specified.
§Returns

Returns the current position mode:

  • true: Hedge mode (dual-side position).
  • false: One-way mode.
§Errors

Returns an error if authentication fails or the API request fails.

§Example
let binance = Binance::new_swap(ExchangeConfig::default())?;

// Fetch position mode for USDT-margined futures (FAPI)
let dual_side = binance.fetch_position_mode(None).await?;
println!("FAPI Hedge mode enabled: {}", dual_side);

// Fetch position mode for coin-margined futures (DAPI)
let params = json!({"type": "delivery"});
let dual_side = binance.fetch_position_mode(Some(params)).await?;
println!("DAPI Hedge mode enabled: {}", dual_side);

// Alternative: use "coin_m" type
let params = json!({"type": "coin_m"});
let dual_side = binance.fetch_position_mode(Some(params)).await?;
Source

pub async fn modify_isolated_position_margin( &self, symbol: &str, amount: Decimal, params: Option<Value>, ) -> Result<Value, Error>

Modify isolated position margin.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT”).
  • amount - Adjustment amount (positive to add, negative to reduce).
  • params - Optional parameters:
    • type: Operation type (1=add, 2=reduce). If provided, amount sign is ignored.
    • positionSide: Position side “LONG” | “SHORT” (required in hedge mode).
§Returns

Returns the adjustment result including the new margin amount.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_funding_rate( &self, symbol: &str, params: Option<HashMap<String, String>>, ) -> Result<FundingRate, Error>

Fetch current funding rate for a trading pair.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT:USDT”).
  • params - Optional parameters.
§Returns

Returns the current funding rate information.

§Errors

Returns an error if:

  • The market is not a futures or swap market
  • The API request fails
§Example
let binance = Binance::new_swap(ExchangeConfig::default())?;
let rate = binance.fetch_funding_rate("BTC/USDT:USDT", None).await?;
println!("Funding rate: {:?}", rate.funding_rate);
Source

pub async fn fetch_funding_rates( &self, symbols: Option<Vec<String>>, params: Option<BTreeMap<String, String>>, ) -> Result<BTreeMap<String, FundingRate>, Error>

Fetch current funding rates for multiple trading pairs.

§Arguments
  • symbols - Optional list of trading pairs. None fetches all pairs.
  • params - Optional parameters.
§Returns

Returns a HashMap of funding rates keyed by symbol.

§Errors

Returns an error if the API request fails.

§Example
let binance = Binance::new_swap(ExchangeConfig::default())?;
let rates = binance.fetch_funding_rates(None, None).await?;
println!("Found {} funding rates", rates.len());
Source

pub async fn fetch_funding_rate_history( &self, symbol: &str, since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<FundingRateHistory>, Error>

Fetch funding rate history for a trading pair.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT:USDT”).
  • since - Optional start timestamp in milliseconds.
  • limit - Optional record limit (default 100, max 1000).
  • params - Optional parameters.
§Returns

Returns a vector of historical funding rate records.

§Errors

Returns an error if:

  • The market is not a futures or swap market
  • The API request fails
§Example
let binance = Binance::new_swap(ExchangeConfig::default())?;
let history = binance.fetch_funding_rate_history("BTC/USDT:USDT", None, Some(10), None).await?;
println!("Found {} records", history.len());
Source

pub async fn fetch_funding_history( &self, symbol: Option<&str>, since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Value, Error>

Fetch funding payment history for a trading pair.

§Arguments
  • symbol - Optional trading pair symbol. None returns all.
  • since - Optional start timestamp in milliseconds.
  • limit - Optional record limit.
  • params - Optional parameters.
§Returns

Returns funding payment history as raw JSON.

§Errors

Returns an error if authentication fails or the API request fails.

Source§

impl Binance

Source

pub async fn borrow_cross_margin( &self, currency: &str, amount: f64, ) -> Result<MarginLoan, Error>

Borrow funds in cross margin mode.

§Arguments
  • currency - Currency code (e.g., “USDT”, “BTC”).
  • amount - Borrow amount.
§Returns

Returns a MarginLoan record with transaction details.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;
let loan = binance.borrow_cross_margin("USDT", 100.0).await?;
println!("Loan ID: {}", loan.id);
Source

pub async fn borrow_isolated_margin( &self, symbol: &str, currency: &str, amount: f64, ) -> Result<MarginLoan, Error>

Borrow funds in isolated margin mode.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT”).
  • currency - Currency code to borrow.
  • amount - Borrow amount.
§Returns

Returns a MarginLoan record with transaction details.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;
let loan = binance.borrow_isolated_margin("BTC/USDT", "USDT", 100.0).await?;
println!("Loan ID: {}", loan.id);
Source

pub async fn repay_cross_margin( &self, currency: &str, amount: f64, ) -> Result<MarginRepay, Error>

Repay borrowed funds in cross margin mode.

§Arguments
  • currency - Currency code (e.g., “USDT”, “BTC”).
  • amount - Repayment amount.
§Returns

Returns a MarginRepay record with transaction details.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;
let repay = binance.repay_cross_margin("USDT", 100.0).await?;
println!("Repay ID: {}", repay.id);
Source

pub async fn repay_isolated_margin( &self, symbol: &str, currency: &str, amount: Decimal, ) -> Result<MarginRepay, Error>

Repay borrowed funds in isolated margin mode.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT”).
  • currency - Currency code to repay.
  • amount - Repayment amount.
§Returns

Returns a MarginRepay record with transaction details.

§Errors

Returns an error if authentication fails or the API request fails.

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your_api_key".to_string());
config.secret = Some("your_secret".to_string());
let binance = Binance::new(config)?;
let repay = binance.repay_isolated_margin("BTC/USDT", "USDT", dec!(100)).await?;
println!("Repay ID: {}", repay.id);
Source

pub async fn fetch_margin_adjustment_history( &self, symbol: Option<&str>, since: Option<i64>, limit: Option<i64>, ) -> Result<Vec<MarginAdjustment>, Error>

Fetch margin adjustment history.

Retrieves liquidation records and margin adjustment history.

§Arguments
  • symbol - Optional trading pair symbol (required for isolated margin).
  • since - Optional start timestamp in milliseconds.
  • limit - Optional maximum number of records to return.
§Returns

Returns a vector of MarginAdjustment records.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_cross_margin_max_borrowable( &self, currency: &str, ) -> Result<Decimal, Error>

Fetch maximum borrowable amount for cross margin.

§Arguments
  • currency - Currency code (e.g., “USDT”, “BTC”).
§Returns

Returns the maximum borrowable amount as a Decimal.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_isolated_margin_max_borrowable( &self, symbol: &str, currency: &str, ) -> Result<Decimal, Error>

Fetch maximum borrowable amount for isolated margin.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT”).
  • currency - Currency code to check.
§Returns

Returns the maximum borrowable amount as a Decimal.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_max_transferable( &self, currency: &str, ) -> Result<Decimal, Error>

Fetch maximum transferable amount.

§Arguments
  • currency - Currency code (e.g., “USDT”, “BTC”).
§Returns

Returns the maximum transferable amount as a Decimal.

§Errors

Returns an error if authentication fails or the API request fails.

Source§

impl Binance

Source

pub async fn fetch_status(&self) -> Result<SystemStatus, Error>

Fetch exchange system status.

§Returns

Returns formatted exchange status information with the following structure:

{
    "status": "ok" | "maintenance",
    "updated": null,
    "eta": null,
    "url": null,
    "info": { ... }
}
Source

pub async fn fetch_markets( &self, ) -> Result<Arc<HashMap<String, Arc<Market>>>, Error>

Fetch all trading markets.

§Returns

Returns a HashMap of [Market] structures containing market information.

§Errors

Returns an error if the API request fails or response parsing fails.

§Example
let binance = Binance::new(ExchangeConfig::default())?;
let markets = binance.fetch_markets().await?;
println!("Found {} markets", markets.len());
Source

pub async fn load_markets( &self, reload: bool, ) -> Result<Arc<HashMap<String, Arc<Market>>>, Error>

Load and cache market data.

Standard CCXT method for loading all market data from the exchange. If markets are already loaded and reload is false, returns cached data.

§Arguments
  • reload - Whether to force reload market data from the API.
§Returns

Returns a HashMap containing all market data, keyed by symbol (e.g., “BTC/USDT”).

§Errors

Returns an error if the API request fails or response parsing fails.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Load markets for the first time
let markets = binance.load_markets(false).await?;
println!("Loaded {} markets", markets.len());

// Subsequent calls use cache (no API request)
let markets = binance.load_markets(false).await?;

// Force reload
let markets = binance.load_markets(true).await?;
Source

pub async fn fetch_ticker( &self, symbol: &str, params: impl IntoTickerParams, ) -> Result<Ticker, Error>

Fetch ticker for a single trading pair.

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT”).
  • params - Optional parameters to configure the ticker request.
§Returns

Returns Ticker data for the specified symbol.

§Errors

Returns an error if the market is not found or the API request fails.

Source

pub async fn fetch_tickers( &self, symbols: Option<Vec<String>>, ) -> Result<Vec<Ticker>, Error>

Fetch tickers for multiple trading pairs.

§Arguments
  • symbols - Optional list of trading pair symbols; fetches all if None.
§Returns

Returns a vector of Ticker structures.

§Errors

Returns an error if markets are not loaded or the API request fails.

Source

pub async fn fetch_order_book( &self, symbol: &str, limit: Option<u32>, ) -> Result<OrderBook, Error>

Fetch order book for a trading pair.

§Arguments
  • symbol - Trading pair symbol.
  • limit - Optional depth limit (valid values: 5, 10, 20, 50, 100, 500, 1000, 5000).
§Returns

Returns [OrderBook] data containing bids and asks.

§Errors

Returns an error if the market is not found or the API request fails.

Source

pub async fn fetch_trades( &self, symbol: &str, limit: Option<u32>, ) -> Result<Vec<Trade>, Error>

Fetch recent public trades.

§Arguments
  • symbol - Trading pair symbol.
  • limit - Optional limit on number of trades (maximum: 1000).
§Returns

Returns a vector of Trade structures, sorted by timestamp in descending order.

§Errors

Returns an error if the market is not found or the API request fails.

Source

pub async fn fetch_recent_trades( &self, symbol: &str, limit: Option<u32>, ) -> Result<Vec<Trade>, Error>

Fetch recent public trades (alias for fetch_trades).

§Arguments
  • symbol - Trading pair symbol.
  • limit - Optional limit on number of trades (default: 500, maximum: 1000).
§Returns

Returns a vector of Trade structures for recent public trades.

§Errors

Returns an error if the market is not found or the API request fails.

Source

pub async fn fetch_agg_trades( &self, symbol: &str, since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<AggTrade>, Error>

Fetch aggregated trade data.

§Arguments
  • symbol - Trading pair symbol.
  • since - Optional start timestamp in milliseconds.
  • limit - Optional limit on number of records (default: 500, maximum: 1000).
  • params - Additional parameters that may include:
    • fromId: Start from specific aggTradeId.
    • endTime: End timestamp in milliseconds.
§Returns

Returns a vector of aggregated trade records.

§Errors

Returns an error if the market is not found or the API request fails.

Source

pub async fn fetch_historical_trades( &self, symbol: &str, _since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Trade>, Error>

Fetch historical trade data (requires API key but not signature).

Note: Binance API uses fromId parameter instead of timestamp.

§Arguments
  • symbol - Trading pair symbol.
  • _since - Optional start timestamp (unused, Binance uses fromId instead).
  • limit - Optional limit on number of records (default: 500, maximum: 1000).
  • params - Additional parameters that may include:
    • fromId: Start from specific tradeId.
§Returns

Returns a vector of historical Trade records.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_24hr_stats( &self, symbol: Option<&str>, ) -> Result<Vec<Stats24hr>, Error>

Fetch 24-hour trading statistics.

§Arguments
  • symbol - Optional trading pair symbol. If None, returns statistics for all pairs.
§Returns

Returns a vector of Stats24hr structures. Single symbol returns one item, all symbols return multiple items.

§Errors

Returns an error if the market is not found or the API request fails.

Source

pub async fn fetch_trading_limits( &self, symbol: &str, ) -> Result<TradingLimits, Error>

Fetch trading limits information for a symbol.

§Arguments
  • symbol - Trading pair symbol.
§Returns

Returns TradingLimits containing minimum/maximum order constraints.

§Errors

Returns an error if the market is not found or the API request fails.

Source

pub async fn fetch_ohlcv_v2( &self, request: OhlcvRequest, ) -> Result<Vec<OHLCV>, Error>

Fetch OHLCV (candlestick) data using the builder pattern.

This is the preferred method for fetching OHLCV data. It accepts an OhlcvRequest built using the builder pattern, which provides validation and a more ergonomic API.

§Arguments
§Returns

Returns OHLCV data array: [timestamp, open, high, low, close, volume]

§Errors

Returns an error if the market is not found or the API request fails.

§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::{ExchangeConfig, types::OhlcvRequest};

let binance = Binance::new(ExchangeConfig::default())?;

// Fetch OHLCV data using the builder
let request = OhlcvRequest::builder()
    .symbol("BTC/USDT")
    .timeframe("1h")
    .limit(100)
    .build()?;

let ohlcv = binance.fetch_ohlcv_v2(request).await?;
println!("Fetched {} candles", ohlcv.len());

Requirements: 2.3, 2.6

Source

pub async fn fetch_ohlcv( &self, symbol: &str, timeframe: &str, since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, Value>>, ) -> Result<Vec<OHLCV>, Error>

👎Deprecated since 0.2.0: Use fetch_ohlcv_v2 with OhlcvRequest::builder() instead

Fetch OHLCV (candlestick) data (deprecated).

§Deprecated

This method is deprecated. Use fetch_ohlcv_v2 with OhlcvRequest::builder() instead for a more ergonomic API.

§Arguments
  • symbol - Trading pair symbol, e.g., “BTC/USDT”
  • timeframe - Time period, e.g., “1m”, “5m”, “1h”, “1d”
  • since - Start timestamp in milliseconds
  • limit - Maximum number of candlesticks to return
  • params - Optional parameters
    • price - Price type: “mark” | “index” | “premiumIndex” (futures only)
    • until - End timestamp in milliseconds
§Returns

Returns OHLCV data array: [timestamp, open, high, low, close, volume]

Source

pub async fn fetch_time(&self) -> Result<ServerTime, Error>

Fetch server time.

Retrieves the current server timestamp from the exchange.

§Returns

Returns ServerTime containing the server timestamp and formatted datetime.

§Errors

Returns an error if the API request fails.

§Example
let binance = Binance::new(ExchangeConfig::default())?;
let server_time = binance.fetch_time().await?;
println!("Server time: {} ({})", server_time.server_time, server_time.datetime);
Source

pub async fn fetch_bids_asks( &self, symbol: Option<&str>, ) -> Result<Vec<BidAsk>, Error>

Fetch best bid/ask prices.

Retrieves the best bid and ask prices for one or all trading pairs.

§Arguments
  • symbol - Optional trading pair symbol; if omitted, returns all symbols
§Returns

Returns a vector of BidAsk structures containing bid/ask prices.

§API Endpoint
  • GET /api/v3/ticker/bookTicker
  • Weight: 1 for single symbol, 2 for all symbols
  • Requires signature: No
§Errors

Returns an error if the API request fails.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Fetch bid/ask for single symbol
let bid_ask = binance.fetch_bids_asks(Some("BTC/USDT")).await?;
println!("BTC/USDT bid: {}, ask: {}", bid_ask[0].bid_price, bid_ask[0].ask_price);

// Fetch bid/ask for all symbols
let all_bid_asks = binance.fetch_bids_asks(None).await?;
println!("Total symbols: {}", all_bid_asks.len());
Source

pub async fn fetch_last_prices( &self, symbol: Option<&str>, ) -> Result<Vec<LastPrice>, Error>

Fetch latest prices.

Retrieves the most recent price for one or all trading pairs.

§Arguments
  • symbol - Optional trading pair symbol; if omitted, returns all symbols
§Returns

Returns a vector of LastPrice structures containing the latest prices.

§API Endpoint
  • GET /api/v3/ticker/price
  • Weight: 1 for single symbol, 2 for all symbols
  • Requires signature: No
§Errors

Returns an error if the API request fails.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Fetch latest price for single symbol
let price = binance.fetch_last_prices(Some("BTC/USDT")).await?;
println!("BTC/USDT last price: {}", price[0].price);

// Fetch latest prices for all symbols
let all_prices = binance.fetch_last_prices(None).await?;
println!("Total symbols: {}", all_prices.len());
Source

pub async fn fetch_mark_price( &self, symbol: Option<&str>, ) -> Result<Vec<MarkPrice>, Error>

Fetch futures mark prices.

Retrieves mark prices for futures contracts, used for calculating unrealized PnL. Includes funding rates and next funding time.

§Arguments
  • symbol - Optional trading pair symbol; if omitted, returns all futures pairs
§Returns

Returns a vector of MarkPrice structures containing mark prices and funding rates.

§API Endpoint
  • GET /fapi/v1/premiumIndex
  • Weight: 1 for single symbol, 10 for all symbols
  • Requires signature: No
§Note

This API only applies to futures markets (USDT-margined perpetual contracts).

§Errors

Returns an error if the API request fails.

§Example
let binance = Binance::new(ExchangeConfig::default())?;

// Fetch mark price for single futures symbol
let mark_price = binance.fetch_mark_price(Some("BTC/USDT:USDT")).await?;
println!("BTC/USDT mark price: {}", mark_price[0].mark_price);
println!("Funding rate: {:?}", mark_price[0].last_funding_rate);

// Fetch mark prices for all futures symbols
let all_mark_prices = binance.fetch_mark_price(None).await?;
println!("Total futures symbols: {}", all_mark_prices.len());
Source§

impl Binance

Source

pub async fn create_order_v2( &self, request: OrderRequest, ) -> Result<Order, Error>

Create a new order using the builder pattern.

This is the preferred method for creating orders. It accepts an OrderRequest built using the builder pattern, which provides compile-time validation of required fields and a more ergonomic API.

§Arguments
§Returns

Returns the created Order structure with order details.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::{ExchangeConfig, types::{OrderRequest, OrderSide, OrderType, Amount, Price}};
use rust_decimal_macros::dec;

let binance = Binance::new(ExchangeConfig::default())?;

// Create a market order using the builder
let request = OrderRequest::builder()
    .symbol("BTC/USDT")
    .side(OrderSide::Buy)
    .order_type(OrderType::Market)
    .amount(Amount::new(dec!(0.001)))
    .build();

let order = binance.create_order_v2(request).await?;
println!("Order created: {:?}", order);

Requirements: 2.2, 2.6

Source

pub async fn create_order( &self, symbol: &str, order_type: OrderType, side: OrderSide, amount: Amount, price: Option<Price>, params: Option<HashMap<String, String>>, ) -> Result<Order, Error>

👎Deprecated since 0.2.0: Use create_order_v2 with OrderRequest::builder() instead

Create a new order (deprecated).

§Deprecated

This method is deprecated. Use create_order_v2 with OrderRequest::builder() instead for a more ergonomic API.

§Arguments
  • symbol - Trading pair symbol.
  • order_type - Order type (Market, Limit, StopLoss, etc.).
  • side - Order side (Buy or Sell).
  • amount - Order quantity as Amount type.
  • price - Optional price as Price type (required for limit orders).
  • params - Additional parameters.
§Returns

Returns the created Order structure with order details.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

Source

pub async fn cancel_order(&self, id: &str, symbol: &str) -> Result<Order, Error>

Cancel an order.

§Arguments
  • id - Order ID.
  • symbol - Trading pair symbol.
§Returns

Returns the cancelled Order information.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

Source

pub async fn fetch_order(&self, id: &str, symbol: &str) -> Result<Order, Error>

Fetch order details.

§Arguments
  • id - Order ID.
  • symbol - Trading pair symbol.
§Returns

Returns the Order information.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

Source

pub async fn fetch_open_orders( &self, symbol: Option<&str>, ) -> Result<Vec<Order>, Error>

Fetch open (unfilled) orders.

§Arguments
  • symbol - Optional trading pair symbol. If None, fetches all open orders.
§Returns

Returns a vector of open Order structures.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn fetch_closed_orders( &self, symbol: Option<&str>, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<Order>, Error>

Fetch closed (completed) orders.

§Arguments
  • symbol - Optional trading pair symbol.
  • since - Optional start timestamp (milliseconds).
  • limit - Optional limit on number of orders (default 500, max 1000).
§Returns

Returns a vector of closed Order structures.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn cancel_all_orders(&self, symbol: &str) -> Result<Vec<Order>, Error>

Cancel all open orders.

§Arguments
  • symbol - Trading pair symbol.
§Returns

Returns a vector of cancelled Order structures.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

Source

pub async fn cancel_orders( &self, ids: Vec<String>, symbol: &str, ) -> Result<Vec<Order>, Error>

Cancel multiple orders.

§Arguments
  • ids - Vector of order IDs to cancel.
  • symbol - Trading pair symbol.
§Returns

Returns a vector of cancelled Order structures.

§Errors

Returns an error if authentication fails, market is not found, or the API request fails.

Source

pub async fn fetch_orders( &self, symbol: Option<&str>, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<Order>, Error>

Fetch all orders (historical and current).

§Arguments
  • symbol - Optional trading pair symbol.
  • since - Optional start timestamp (milliseconds).
  • limit - Optional limit on number of orders (default 500, max 1000).
§Returns

Returns a vector of Order structures.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn create_stop_loss_order( &self, symbol: &str, side: OrderSide, amount: Amount, stop_price: Price, price: Option<Price>, params: Option<HashMap<String, String>>, ) -> Result<Order, Error>

Create a stop-loss order.

§Arguments
  • symbol - Trading pair symbol.
  • side - Order side (Buy/Sell).
  • amount - Order quantity as Amount type.
  • stop_price - Stop-loss trigger price as Price type.
  • price - Optional limit price as Price type (if None, creates market stop-loss order).
  • params - Optional additional parameters.
§Returns

Returns the created stop-loss Order.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn create_take_profit_order( &self, symbol: &str, side: OrderSide, amount: Amount, take_profit_price: Price, price: Option<Price>, params: Option<HashMap<String, String>>, ) -> Result<Order, Error>

Create a take-profit order.

§Arguments
  • symbol - Trading pair symbol.
  • side - Order side (Buy/Sell).
  • amount - Order quantity as Amount type.
  • take_profit_price - Take-profit trigger price as Price type.
  • price - Optional limit price as Price type (if None, creates market take-profit order).
  • params - Optional additional parameters.
§Returns

Returns the created take-profit Order.

§Errors

Returns an error if authentication fails or the API request fails.

Source

pub async fn create_trailing_stop_order( &self, symbol: &str, side: OrderSide, amount: Amount, trailing_percent: Decimal, activation_price: Option<Price>, params: Option<HashMap<String, String>>, ) -> Result<Order, Error>

Create a trailing stop order.

§Arguments
  • symbol - Trading pair symbol.
  • side - Order side (Buy/Sell).
  • amount - Order quantity as Amount type.
  • trailing_percent - Trailing percentage as Decimal (e.g., 2.0 for 2%).
  • activation_price - Optional activation price as Price type (not supported for spot markets).
  • params - Optional additional parameters.
§Returns

Returns the created trailing stop Order.

§Errors

Returns an error if authentication fails or the API request fails.

Source§

impl Binance

Source

pub async fn subscribe_ticker(&self, symbol: &str) -> Result<(), Error>

Subscribes to the ticker stream for a unified symbol

§Arguments
  • symbol - Unified trading pair identifier
§Returns

Result of the subscription call

Source

pub async fn subscribe_trades(&self, symbol: &str) -> Result<(), Error>

Subscribes to the trade stream for a unified symbol

§Arguments
  • symbol - Unified trading pair identifier
§Returns

Result of the subscription call

Source

pub async fn subscribe_orderbook( &self, symbol: &str, levels: Option<u32>, ) -> Result<(), Error>

Subscribes to the order book stream for a unified symbol

§Arguments
  • symbol - Unified trading pair identifier
  • levels - Optional depth limit (default 20)
§Returns

Result of the subscription call

Source

pub async fn subscribe_kline( &self, symbol: &str, interval: &str, ) -> Result<(), Error>

Subscribes to the candlestick stream for a unified symbol

§Arguments
  • symbol - Unified trading pair identifier
  • interval - Candlestick interval identifier
§Returns

Result of the subscription call

Source

pub async fn watch_ticker( &self, symbol: &str, params: Option<HashMap<String, Value>>, ) -> Result<Ticker, Error>

Watches a ticker stream for a single unified symbol

§Arguments
  • symbol - Unified trading pair identifier (e.g. “BTC/USDT”)
  • params - Optional parameters
    • name: Channel name (ticker/miniTicker, defaults to ticker)
§Returns

Parsed ticker structure

§Example
let exchange = Binance::new(ExchangeConfig::default())?;
let ticker = exchange.watch_ticker("BTC/USDT", None).await?;
println!("Price: {}", ticker.last.unwrap_or(Price::ZERO));
Source

pub async fn watch_tickers( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, Value>>, ) -> Result<HashMap<String, Ticker>, Error>

Watches ticker streams for multiple unified symbols

§Arguments
  • symbols - Optional list of unified trading pairs (None subscribes to all)
  • params - Optional parameters
    • name: Channel name (ticker/miniTicker, defaults to ticker)
§Returns

Mapping of symbol to ticker data

§Example
let exchange = Binance::new(ExchangeConfig::default())?;

// Watch a subset of symbols
let tickers = exchange.watch_tickers(
    Some(vec!["BTC/USDT".to_string(), "ETH/USDT".to_string()]),
    None
).await?;

// Watch all symbols
let all_tickers = exchange.watch_tickers(None, None).await?;
Source

pub async fn watch_mark_price( &self, symbol: &str, params: Option<HashMap<String, Value>>, ) -> Result<Ticker, Error>

Watches the mark price stream for a futures market

§Arguments
  • symbol - Unified trading pair identifier (e.g. “BTC/USDT:USDT”)
  • params - Optional parameters
    • use1sFreq: Whether to use 1-second updates (defaults to true)
§Returns

Ticker structure representing the mark price

§Example
let exchange = Binance::new(ExchangeConfig::default())?;

// Use 1-second updates
let ticker = exchange.watch_mark_price("BTC/USDT:USDT", None).await?;

// Use 3-second updates
let mut params = HashMap::new();
params.insert("use1sFreq".to_string(), json!(false));
let ticker = exchange.watch_mark_price("BTC/USDT:USDT", Some(params)).await?;
Source

pub async fn watch_order_book( &self, symbol: &str, limit: Option<i64>, params: Option<HashMap<String, Value>>, ) -> Result<OrderBook, Error>

Watches an order book stream for a unified symbol

§Arguments
  • symbol - Unified trading pair identifier (e.g. “BTC/USDT”)
  • limit - Optional depth limit (defaults to unlimited)
  • params - Optional parameters
    • speed: Update frequency (100 or 1000 ms, defaults to 100)
§Returns

Order book snapshot populated with streaming updates

§Example
let exchange = Binance::new(ExchangeConfig::default())?;

// Watch order book with 100 ms updates
let orderbook = exchange.watch_order_book("BTC/USDT", None, None).await?;
println!("Best bid: {:?}", orderbook.best_bid());
println!("Best ask: {:?}", orderbook.best_ask());

// Watch order book limited to 100 levels with 1000 ms updates
let mut params = HashMap::new();
params.insert("speed".to_string(), json!(1000));
let orderbook = exchange.watch_order_book(
    "BTC/USDT",
    Some(100),
    Some(params)
).await?;
Source

pub async fn watch_order_books( &self, symbols: Vec<String>, limit: Option<i64>, params: Option<HashMap<String, Value>>, ) -> Result<HashMap<String, OrderBook>, Error>

Watches order books for multiple symbols

§Arguments
  • symbols - List of trading pairs (maximum 200)
  • limit - Optional depth limit
  • params - Optional parameters
    • speed: Update frequency (100 or 1000 ms)
§Returns

Mapping of symbol to corresponding order book

§Example
let exchange = Binance::new(ExchangeConfig::default())?;

let symbols = vec![
    "BTC/USDT".to_string(),
    "ETH/USDT".to_string(),
];

let orderbooks = exchange.watch_order_books(symbols, None, None).await?;
for (symbol, ob) in orderbooks {
    println!("{}: spread = {:?}", symbol, ob.spread());
}
Source

pub async fn watch_mark_prices( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, Value>>, ) -> Result<HashMap<String, Ticker>, Error>

Watches mark prices for multiple futures symbols

§Arguments
  • symbols - Optional list of symbols (None subscribes to all)
  • params - Optional parameters
    • use1sFreq: Whether to use 1-second updates (defaults to true)
§Returns

Mapping of symbol to ticker data

Source

pub async fn watch_trades( &self, symbol: &str, since: Option<i64>, limit: Option<usize>, ) -> Result<Vec<Trade>, Error>

Streams trade data for a unified symbol

§Arguments
  • symbol - Unified trading pair identifier (e.g. “BTC/USDT”)
  • since - Optional starting timestamp in milliseconds
  • limit - Optional maximum number of trades to return
§Returns

Vector of parsed trade data

Source

pub async fn watch_ohlcv( &self, symbol: &str, timeframe: &str, since: Option<i64>, limit: Option<usize>, ) -> Result<Vec<OHLCV>, Error>

Streams OHLCV data for a unified symbol

§Arguments
  • symbol - Unified trading pair identifier (e.g. “BTC/USDT”)
  • timeframe - Candlestick interval (e.g. “1m”, “5m”, “1h”, “1d”)
  • since - Optional starting timestamp in milliseconds
  • limit - Optional maximum number of entries to return
§Returns

Vector of OHLCV entries

Source

pub async fn watch_bids_asks(&self, symbol: &str) -> Result<BidAsk, Error>

Streams the best bid/ask data for a unified symbol

§Arguments
  • symbol - Unified trading pair identifier (e.g. “BTC/USDT”)
§Returns

Latest bid/ask snapshot

Source

pub async fn watch_balance( self: Arc<Binance>, params: Option<HashMap<String, Value>>, ) -> Result<Balance, Error>

Streams account balance changes (private user data stream)

§Arguments
  • params - Optional parameters
    • type: Account type (spot/future/delivery/margin, etc.)
    • fetchBalanceSnapshot: Whether to fetch an initial snapshot (default false)
    • awaitBalanceSnapshot: Whether to wait for snapshot completion (default true)
§Returns

Updated account balances

§Example
let mut config = ExchangeConfig::default();
config.api_key = Some("your-api-key".to_string());
config.secret = Some("your-secret".to_string());
let exchange = Arc::new(Binance::new(config)?);

// Watch spot account balance
let balance = exchange.clone().watch_balance(None).await?;

// Watch futures account balance
let mut params = HashMap::new();
params.insert("type".to_string(), json!("future"));
let futures_balance = exchange.clone().watch_balance(Some(params)).await?;
Source

pub async fn watch_orders( self: Arc<Binance>, symbol: Option<&str>, since: Option<i64>, limit: Option<usize>, _params: Option<HashMap<String, Value>>, ) -> Result<Vec<Order>, Error>

Watches authenticated order updates via the user data stream

Streams real-time order status changes delivered by Binance user data WebSocket messages

§Arguments
  • symbol - Optional trading pair filter (e.g. “BTC/USDT”)
  • since - Optional starting timestamp in milliseconds
  • limit - Optional maximum number of orders to return
  • params - Optional additional parameters
§Returns

Orders returned in descending chronological order

§Examples
use std::sync::Arc;
use ccxt_exchanges::binance::Binance;

async fn example() -> Result<(), Box<dyn std::error::Error>> {
    let exchange = Arc::new(Binance::new(Default::default())?);

    // Watch all order updates
    let orders = exchange.clone().watch_orders(None, None, None, None).await?;
    println!("Received {} order updates", orders.len());

    // Watch updates for a specific trading pair
    let btc_orders = exchange.clone().watch_orders(Some("BTC/USDT"), None, None, None).await?;
    println!("BTC/USDT orders: {:?}", btc_orders);

    Ok(())
}
Source

pub async fn watch_my_trades( self: Arc<Binance>, symbol: Option<&str>, since: Option<i64>, limit: Option<usize>, _params: Option<HashMap<String, Value>>, ) -> Result<Vec<Trade>, Error>

Watches authenticated user trade updates

§Arguments
  • symbol - Optional trading pair to filter (None subscribes to all)
  • since - Starting timestamp in milliseconds
  • limit - Maximum number of trades to return
  • params - Additional parameters
§Returns

List of trade records

§Example
use std::sync::Arc;
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = ExchangeConfig::default();
    config.api_key = Some("your-api-key".to_string());
    config.secret = Some("your-secret".to_string());
    let exchange = Arc::new(Binance::new(config)?);

    // Subscribe to BTC/USDT trade updates
    let trades = exchange.clone().watch_my_trades(Some("BTC/USDT"), None, None, None).await?;
    println!("My trades: {:?}", trades);
    Ok(())
}
Source

pub async fn watch_positions( self: Arc<Binance>, symbols: Option<Vec<String>>, since: Option<i64>, limit: Option<usize>, _params: Option<HashMap<String, Value>>, ) -> Result<Vec<Position>, Error>

Watches authenticated futures position updates

Receives ACCOUNT_UPDATE events via the user data stream to track changes to futures Supports both USD-margined (USD-M) and coin-margined (COIN-M) contracts.

§Arguments
  • symbols - Optional list of symbols (None subscribes to all positions)
  • since - Optional starting timestamp
  • limit - Optional maximum number of positions to return
  • params - Optional parameters
    • type: Market type (future/delivery, default future)
    • subType: Subtype (linear/inverse)
§Returns

Collection of positions

§Implementation Details
  1. Subscribe to ACCOUNT_UPDATE events through the user data stream.
  2. Parse the position data contained in the P array.
  3. Update the internal position cache.
  4. Filter results according to the provided arguments.
§WebSocket Message Format
{
  "e": "ACCOUNT_UPDATE",
  "T": 1667881353112,
  "E": 1667881353115,
  "a": {
    "P": [
      {
        "s": "BTCUSDT",
        "pa": "-0.089",
        "ep": "19700.03933",
        "up": "1.53058860",
        "mt": "isolated",
        "ps": "BOTH"
      }
    ]
  }
}
§Example
let exchange = Arc::new(Binance::new(ExchangeConfig::default())?);

// Watch all positions
let positions = exchange.clone().watch_positions(None, None, None, None).await?;
for pos in positions {
    println!("Symbol: {}, Side: {:?}, Contracts: {:?}",
             pos.symbol, pos.side, pos.contracts);
}

// Watch a subset of symbols
let symbols = vec!["BTC/USDT".to_string(), "ETH/USDT".to_string()];
let positions = exchange.clone().watch_positions(Some(symbols), None, Some(10), None).await?;
Source§

impl Binance

Source

pub fn builder() -> BinanceBuilder

Creates a new Binance instance using the builder pattern.

This is the recommended way to create a Binance instance.

§Example
use ccxt_exchanges::binance::Binance;

let binance = Binance::builder()
    .api_key("your-api-key")
    .secret("your-secret")
    .sandbox(true)
    .build()
    .unwrap();
Source

pub fn new(config: ExchangeConfig) -> Result<Binance, Error>

Creates a new Binance instance.

§Arguments
  • config - Exchange configuration.
§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;

let config = ExchangeConfig {
    id: "binance".to_string(),
    name: "Binance".to_string(),
    api_key: Some("your-api-key".to_string()),
    secret: Some("your-secret".to_string()),
    ..Default::default()
};

let binance = Binance::new(config).unwrap();
Source

pub fn new_with_options( config: ExchangeConfig, options: BinanceOptions, ) -> Result<Binance, Error>

Creates a new Binance instance with custom options.

This is used internally by the builder pattern.

§Arguments
  • config - Exchange configuration.
  • options - Binance-specific options.
§Example
use ccxt_exchanges::binance::{Binance, BinanceOptions};
use ccxt_core::ExchangeConfig;
use ccxt_core::types::default_type::DefaultType;

let config = ExchangeConfig::default();
let options = BinanceOptions {
    default_type: DefaultType::Swap,
    ..Default::default()
};

let binance = Binance::new_with_options(config, options).unwrap();
Source

pub fn new_swap(config: ExchangeConfig) -> Result<Binance, Error>

Creates a new Binance futures instance for perpetual contracts.

§Arguments
  • config - Exchange configuration.
§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;

let config = ExchangeConfig::default();
let futures = Binance::new_swap(config).unwrap();
Source

pub fn base(&self) -> &BaseExchange

Returns a reference to the base exchange.

Source

pub fn base_mut(&mut self) -> &mut BaseExchange

Returns a mutable reference to the base exchange.

Source

pub fn options(&self) -> &BinanceOptions

Returns the Binance options.

Source

pub fn set_options(&mut self, options: BinanceOptions)

Sets the Binance options.

Source

pub fn time_sync(&self) -> &Arc<TimeSyncManager>

Returns a reference to the time synchronization manager.

The TimeSyncManager caches the time offset between local system time and Binance server time, reducing network round-trips for signed requests.

§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;

let binance = Binance::new(ExchangeConfig::default()).unwrap();
let time_sync = binance.time_sync();
println!("Time sync initialized: {}", time_sync.is_initialized());
Source

pub fn signed_request( &self, endpoint: impl Into<String>, ) -> SignedRequestBuilder<'_>

Creates a new signed request builder for the given endpoint.

This is the recommended way to make authenticated API requests. The builder handles credential validation, timestamp generation, parameter signing, and request execution.

§Arguments
  • endpoint - Full API endpoint URL
§Example
use ccxt_exchanges::binance::{Binance, HttpMethod};
use ccxt_core::ExchangeConfig;

let binance = Binance::new(ExchangeConfig::default())?;

// Simple GET request
let response = binance.signed_request("https://api.binance.com/api/v3/account")
    .execute()
    .await?;

// POST request with parameters
let response = binance.signed_request("https://api.binance.com/api/v3/order")
    .method(HttpMethod::Post)
    .param("symbol", "BTCUSDT")
    .param("side", "BUY")
    .execute()
    .await?;
Source

pub fn id(&self) -> &'static str

Returns the exchange ID.

Source

pub fn name(&self) -> &'static str

Returns the exchange name.

Source

pub fn version(&self) -> &'static str

Returns the API version.

Source

pub fn certified(&self) -> bool

Returns true if the exchange is CCXT-certified.

Source

pub fn pro(&self) -> bool

Returns true if Pro version (WebSocket) is supported.

Source

pub fn rate_limit(&self) -> u32

Returns the rate limit in requests per second.

Source

pub fn is_sandbox(&self) -> bool

Returns true if sandbox/testnet mode is enabled.

Sandbox mode is enabled when either:

  • config.sandbox is set to true
  • options.test is set to true
§Returns

true if sandbox mode is enabled, false otherwise.

§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;

let config = ExchangeConfig {
    sandbox: true,
    ..Default::default()
};
let binance = Binance::new(config).unwrap();
assert!(binance.is_sandbox());
Source

pub fn timeframes(&self) -> HashMap<String, String>

Returns the supported timeframes.

Source

pub fn urls(&self) -> BinanceUrls

Returns the API URLs.

Source

pub fn get_ws_url(&self) -> String

Determines the WebSocket URL based on default_type and default_sub_type.

This method implements the endpoint routing logic according to:

  • Spot/Margin: Uses the standard WebSocket endpoint
  • Swap/Futures with Linear sub-type: Uses FAPI WebSocket endpoint
  • Swap/Futures with Inverse sub-type: Uses DAPI WebSocket endpoint
  • Option: Uses EAPI WebSocket endpoint
§Returns

The appropriate WebSocket URL string.

§Note

This method delegates to BinanceEndpointRouter::default_ws_endpoint(). The routing logic is centralized in the trait implementation.

Source

pub fn get_rest_url_public(&self) -> String

Returns the public REST API base URL based on default_type and default_sub_type.

This method implements the endpoint routing logic for public REST API calls:

  • Spot: Uses the public API endpoint (api.binance.com)
  • Margin: Uses the SAPI endpoint (api.binance.com/sapi)
  • Swap/Futures with Linear sub-type: Uses FAPI endpoint (fapi.binance.com)
  • Swap/Futures with Inverse sub-type: Uses DAPI endpoint (dapi.binance.com)
  • Option: Uses EAPI endpoint (eapi.binance.com)
§Returns

The appropriate REST API base URL string.

§Note

This method delegates to BinanceEndpointRouter::default_rest_endpoint(EndpointType::Public). The routing logic is centralized in the trait implementation.

§Example
use ccxt_exchanges::binance::{Binance, BinanceOptions};
use ccxt_core::ExchangeConfig;
use ccxt_core::types::default_type::{DefaultType, DefaultSubType};

let options = BinanceOptions {
    default_type: DefaultType::Swap,
    default_sub_type: Some(DefaultSubType::Linear),
    ..Default::default()
};
let binance = Binance::new_with_options(ExchangeConfig::default(), options).unwrap();
let url = binance.get_rest_url_public();
assert!(url.contains("fapi.binance.com"));
Source

pub fn get_rest_url_private(&self) -> String

Returns the private REST API base URL based on default_type and default_sub_type.

This method implements the endpoint routing logic for private REST API calls:

  • Spot: Uses the private API endpoint (api.binance.com)
  • Margin: Uses the SAPI endpoint (api.binance.com/sapi)
  • Swap/Futures with Linear sub-type: Uses FAPI endpoint (fapi.binance.com)
  • Swap/Futures with Inverse sub-type: Uses DAPI endpoint (dapi.binance.com)
  • Option: Uses EAPI endpoint (eapi.binance.com)
§Returns

The appropriate REST API base URL string.

§Note

This method delegates to BinanceEndpointRouter::default_rest_endpoint(EndpointType::Private). The routing logic is centralized in the trait implementation.

§Example
use ccxt_exchanges::binance::{Binance, BinanceOptions};
use ccxt_core::ExchangeConfig;
use ccxt_core::types::default_type::{DefaultType, DefaultSubType};

let options = BinanceOptions {
    default_type: DefaultType::Swap,
    default_sub_type: Some(DefaultSubType::Inverse),
    ..Default::default()
};
let binance = Binance::new_with_options(ExchangeConfig::default(), options).unwrap();
let url = binance.get_rest_url_private();
assert!(url.contains("dapi.binance.com"));
Source

pub fn is_contract_type(&self) -> bool

Checks if the current default_type is a contract type (Swap, Futures, or Option).

This is useful for determining whether contract-specific API endpoints should be used.

§Returns

true if the default_type is Swap, Futures, or Option; false otherwise.

Source

pub fn is_inverse(&self) -> bool

Checks if the current configuration uses inverse (coin-margined) contracts.

§Returns

true if default_sub_type is Inverse; false otherwise.

Source

pub fn is_linear(&self) -> bool

Checks if the current configuration uses linear (USDT-margined) contracts.

§Returns

true if default_sub_type is Linear or not specified (defaults to Linear); false otherwise.

Source

pub fn create_ws(&self) -> BinanceWs

Creates a WebSocket client for public data streams.

Used for subscribing to public data streams (ticker, orderbook, trades, etc.). The WebSocket endpoint is automatically selected based on default_type and default_sub_type:

  • Spot/Margin: wss://stream.binance.com:9443/ws
  • Swap/Futures (Linear): wss://fstream.binance.com/ws
  • Swap/Futures (Inverse): wss://dstream.binance.com/ws
  • Option: wss://nbstream.binance.com/eoptions/ws
§Returns

Returns a BinanceWs instance.

§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;

let binance = Binance::new(ExchangeConfig::default())?;
let ws = binance.create_ws();
ws.connect().await?;
Source

pub fn create_authenticated_ws(self: &Arc<Binance>) -> BinanceWs

Creates an authenticated WebSocket client for user data streams.

Used for subscribing to private data streams (account balance, order updates, trade history, etc.). Requires API key configuration. The WebSocket endpoint is automatically selected based on default_type and default_sub_type.

§Returns

Returns a BinanceWs instance with listen key manager.

§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;
use std::sync::Arc;

let config = ExchangeConfig {
    api_key: Some("your-api-key".to_string()),
    secret: Some("your-secret".to_string()),
    ..Default::default()
};
let binance = Arc::new(Binance::new(config)?);
let ws = binance.create_authenticated_ws();
ws.connect_user_stream().await?;

Trait Implementations§

Source§

impl BinanceEndpointRouter for Binance

Source§

fn rest_endpoint(&self, market: &Market, endpoint_type: EndpointType) -> String

Returns the REST API endpoint for a specific market. Read more
Source§

fn ws_endpoint(&self, market: &Market) -> String

Returns the WebSocket endpoint for a specific market. Read more
Source§

fn default_rest_endpoint(&self, endpoint_type: EndpointType) -> String

Returns the default REST endpoint when no specific market is provided. Read more
Source§

fn default_ws_endpoint(&self) -> String

Returns the default WebSocket endpoint when no specific market is provided. Read more
Source§

fn sapi_endpoint(&self) -> String

Returns the SAPI (Spot API) endpoint. Read more
Source§

fn papi_endpoint(&self) -> String

Returns the Portfolio Margin API (PAPI) endpoint. Read more
Source§

impl Debug for Binance

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Exchange for Binance

Source§

fn id(&self) -> &'static str

Returns the exchange identifier (e.g., “binance”, “coinbase”) Read more
Source§

fn name(&self) -> &'static str

Returns the human-readable exchange name (e.g., “Binance”, “Coinbase”)
Source§

fn version(&self) -> &'static str

Returns the API version string
Source§

fn certified(&self) -> bool

Returns whether this exchange is CCXT certified Read more
Source§

fn has_websocket(&self) -> bool

Returns whether this exchange supports WebSocket (pro features)
Source§

fn capabilities(&self) -> ExchangeCapabilities

Returns the exchange capabilities Read more
Source§

fn timeframes(&self) -> Vec<Timeframe>

Returns supported timeframes for OHLCV data
Source§

fn rate_limit(&self) -> u32

Returns the rate limit (requests per second)
Source§

fn fetch_markets<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<Vec<Market>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Binance: 'async_trait,

Fetch all available markets Read more
Source§

fn load_markets<'life0, 'async_trait>( &'life0 self, reload: bool, ) -> Pin<Box<dyn Future<Output = Result<Arc<HashMap<String, Arc<Market>>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Binance: 'async_trait,

Load markets and cache them Read more
Source§

fn fetch_ticker<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Ticker, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Fetch ticker for a single symbol Read more
Source§

fn fetch_tickers<'life0, 'life1, 'async_trait>( &'life0 self, symbols: Option<&'life1 [String]>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Ticker>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Fetch tickers for multiple symbols (or all if None) Read more
Source§

fn fetch_order_book<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, limit: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<OrderBook, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Fetch order book for a symbol Read more
Source§

fn fetch_trades<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, limit: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Trade>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Fetch recent public trades Read more
Source§

fn fetch_ohlcv<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, timeframe: Timeframe, since: Option<i64>, limit: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Ohlcv>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Fetch OHLCV candlestick data Read more
Source§

fn create_order<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, order_type: OrderType, side: OrderSide, amount: Amount, price: Option<Price>, ) -> Pin<Box<dyn Future<Output = Result<Order, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Create a new order Read more
Source§

fn cancel_order<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, id: &'life1 str, symbol: Option<&'life2 str>, ) -> Pin<Box<dyn Future<Output = Result<Order, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, Binance: 'async_trait,

Cancel an existing order Read more
Source§

fn cancel_all_orders<'life0, 'life1, 'async_trait>( &'life0 self, symbol: Option<&'life1 str>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Order>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Cancel all orders (optionally for a specific symbol) Read more
Source§

fn fetch_order<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, id: &'life1 str, symbol: Option<&'life2 str>, ) -> Pin<Box<dyn Future<Output = Result<Order, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, Binance: 'async_trait,

Fetch a specific order by ID Read more
Source§

fn fetch_open_orders<'life0, 'life1, 'async_trait>( &'life0 self, symbol: Option<&'life1 str>, _since: Option<i64>, _limit: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Order>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Fetch all open orders Read more
Source§

fn fetch_closed_orders<'life0, 'life1, 'async_trait>( &'life0 self, symbol: Option<&'life1 str>, since: Option<i64>, limit: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Order>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Fetch closed orders Read more
Source§

fn fetch_balance<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<Balance, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Binance: 'async_trait,

Fetch account balance Read more
Source§

fn fetch_my_trades<'life0, 'life1, 'async_trait>( &'life0 self, symbol: Option<&'life1 str>, since: Option<i64>, limit: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Trade>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Fetch user’s trade history Read more
Source§

fn market<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Arc<Market>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Get a specific market by symbol Read more
Source§

fn markets<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Arc<HashMap<String, Arc<Market>>>> + Send + 'async_trait>>
where 'life0: 'async_trait, Binance: 'async_trait,

Get all cached markets Read more
Source§

fn is_symbol_active<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, ) -> Pin<Box<dyn Future<Output = bool> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait,

Check if a symbol is valid and active Read more
Source§

impl PublicExchange for Binance

Source§

fn id(&self) -> &'static str

Returns the exchange identifier (e.g., “binance”, “okx”). Read more
Source§

fn name(&self) -> &'static str

Returns the human-readable exchange name (e.g., “Binance”, “OKX”).
Source§

fn version(&self) -> &'static str

Returns the API version string. Read more
Source§

fn certified(&self) -> bool

Returns whether this exchange implementation is CCXT certified. Read more
Source§

fn capabilities(&self) -> ExchangeCapabilities

Returns the exchange capabilities. Read more
Source§

fn timeframes(&self) -> Vec<Timeframe>

Returns supported timeframes for OHLCV data. Read more
Source§

fn rate_limit(&self) -> u32

Returns the rate limit (requests per second). Read more
Source§

fn has_websocket(&self) -> bool

Returns whether WebSocket is supported. Read more
Source§

fn is_sandbox(&self) -> bool

Returns whether the exchange is in sandbox/testnet mode. Read more
Source§

fn countries(&self) -> Vec<&'static str>

Returns the exchange’s countries of operation. Read more
Source§

fn urls(&self) -> Vec<&'static str>

Returns the exchange’s website URLs. Read more
Source§

fn has_capability(&self, name: &str) -> bool

Check if a specific capability is supported. Read more
Source§

impl WsExchange for Binance

Source§

fn ws_connect<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Binance: 'async_trait,

Connect to the WebSocket server Read more
Source§

fn ws_disconnect<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Binance: 'async_trait,

Disconnect from the WebSocket server Read more
Source§

fn ws_is_connected(&self) -> bool

Check if WebSocket is connected Read more
Source§

fn ws_state(&self) -> WsConnectionState

Get WebSocket connection state Read more
Source§

fn watch_ticker<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Ticker, Error>> + Send>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Watch ticker updates for a symbol Read more
Source§

fn watch_tickers<'life0, 'life1, 'async_trait>( &'life0 self, symbols: &'life1 [String], ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Vec<Ticker>, Error>> + Send>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Watch tickers for multiple symbols Read more
Source§

fn watch_order_book<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, limit: Option<u32>, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<OrderBook, Error>> + Send>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Watch order book updates Read more
Source§

fn watch_trades<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Vec<Trade>, Error>> + Send>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Watch public trades Read more
Source§

fn watch_ohlcv<'life0, 'life1, 'async_trait>( &'life0 self, symbol: &'life1 str, timeframe: Timeframe, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Ohlcv, Error>> + Send>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Watch OHLCV candlestick updates Read more
Source§

fn watch_balance<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Balance, Error>> + Send>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Binance: 'async_trait,

Watch account balance updates Read more
Source§

fn watch_orders<'life0, 'life1, 'async_trait>( &'life0 self, _symbol: Option<&'life1 str>, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Order, Error>> + Send>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Watch order updates Read more
Source§

fn watch_my_trades<'life0, 'life1, 'async_trait>( &'life0 self, _symbol: Option<&'life1 str>, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Trade, Error>> + Send>>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Binance: 'async_trait,

Watch user trade updates Read more
Source§

fn subscribe<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, channel: &'life1 str, symbol: Option<&'life2 str>, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, Binance: 'async_trait,

Subscribe to a channel Read more
Source§

fn unsubscribe<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, channel: &'life1 str, symbol: Option<&'life2 str>, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, Binance: 'async_trait,

Unsubscribe from a channel Read more
Source§

fn subscriptions(&self) -> Vec<String>

Get list of active subscriptions Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ExchangeExt for T
where T: Exchange + ?Sized,

Source§

fn supports_market_data(&self) -> bool

Check if this exchange implements the MarketData trait. Read more
Source§

fn supports_trading(&self) -> bool

Check if this exchange implements the Trading trait. Read more
Source§

fn supports_account(&self) -> bool

Check if this exchange implements the Account trait. Read more
Source§

fn supports_margin(&self) -> bool

Check if this exchange implements the Margin trait. Read more
Source§

fn supports_funding(&self) -> bool

Check if this exchange implements the Funding trait. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> FullExchange for T
where T: Exchange + WsExchange,