pub struct Binance { /* private fields */ }Expand description
Binance exchange structure.
Implementations§
Source§impl Binance
impl Binance
Sourcepub async fn get_signing_timestamp(&self) -> Result<i64>
pub async fn get_signing_timestamp(&self) -> Result<i64>
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
Sourcepub async fn sync_time(&self) -> Result<()>
pub async fn sync_time(&self) -> Result<()>
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
Sourcepub fn is_timestamp_error(&self, error: &Error) -> bool
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 Code | Message | Meaning |
|---|---|---|
| -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
Sourcepub async fn execute_signed_request_with_retry<T, F, Fut>(
&self,
request_fn: F,
) -> Result<T>
pub async fn execute_signed_request_with_retry<T, F, Fut>( &self, request_fn: F, ) -> Result<T>
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
- Execute the request with the current timestamp
- If the request fails with a timestamp error: a. Resync time with the server b. Retry the request with a fresh timestamp
- 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 requestF- The async function that performs the signed request
§Arguments
request_fn- An async function that takes a timestamp (i64) and returns aResult<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
Sourcepub async fn handle_timestamp_error_and_resync(&self, error: &Error) -> bool
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
impl Binance
Sourcepub async fn fetch_balance_simple(&self) -> Result<Balance>
pub async fn fetch_balance_simple(&self) -> Result<Balance>
Sourcepub async fn fetch_balance(
&self,
account_type: Option<AccountType>,
) -> Result<Balance>
pub async fn fetch_balance( &self, account_type: Option<AccountType>, ) -> Result<Balance>
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 accountIsolatedMargin- Isolated margin accountFutures- USDT-margined futures (linear)Delivery- Coin-margined futures (inverse)Funding- Funding walletOption- 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?;Sourcepub async fn fetch_balance_with_params(
&self,
params: BalanceFetchParams,
) -> Result<Balance>
pub async fn fetch_balance_with_params( &self, params: BalanceFetchParams, ) -> Result<Balance>
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 tradingsymbols- Symbols for isolated margin queriesportfolio_margin- Use Portfolio Margin APIsub_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?;Sourcepub async fn fetch_my_trades(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<u32>,
) -> Result<Vec<Trade>>
pub async fn fetch_my_trades( &self, symbol: &str, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<Trade>>
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.
Sourcepub async fn fetch_my_recent_trades(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<Trade>>
pub async fn fetch_my_recent_trades( &self, symbol: &str, since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Trade>>
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);
}Sourcepub async fn fetch_currencies(&self) -> Result<Vec<Currency>>
pub async fn fetch_currencies(&self) -> Result<Vec<Currency>>
Sourcepub async fn fetch_trading_fee(
&self,
symbol: &str,
params: Option<HashMap<String, String>>,
) -> Result<FeeTradingFee>
pub async fn fetch_trading_fee( &self, symbol: &str, params: Option<HashMap<String, String>>, ) -> Result<FeeTradingFee>
Fetch trading fees for a symbol.
§Arguments
symbol- Trading pair symbol.params- Optional parameters. SupportsportfolioMarginkey 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);Sourcepub async fn fetch_trading_fees(
&self,
symbols: Option<Vec<String>>,
params: Option<HashMap<String, String>>,
) -> Result<HashMap<String, FeeTradingFee>>
pub async fn fetch_trading_fees( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, String>>, ) -> Result<HashMap<String, FeeTradingFee>>
Fetch trading fees for multiple symbols.
§Arguments
symbols- Optional list of trading pair symbols.Nonefetches 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);
}Sourcepub async fn create_listen_key(&self) -> Result<String>
pub async fn create_listen_key(&self) -> Result<String>
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);Sourcepub async fn refresh_listen_key(&self, listen_key: &str) -> Result<()>
pub async fn refresh_listen_key(&self, listen_key: &str) -> Result<()>
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
Sourcepub async fn delete_listen_key(&self, listen_key: &str) -> Result<()>
pub async fn delete_listen_key(&self, listen_key: &str) -> Result<()>
Source§impl Binance
impl Binance
Sourcepub async fn set_position_mode_dapi(
&self,
dual_side: bool,
params: Option<Value>,
) -> Result<Value>
pub async fn set_position_mode_dapi( &self, dual_side: bool, params: Option<Value>, ) -> Result<Value>
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-truefor hedge mode (dual-side position),falsefor 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
}
}Sourcepub async fn fetch_position_mode_dapi(
&self,
params: Option<Value>,
) -> Result<bool>
pub async fn fetch_position_mode_dapi( &self, params: Option<Value>, ) -> Result<bool>
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),
}Sourcepub async fn fetch_dapi_account(&self, params: Option<Value>) -> Result<Value>
pub async fn fetch_dapi_account(&self, params: Option<Value>) -> Result<Value>
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 balancetotalUnrealizedProfit: Total unrealized profittotalMarginBalance: Total margin balanceavailableBalance: Available balance for new positionsmaxWithdrawAmount: Maximum withdraw amountassets: List of asset balancespositions: 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
}
}Sourcepub async fn fetch_dapi_income(
&self,
symbol: Option<&str>,
income_type: Option<&str>,
since: Option<i64>,
limit: Option<u32>,
params: Option<Value>,
) -> Result<Value>
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>
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 symbolincomeType: Type of incomeincome: Income amountasset: Asset currencyinfo: Additional informationtime: TimestamptranId: Transaction IDtradeId: 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),
}Sourcepub async fn fetch_dapi_commission_rate(
&self,
symbol: &str,
params: Option<Value>,
) -> Result<Value>
pub async fn fetch_dapi_commission_rate( &self, symbol: &str, params: Option<Value>, ) -> Result<Value>
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 symbolmakerCommissionRate: 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),
}Sourcepub async fn fetch_dapi_adl_quantile(
&self,
symbol: Option<&str>,
params: Option<Value>,
) -> Result<Value>
pub async fn fetch_dapi_adl_quantile( &self, symbol: Option<&str>, params: Option<Value>, ) -> Result<Value>
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 symboladlQuantile: 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),
}Sourcepub 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>
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>
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 IDsymbol: Trading pair symbolstatus: Order statusclientOrderId: Client order IDprice: Order priceavgPrice: Average fill priceorigQty: Original quantityexecutedQty: Executed quantitycumBase: Cumulative base assettimeInForce: Time in forcetype: Order typereduceOnly: Whether reduce-onlyside: Order side (BUY/SELL)positionSide: Position side (LONG/SHORT/BOTH)origType: Original order typetime: Order timeupdateTime: 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
impl Binance
Sourcepub async fn fetch_deposit_address(
&self,
code: &str,
params: Option<BTreeMap<String, String>>,
) -> Result<DepositAddress>
pub async fn fetch_deposit_address( &self, code: &str, params: Option<BTreeMap<String, String>>, ) -> Result<DepositAddress>
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);Sourcepub async fn withdraw(
&self,
code: &str,
amount: &str,
address: &str,
params: Option<BTreeMap<String, String>>,
) -> Result<Transaction>
pub async fn withdraw( &self, code: &str, amount: &str, address: &str, params: Option<BTreeMap<String, String>>, ) -> Result<Transaction>
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 fortag).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?;Sourcepub async fn fetch_deposits(
&self,
code: Option<&str>,
since: Option<i64>,
limit: Option<i64>,
params: Option<BTreeMap<String, String>>,
) -> Result<Vec<Transaction>>
pub async fn fetch_deposits( &self, code: Option<&str>, since: Option<i64>, limit: Option<i64>, params: Option<BTreeMap<String, String>>, ) -> Result<Vec<Transaction>>
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?;Sourcepub async fn fetch_withdrawals(
&self,
code: Option<&str>,
since: Option<i64>,
limit: Option<i64>,
params: Option<BTreeMap<String, String>>,
) -> Result<Vec<Transaction>>
pub async fn fetch_withdrawals( &self, code: Option<&str>, since: Option<i64>, limit: Option<i64>, params: Option<BTreeMap<String, String>>, ) -> Result<Vec<Transaction>>
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?;Sourcepub async fn fetch_deposit_withdraw_fees(
&self,
currency: Option<&str>,
params: Option<BTreeMap<String, String>>,
) -> Result<Vec<DepositWithdrawFee>>
pub async fn fetch_deposit_withdraw_fees( &self, currency: Option<&str>, params: Option<BTreeMap<String, String>>, ) -> Result<Vec<DepositWithdrawFee>>
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
impl Binance
Sourcepub async fn fetch_funding_rate(
&self,
symbol: &str,
params: Option<HashMap<String, String>>,
) -> Result<FeeFundingRate>
pub async fn fetch_funding_rate( &self, symbol: &str, params: Option<HashMap<String, String>>, ) -> Result<FeeFundingRate>
Fetch current funding rate for a trading pair.
Sourcepub async fn fetch_funding_rates(
&self,
symbols: Option<Vec<String>>,
params: Option<BTreeMap<String, String>>,
) -> Result<BTreeMap<String, FeeFundingRate>>
pub async fn fetch_funding_rates( &self, symbols: Option<Vec<String>>, params: Option<BTreeMap<String, String>>, ) -> Result<BTreeMap<String, FeeFundingRate>>
Fetch current funding rates for multiple trading pairs.
Source§impl Binance
impl Binance
Sourcepub async fn fetch_leverages(
&self,
symbols: Option<Vec<String>>,
params: Option<Value>,
) -> Result<BTreeMap<String, Leverage>>
pub async fn fetch_leverages( &self, symbols: Option<Vec<String>>, params: Option<Value>, ) -> Result<BTreeMap<String, Leverage>>
Fetch leverage settings for multiple trading pairs.
Sourcepub async fn fetch_leverage(
&self,
symbol: &str,
params: Option<Value>,
) -> Result<Leverage>
pub async fn fetch_leverage( &self, symbol: &str, params: Option<Value>, ) -> Result<Leverage>
Fetch leverage settings for a single trading pair.
Sourcepub async fn set_leverage(
&self,
symbol: &str,
leverage: i64,
params: Option<HashMap<String, String>>,
) -> Result<HashMap<String, Value>>
pub async fn set_leverage( &self, symbol: &str, leverage: i64, params: Option<HashMap<String, String>>, ) -> Result<HashMap<String, Value>>
Set leverage multiplier for a trading pair.
Source§impl Binance
impl Binance
Sourcepub async fn set_margin_mode(
&self,
symbol: &str,
margin_mode: &str,
params: Option<HashMap<String, String>>,
) -> Result<HashMap<String, Value>>
pub async fn set_margin_mode( &self, symbol: &str, margin_mode: &str, params: Option<HashMap<String, String>>, ) -> Result<HashMap<String, Value>>
Set margin mode for a trading pair.
Sourcepub async fn set_position_mode(
&self,
dual_side: bool,
params: Option<Value>,
) -> Result<Value>
pub async fn set_position_mode( &self, dual_side: bool, params: Option<Value>, ) -> Result<Value>
Set position mode (hedge mode or one-way mode).
Source§impl Binance
impl Binance
Sourcepub async fn fetch_position(
&self,
symbol: &str,
params: Option<Value>,
) -> Result<Position>
pub async fn fetch_position( &self, symbol: &str, params: Option<Value>, ) -> Result<Position>
Fetch a single position for a trading pair.
Sourcepub async fn fetch_positions(
&self,
symbols: Option<Vec<String>>,
params: Option<Value>,
) -> Result<Vec<Position>>
pub async fn fetch_positions( &self, symbols: Option<Vec<String>>, params: Option<Value>, ) -> Result<Vec<Position>>
Fetch all positions.
Source§impl Binance
impl Binance
Sourcepub async fn borrow_cross_margin(
&self,
currency: &str,
amount: f64,
) -> Result<MarginLoan>
pub async fn borrow_cross_margin( &self, currency: &str, amount: f64, ) -> Result<MarginLoan>
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);Sourcepub async fn borrow_isolated_margin(
&self,
symbol: &str,
currency: &str,
amount: f64,
) -> Result<MarginLoan>
pub async fn borrow_isolated_margin( &self, symbol: &str, currency: &str, amount: f64, ) -> Result<MarginLoan>
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);Sourcepub async fn repay_cross_margin(
&self,
currency: &str,
amount: f64,
) -> Result<MarginRepay>
pub async fn repay_cross_margin( &self, currency: &str, amount: f64, ) -> Result<MarginRepay>
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);Sourcepub async fn repay_isolated_margin(
&self,
symbol: &str,
currency: &str,
amount: Decimal,
) -> Result<MarginRepay>
pub async fn repay_isolated_margin( &self, symbol: &str, currency: &str, amount: Decimal, ) -> Result<MarginRepay>
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);Sourcepub async fn fetch_margin_adjustment_history(
&self,
symbol: Option<&str>,
since: Option<i64>,
limit: Option<i64>,
) -> Result<Vec<MarginAdjustment>>
pub async fn fetch_margin_adjustment_history( &self, symbol: Option<&str>, since: Option<i64>, limit: Option<i64>, ) -> Result<Vec<MarginAdjustment>>
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.
Sourcepub async fn fetch_cross_margin_max_borrowable(
&self,
currency: &str,
) -> Result<Decimal>
pub async fn fetch_cross_margin_max_borrowable( &self, currency: &str, ) -> Result<Decimal>
Sourcepub async fn fetch_isolated_margin_max_borrowable(
&self,
symbol: &str,
currency: &str,
) -> Result<Decimal>
pub async fn fetch_isolated_margin_max_borrowable( &self, symbol: &str, currency: &str, ) -> Result<Decimal>
Sourcepub async fn fetch_max_transferable(&self, currency: &str) -> Result<Decimal>
pub async fn fetch_max_transferable(&self, currency: &str) -> Result<Decimal>
Source§impl Binance
impl Binance
Sourcepub async fn fetch_status(&self) -> Result<SystemStatus>
pub async fn fetch_status(&self) -> Result<SystemStatus>
Fetch exchange system status.
§Returns
Returns formatted exchange status information with the following structure:
{
"status": "ok" | "maintenance",
"updated": null,
"eta": null,
"url": null,
"info": { ... }
}Sourcepub async fn fetch_markets(&self) -> Result<Arc<HashMap<String, Arc<Market>>>>
pub async fn fetch_markets(&self) -> Result<Arc<HashMap<String, Arc<Market>>>>
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());Sourcepub async fn load_markets(
&self,
reload: bool,
) -> Result<Arc<HashMap<String, Arc<Market>>>>
pub async fn load_markets( &self, reload: bool, ) -> Result<Arc<HashMap<String, Arc<Market>>>>
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?;Sourcepub async fn fetch_ticker(
&self,
symbol: &str,
params: impl IntoTickerParams,
) -> Result<Ticker>
pub async fn fetch_ticker( &self, symbol: &str, params: impl IntoTickerParams, ) -> Result<Ticker>
Sourcepub async fn fetch_order_book(
&self,
symbol: &str,
limit: Option<u32>,
) -> Result<OrderBook>
pub async fn fetch_order_book( &self, symbol: &str, limit: Option<u32>, ) -> Result<OrderBook>
Sourcepub async fn fetch_recent_trades(
&self,
symbol: &str,
limit: Option<u32>,
) -> Result<Vec<Trade>>
pub async fn fetch_recent_trades( &self, symbol: &str, limit: Option<u32>, ) -> Result<Vec<Trade>>
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.
Sourcepub async fn fetch_agg_trades(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<AggTrade>>
pub async fn fetch_agg_trades( &self, symbol: &str, since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<AggTrade>>
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.
Sourcepub async fn fetch_historical_trades(
&self,
symbol: &str,
_since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<Trade>>
pub async fn fetch_historical_trades( &self, symbol: &str, _since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Trade>>
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 usesfromIdinstead).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.
Sourcepub async fn fetch_24hr_stats(
&self,
symbol: Option<&str>,
) -> Result<Vec<Stats24hr>>
pub async fn fetch_24hr_stats( &self, symbol: Option<&str>, ) -> Result<Vec<Stats24hr>>
Fetch 24-hour trading statistics.
§Arguments
symbol- Optional trading pair symbol. IfNone, 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.
Sourcepub async fn fetch_trading_limits(&self, symbol: &str) -> Result<TradingLimits>
pub async fn fetch_trading_limits(&self, symbol: &str) -> Result<TradingLimits>
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.
Sourcepub async fn fetch_ohlcv_v2(&self, request: OhlcvRequest) -> Result<Vec<OHLCV>>
pub async fn fetch_ohlcv_v2(&self, request: OhlcvRequest) -> Result<Vec<OHLCV>>
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
request- OHLCV request built viaOhlcvRequest::builder()
§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
Sourcepub async fn fetch_ohlcv(
&self,
symbol: &str,
timeframe: &str,
since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, Value>>,
) -> Result<Vec<OHLCV>>
👎Deprecated since 0.2.0: Use fetch_ohlcv_v2 with OhlcvRequest::builder() instead
pub async fn fetch_ohlcv( &self, symbol: &str, timeframe: &str, since: Option<i64>, limit: Option<u32>, params: Option<HashMap<String, Value>>, ) -> Result<Vec<OHLCV>>
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 millisecondslimit- Maximum number of candlesticks to returnparams- Optional parametersprice- Price type: “mark” | “index” | “premiumIndex” (futures only)until- End timestamp in milliseconds
§Returns
Returns OHLCV data array: [timestamp, open, high, low, close, volume]
Sourcepub async fn fetch_time(&self) -> Result<ServerTime>
pub async fn fetch_time(&self) -> Result<ServerTime>
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);Sourcepub async fn fetch_bids_asks(&self, symbol: Option<&str>) -> Result<Vec<BidAsk>>
pub async fn fetch_bids_asks(&self, symbol: Option<&str>) -> Result<Vec<BidAsk>>
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());Sourcepub async fn fetch_last_prices(
&self,
symbol: Option<&str>,
) -> Result<Vec<LastPrice>>
pub async fn fetch_last_prices( &self, symbol: Option<&str>, ) -> Result<Vec<LastPrice>>
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());Sourcepub async fn fetch_mark_price(
&self,
symbol: Option<&str>,
) -> Result<Vec<MarkPrice>>
pub async fn fetch_mark_price( &self, symbol: Option<&str>, ) -> Result<Vec<MarkPrice>>
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
impl Binance
Sourcepub async fn create_order_v2(&self, request: OrderRequest) -> Result<Order>
pub async fn create_order_v2(&self, request: OrderRequest) -> Result<Order>
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
request- Order request built viaOrderRequest::builder()
§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
Sourcepub async fn create_order(
&self,
symbol: &str,
order_type: OrderType,
side: OrderSide,
amount: Amount,
price: Option<Price>,
params: Option<HashMap<String, String>>,
) -> Result<Order>
👎Deprecated since 0.2.0: Use create_order_v2 with OrderRequest::builder() instead
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>
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 asAmounttype.price- Optional price asPricetype (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.
Sourcepub async fn fetch_closed_orders(
&self,
symbol: Option<&str>,
since: Option<i64>,
limit: Option<u32>,
) -> Result<Vec<Order>>
pub async fn fetch_closed_orders( &self, symbol: Option<&str>, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<Order>>
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.
Sourcepub async fn fetch_orders(
&self,
symbol: Option<&str>,
since: Option<i64>,
limit: Option<u32>,
) -> Result<Vec<Order>>
pub async fn fetch_orders( &self, symbol: Option<&str>, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<Order>>
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.
Sourcepub 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>
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>
Create a stop-loss order.
§Arguments
symbol- Trading pair symbol.side- Order side (Buy/Sell).amount- Order quantity asAmounttype.stop_price- Stop-loss trigger price asPricetype.price- Optional limit price asPricetype (ifNone, 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.
Sourcepub 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>
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>
Create a take-profit order.
§Arguments
symbol- Trading pair symbol.side- Order side (Buy/Sell).amount- Order quantity asAmounttype.take_profit_price- Take-profit trigger price asPricetype.price- Optional limit price asPricetype (ifNone, 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.
Sourcepub 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>
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>
Create a trailing stop order.
§Arguments
symbol- Trading pair symbol.side- Order side (Buy/Sell).amount- Order quantity asAmounttype.trailing_percent- Trailing percentage asDecimal(e.g., 2.0 for 2%).activation_price- Optional activation price asPricetype (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.
§impl Binance
impl Binance
pub async fn subscribe_ticker(&self, symbol: &str) -> Result<()>
pub async fn subscribe_ticker(&self, symbol: &str) -> Result<()>
Subscribes to the ticker stream for a unified symbol
pub async fn subscribe_trades(&self, symbol: &str) -> Result<()>
pub async fn subscribe_trades(&self, symbol: &str) -> Result<()>
Subscribes to the trade stream for a unified symbol
pub async fn subscribe_orderbook(
&self,
symbol: &str,
levels: Option<u32>,
) -> Result<()>
pub async fn subscribe_orderbook( &self, symbol: &str, levels: Option<u32>, ) -> Result<()>
Subscribes to the order book stream for a unified symbol
pub async fn subscribe_kline(&self, symbol: &str, interval: &str) -> Result<()>
pub async fn subscribe_kline(&self, symbol: &str, interval: &str) -> Result<()>
Subscribes to the candlestick stream for a unified symbol
pub async fn watch_ticker(
&self,
symbol: &str,
params: Option<HashMap<String, Value>>,
) -> Result<Ticker>
pub async fn watch_ticker( &self, symbol: &str, params: Option<HashMap<String, Value>>, ) -> Result<Ticker>
Watches a ticker stream for a single unified symbol
pub async fn watch_tickers(
&self,
symbols: Option<Vec<String>>,
params: Option<HashMap<String, Value>>,
) -> Result<HashMap<String, Ticker>>
pub async fn watch_tickers( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, Value>>, ) -> Result<HashMap<String, Ticker>>
Watches ticker streams for multiple unified symbols
pub async fn watch_mark_price(
&self,
symbol: &str,
params: Option<HashMap<String, Value>>,
) -> Result<Ticker>
pub async fn watch_mark_price( &self, symbol: &str, params: Option<HashMap<String, Value>>, ) -> Result<Ticker>
Watches the mark price stream for a futures market
pub async fn watch_order_book(
&self,
symbol: &str,
limit: Option<i64>,
params: Option<HashMap<String, Value>>,
) -> Result<OrderBook>
pub async fn watch_order_book( &self, symbol: &str, limit: Option<i64>, params: Option<HashMap<String, Value>>, ) -> Result<OrderBook>
Watches an order book stream for a unified symbol
pub async fn watch_order_books(
&self,
symbols: Vec<String>,
limit: Option<i64>,
params: Option<HashMap<String, Value>>,
) -> Result<HashMap<String, OrderBook>>
pub async fn watch_order_books( &self, symbols: Vec<String>, limit: Option<i64>, params: Option<HashMap<String, Value>>, ) -> Result<HashMap<String, OrderBook>>
Watches order books for multiple symbols
pub async fn watch_mark_prices(
&self,
symbols: Option<Vec<String>>,
params: Option<HashMap<String, Value>>,
) -> Result<HashMap<String, Ticker>>
pub async fn watch_mark_prices( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, Value>>, ) -> Result<HashMap<String, Ticker>>
Watches mark prices for multiple futures symbols
pub async fn watch_trades(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<usize>,
) -> Result<Vec<Trade>>
pub async fn watch_trades( &self, symbol: &str, since: Option<i64>, limit: Option<usize>, ) -> Result<Vec<Trade>>
Streams trade data for a unified symbol
pub async fn watch_ohlcv(
&self,
symbol: &str,
timeframe: &str,
since: Option<i64>,
limit: Option<usize>,
) -> Result<Vec<OHLCV>>
pub async fn watch_ohlcv( &self, symbol: &str, timeframe: &str, since: Option<i64>, limit: Option<usize>, ) -> Result<Vec<OHLCV>>
Streams OHLCV data for a unified symbol
pub async fn watch_bids_asks(&self, symbol: &str) -> Result<BidAsk>
pub async fn watch_bids_asks(&self, symbol: &str) -> Result<BidAsk>
Streams the best bid/ask data for a unified symbol
pub async fn watch_balance(
self: Arc<Self>,
params: Option<HashMap<String, Value>>,
) -> Result<Balance>
pub async fn watch_balance( self: Arc<Self>, params: Option<HashMap<String, Value>>, ) -> Result<Balance>
Streams account balance changes (private user data stream)
pub async fn watch_orders(
self: Arc<Self>,
symbol: Option<&str>,
since: Option<i64>,
limit: Option<usize>,
_params: Option<HashMap<String, Value>>,
) -> Result<Vec<Order>>
pub async fn watch_orders( self: Arc<Self>, symbol: Option<&str>, since: Option<i64>, limit: Option<usize>, _params: Option<HashMap<String, Value>>, ) -> Result<Vec<Order>>
Watches authenticated order updates via the user data stream
Source§impl Binance
impl Binance
Sourcepub fn builder() -> BinanceBuilder
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();Sourcepub fn new(config: ExchangeConfig) -> Result<Self>
pub fn new(config: ExchangeConfig) -> Result<Self>
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();Sourcepub fn new_with_options(
config: ExchangeConfig,
options: BinanceOptions,
) -> Result<Self>
pub fn new_with_options( config: ExchangeConfig, options: BinanceOptions, ) -> Result<Self>
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();Sourcepub fn new_swap(config: ExchangeConfig) -> Result<Self>
pub fn new_swap(config: ExchangeConfig) -> Result<Self>
Sourcepub fn base(&self) -> &BaseExchange
pub fn base(&self) -> &BaseExchange
Returns a reference to the base exchange.
Sourcepub fn base_mut(&mut self) -> &mut BaseExchange
pub fn base_mut(&mut self) -> &mut BaseExchange
Returns a mutable reference to the base exchange.
Sourcepub fn options(&self) -> &BinanceOptions
pub fn options(&self) -> &BinanceOptions
Returns the Binance options.
Sourcepub fn set_options(&mut self, options: BinanceOptions)
pub fn set_options(&mut self, options: BinanceOptions)
Sets the Binance options.
Sourcepub fn ws_connection(&self) -> &Arc<RwLock<Option<BinanceWs>>>
pub fn ws_connection(&self) -> &Arc<RwLock<Option<BinanceWs>>>
Returns a reference to the persistent WebSocket connection.
This allows access to the stored WebSocket instance for state tracking.
The connection is stored when ws_connect() is called and cleared
when ws_disconnect() is called.
§Example
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;
let binance = Binance::new(ExchangeConfig::default())?;
let ws_conn = binance.ws_connection();
let guard = ws_conn.read().await;
if guard.is_some() {
println!("WebSocket is connected");
}Sourcepub fn time_sync(&self) -> &Arc<TimeSyncManager>
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());Sourcepub fn signed_request(
&self,
endpoint: impl Into<String>,
) -> SignedRequestBuilder<'_>
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?;Sourcepub fn rate_limit(&self) -> u32
pub fn rate_limit(&self) -> u32
Returns the rate limit in requests per second.
Sourcepub fn is_sandbox(&self) -> bool
pub fn is_sandbox(&self) -> bool
Returns true if sandbox/testnet mode is enabled.
Sandbox mode is enabled when either:
config.sandboxis set totrueoptions.testis set totrue
§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());Sourcepub fn timeframes(&self) -> HashMap<String, String>
pub fn timeframes(&self) -> HashMap<String, String>
Returns the supported timeframes.
Sourcepub fn urls(&self) -> BinanceUrls
pub fn urls(&self) -> BinanceUrls
Returns the API URLs.
Sourcepub fn get_ws_url(&self) -> String
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.
Sourcepub fn get_rest_url_public(&self) -> String
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"));Sourcepub fn get_rest_url_private(&self) -> String
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"));Sourcepub fn is_contract_type(&self) -> bool
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.
Sourcepub fn is_inverse(&self) -> bool
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.
Sourcepub fn is_linear(&self) -> bool
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.
Sourcepub fn create_ws(&self) -> BinanceWs
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?;Sourcepub fn create_authenticated_ws(self: &Arc<Self>) -> BinanceWs
pub fn create_authenticated_ws(self: &Arc<Self>) -> 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?;