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, Error>
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
Sourcepub async fn sync_time(&self) -> Result<(), Error>
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
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, Error>
pub async fn execute_signed_request_with_retry<T, F, Fut>( &self, request_fn: F, ) -> 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
- 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, Error>
pub async fn fetch_balance_simple(&self) -> Result<Balance, Error>
Sourcepub async fn fetch_balance(
&self,
account_type: Option<AccountType>,
) -> Result<Balance, Error>
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 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, Error>
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 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>, Error>
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.
Sourcepub async fn fetch_my_recent_trades(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<Trade>, Error>
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);
}Sourcepub async fn fetch_trading_fee(
&self,
symbol: &str,
params: Option<HashMap<String, String>>,
) -> Result<TradingFee, Error>
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. 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, TradingFee>, Error>
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.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, Error>
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);Sourcepub async fn refresh_listen_key(&self, listen_key: &str) -> Result<(), Error>
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§impl Binance
impl Binance
Sourcepub async fn set_position_mode_dapi(
&self,
dual_side: bool,
params: Option<Value>,
) -> Result<Value, Error>
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-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, Error>
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),
}Sourcepub async fn fetch_dapi_account(
&self,
params: Option<Value>,
) -> Result<Value, Error>
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 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, Error>
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 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, Error>
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 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, Error>
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 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, Error>
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 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, Error>
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);Sourcepub async fn withdraw(
&self,
code: &str,
amount: &str,
address: &str,
params: Option<BTreeMap<String, String>>,
) -> Result<Transaction, Error>
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 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>, Error>
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?;Sourcepub async fn fetch_withdrawals(
&self,
code: Option<&str>,
since: Option<i64>,
limit: Option<i64>,
params: Option<BTreeMap<String, String>>,
) -> Result<Vec<Transaction>, Error>
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?;Sourcepub async fn fetch_deposit_withdraw_fees(
&self,
currency: Option<&str>,
params: Option<BTreeMap<String, String>>,
) -> Result<Vec<DepositWithdrawFee>, Error>
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
impl Binance
Sourcepub async fn fetch_position(
&self,
symbol: &str,
params: Option<Value>,
) -> Result<Position, Error>
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);Sourcepub async fn fetch_positions(
&self,
symbols: Option<Vec<String>>,
params: Option<Value>,
) -> Result<Vec<Position>, Error>
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?;Sourcepub async fn fetch_positions_risk(
&self,
symbols: Option<Vec<String>>,
params: Option<Value>,
) -> Result<Vec<Position>, Error>
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.
Sourcepub async fn fetch_position_risk(
&self,
symbol: Option<&str>,
params: Option<Value>,
) -> Result<Value, Error>
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.Nonereturns 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.
Sourcepub async fn fetch_leverages(
&self,
symbols: Option<Vec<String>>,
params: Option<Value>,
) -> Result<BTreeMap<String, Leverage>, Error>
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.Nonequeries 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?;Sourcepub async fn fetch_leverage(
&self,
symbol: &str,
params: Option<Value>,
) -> Result<Leverage, Error>
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);Sourcepub async fn set_leverage(
&self,
symbol: &str,
leverage: i64,
params: Option<HashMap<String, String>>,
) -> Result<HashMap<String, Value>, Error>
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?;Sourcepub async fn fetch_leverage_bracket(
&self,
symbol: Option<&str>,
params: Option<Value>,
) -> Result<Value, Error>
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.Nonereturns 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.
Sourcepub async fn fetch_leverage_tiers(
&self,
symbols: Option<Vec<String>>,
params: Option<HashMap<String, String>>,
) -> Result<BTreeMap<String, Vec<LeverageTier>>, Error>
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.Nonefetches 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?;Sourcepub async fn set_margin_mode(
&self,
symbol: &str,
margin_mode: &str,
params: Option<HashMap<String, String>>,
) -> Result<HashMap<String, Value>, Error>
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 (isolatedorcross).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
isolatedorcross) - 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?;Sourcepub async fn set_position_mode(
&self,
dual_side: bool,
params: Option<Value>,
) -> Result<Value, Error>
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-truefor hedge mode (dual-side position),falsefor 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?;Sourcepub async fn fetch_position_mode(
&self,
params: Option<Value>,
) -> Result<bool, Error>
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?;Sourcepub async fn modify_isolated_position_margin(
&self,
symbol: &str,
amount: Decimal,
params: Option<Value>,
) -> Result<Value, Error>
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,amountsign 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.
Sourcepub async fn fetch_funding_rate(
&self,
symbol: &str,
params: Option<HashMap<String, String>>,
) -> Result<FundingRate, Error>
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);Sourcepub async fn fetch_funding_rates(
&self,
symbols: Option<Vec<String>>,
params: Option<BTreeMap<String, String>>,
) -> Result<BTreeMap<String, FundingRate>, Error>
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.Nonefetches 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());Sourcepub async fn fetch_funding_rate_history(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<FundingRateHistory>, Error>
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());Sourcepub async fn fetch_funding_history(
&self,
symbol: Option<&str>,
since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Value, Error>
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.Nonereturns 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
impl Binance
Sourcepub async fn borrow_cross_margin(
&self,
currency: &str,
amount: f64,
) -> Result<MarginLoan, Error>
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);Sourcepub async fn borrow_isolated_margin(
&self,
symbol: &str,
currency: &str,
amount: f64,
) -> Result<MarginLoan, Error>
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);Sourcepub async fn repay_cross_margin(
&self,
currency: &str,
amount: f64,
) -> Result<MarginRepay, Error>
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);Sourcepub async fn repay_isolated_margin(
&self,
symbol: &str,
currency: &str,
amount: Decimal,
) -> Result<MarginRepay, Error>
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);Sourcepub async fn fetch_margin_adjustment_history(
&self,
symbol: Option<&str>,
since: Option<i64>,
limit: Option<i64>,
) -> Result<Vec<MarginAdjustment>, Error>
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.
Sourcepub async fn fetch_cross_margin_max_borrowable(
&self,
currency: &str,
) -> Result<Decimal, Error>
pub async fn fetch_cross_margin_max_borrowable( &self, currency: &str, ) -> Result<Decimal, Error>
Sourcepub async fn fetch_isolated_margin_max_borrowable(
&self,
symbol: &str,
currency: &str,
) -> Result<Decimal, Error>
pub async fn fetch_isolated_margin_max_borrowable( &self, symbol: &str, currency: &str, ) -> Result<Decimal, Error>
Source§impl Binance
impl Binance
Sourcepub async fn fetch_status(&self) -> Result<SystemStatus, Error>
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": { ... }
}Sourcepub async fn fetch_markets(
&self,
) -> Result<Arc<HashMap<String, Arc<Market>>>, Error>
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());Sourcepub async fn load_markets(
&self,
reload: bool,
) -> Result<Arc<HashMap<String, Arc<Market>>>, Error>
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?;Sourcepub async fn fetch_ticker(
&self,
symbol: &str,
params: impl IntoTickerParams,
) -> Result<Ticker, Error>
pub async fn fetch_ticker( &self, symbol: &str, params: impl IntoTickerParams, ) -> Result<Ticker, Error>
Sourcepub async fn fetch_tickers(
&self,
symbols: Option<Vec<String>>,
) -> Result<Vec<Ticker>, Error>
pub async fn fetch_tickers( &self, symbols: Option<Vec<String>>, ) -> Result<Vec<Ticker>, Error>
Sourcepub async fn fetch_order_book(
&self,
symbol: &str,
limit: Option<u32>,
) -> Result<OrderBook, Error>
pub async fn fetch_order_book( &self, symbol: &str, limit: Option<u32>, ) -> Result<OrderBook, Error>
Sourcepub async fn fetch_trades(
&self,
symbol: &str,
limit: Option<u32>,
) -> Result<Vec<Trade>, Error>
pub async fn fetch_trades( &self, symbol: &str, limit: Option<u32>, ) -> Result<Vec<Trade>, Error>
Sourcepub async fn fetch_recent_trades(
&self,
symbol: &str,
limit: Option<u32>,
) -> Result<Vec<Trade>, Error>
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.
Sourcepub async fn fetch_agg_trades(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<AggTrade>, Error>
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.
Sourcepub async fn fetch_historical_trades(
&self,
symbol: &str,
_since: Option<i64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<Trade>, Error>
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 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>, Error>
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. 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, Error>
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.
Sourcepub async fn fetch_ohlcv_v2(
&self,
request: OhlcvRequest,
) -> Result<Vec<OHLCV>, Error>
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
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>, Error>
👎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>, Error>
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, Error>
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);Sourcepub async fn fetch_bids_asks(
&self,
symbol: Option<&str>,
) -> Result<Vec<BidAsk>, Error>
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());Sourcepub async fn fetch_last_prices(
&self,
symbol: Option<&str>,
) -> Result<Vec<LastPrice>, Error>
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());Sourcepub async fn fetch_mark_price(
&self,
symbol: Option<&str>,
) -> Result<Vec<MarkPrice>, Error>
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
impl Binance
Sourcepub async fn create_order_v2(
&self,
request: OrderRequest,
) -> Result<Order, Error>
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
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, Error>
👎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, Error>
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>, Error>
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.
Sourcepub async fn cancel_orders(
&self,
ids: Vec<String>,
symbol: &str,
) -> Result<Vec<Order>, Error>
pub async fn cancel_orders( &self, ids: Vec<String>, symbol: &str, ) -> Result<Vec<Order>, Error>
Sourcepub async fn fetch_orders(
&self,
symbol: Option<&str>,
since: Option<i64>,
limit: Option<u32>,
) -> Result<Vec<Order>, Error>
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.
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, Error>
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 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, Error>
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 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, Error>
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 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.
Source§impl Binance
impl Binance
Sourcepub async fn subscribe_orderbook(
&self,
symbol: &str,
levels: Option<u32>,
) -> Result<(), Error>
pub async fn subscribe_orderbook( &self, symbol: &str, levels: Option<u32>, ) -> Result<(), Error>
Sourcepub async fn watch_ticker(
&self,
symbol: &str,
params: Option<HashMap<String, Value>>,
) -> Result<Ticker, Error>
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 parametersname: 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));Sourcepub async fn watch_tickers(
&self,
symbols: Option<Vec<String>>,
params: Option<HashMap<String, Value>>,
) -> Result<HashMap<String, Ticker>, Error>
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 parametersname: 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?;Sourcepub async fn watch_mark_price(
&self,
symbol: &str,
params: Option<HashMap<String, Value>>,
) -> Result<Ticker, Error>
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 parametersuse1sFreq: 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?;Sourcepub async fn watch_order_book(
&self,
symbol: &str,
limit: Option<i64>,
params: Option<HashMap<String, Value>>,
) -> Result<OrderBook, Error>
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 parametersspeed: 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?;Sourcepub async fn watch_order_books(
&self,
symbols: Vec<String>,
limit: Option<i64>,
params: Option<HashMap<String, Value>>,
) -> Result<HashMap<String, OrderBook>, Error>
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 limitparams- Optional parametersspeed: 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());
}Sourcepub async fn watch_mark_prices(
&self,
symbols: Option<Vec<String>>,
params: Option<HashMap<String, Value>>,
) -> Result<HashMap<String, Ticker>, Error>
pub async fn watch_mark_prices( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, Value>>, ) -> Result<HashMap<String, Ticker>, Error>
Sourcepub async fn watch_trades(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<usize>,
) -> Result<Vec<Trade>, Error>
pub async fn watch_trades( &self, symbol: &str, since: Option<i64>, limit: Option<usize>, ) -> Result<Vec<Trade>, Error>
Sourcepub async fn watch_ohlcv(
&self,
symbol: &str,
timeframe: &str,
since: Option<i64>,
limit: Option<usize>,
) -> Result<Vec<OHLCV>, Error>
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 millisecondslimit- Optional maximum number of entries to return
§Returns
Vector of OHLCV entries
Sourcepub async fn watch_balance(
self: Arc<Binance>,
params: Option<HashMap<String, Value>>,
) -> Result<Balance, Error>
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 parameterstype: 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?;Sourcepub 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>
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 millisecondslimit- Optional maximum number of orders to returnparams- 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(())
}Sourcepub 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>
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 millisecondslimit- Maximum number of trades to returnparams- 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(())
}Sourcepub 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>
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 timestamplimit- Optional maximum number of positions to returnparams- Optional parameterstype: Market type (future/delivery, defaultfuture)subType: Subtype (linear/inverse)
§Returns
Collection of positions
§Implementation Details
- Subscribe to ACCOUNT_UPDATE events through the user data stream.
- Parse the position data contained in the
Parray. - Update the internal position cache.
- 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
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<Binance, Error>
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();Sourcepub fn new_with_options(
config: ExchangeConfig,
options: BinanceOptions,
) -> Result<Binance, Error>
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();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 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<Binance>) -> BinanceWs
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?;