pub struct Binance { /* private fields */ }Expand description
Binance exchange structure.
Implementations§
Source§impl Binance
impl Binance
Sourcepub async fn fetch_status(&self) -> Result<Value, Error>
pub async fn fetch_status(&self) -> Result<Value, 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<Vec<Market>, Error>
pub async fn fetch_markets(&self) -> Result<Vec<Market>, Error>
Fetch all trading markets.
§Returns
Returns a vector 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<HashMap<String, Market>, Error>
pub async fn load_markets( &self, reload: bool, ) -> Result<HashMap<String, 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.
§Example
let recent_trades = binance.fetch_recent_trades("BTC/USDT", Some(100)).await?;Sourcepub async fn fetch_my_recent_trades(
&self,
symbol: &str,
since: Option<u64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<Trade>, Error>
pub async fn fetch_my_recent_trades( &self, symbol: &str, since: Option<u64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Trade>, Error>
Fetch authenticated user’s recent trades (private API).
§Arguments
symbol- Trading pair symbol.since- Optional start timestamp in milliseconds.limit- Optional limit on number of trades (default: 500, maximum: 1000).params- Additional parameters.
§Returns
Returns a vector of Trade structures for the user’s trades.
§Errors
Returns an error if authentication fails or the API request fails.
§Example
let my_trades = binance.fetch_my_recent_trades("BTC/USDT", None, Some(50), None).await?;Sourcepub async fn fetch_agg_trades(
&self,
symbol: &str,
since: Option<u64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<AggTrade>, Error>
pub async fn fetch_agg_trades( &self, symbol: &str, since: Option<u64>, 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.
§Example
let agg_trades = binance.fetch_agg_trades("BTC/USDT", None, Some(100), None).await?;Sourcepub async fn fetch_historical_trades(
&self,
symbol: &str,
_since: Option<u64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<Trade>, Error>
pub async fn fetch_historical_trades( &self, symbol: &str, _since: Option<u64>, 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.
§Example
let historical_trades = binance.fetch_historical_trades("BTC/USDT", None, Some(100), None).await?;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.
§Example
// Fetch statistics for a single pair
let stats = binance.fetch_24hr_stats(Some("BTC/USDT")).await?;
// Fetch statistics for all pairs
let all_stats = binance.fetch_24hr_stats(None).await?;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.
§Example
let limits = binance.fetch_trading_limits("BTC/USDT").await?;
println!("Min amount: {:?}", limits.amount.min);
println!("Max amount: {:?}", limits.amount.max);Sourcepub async fn create_order(
&self,
symbol: &str,
order_type: OrderType,
side: OrderSide,
amount: f64,
price: Option<f64>,
params: Option<HashMap<String, String>>,
) -> Result<Order, Error>
pub async fn create_order( &self, symbol: &str, order_type: OrderType, side: OrderSide, amount: f64, price: Option<f64>, params: Option<HashMap<String, String>>, ) -> Result<Order, Error>
Create a new order.
§Arguments
symbol- Trading pair symbol.order_type- Order type (Market, Limit, StopLoss, etc.).side- Order side (Buy or Sell).amount- Order quantity.price- Optional price (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 create_stop_loss_order(
&self,
symbol: &str,
side: OrderSide,
amount: f64,
stop_price: f64,
price: Option<f64>,
params: Option<HashMap<String, String>>,
) -> Result<Order, Error>
pub async fn create_stop_loss_order( &self, symbol: &str, side: OrderSide, amount: f64, stop_price: f64, price: Option<f64>, 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.stop_price- Stop-loss trigger price.price- Optional limit price (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.
§Example
// Create market stop-loss order
let order = exchange.create_stop_loss_order(
"BTC/USDT",
OrderSide::Sell,
0.1,
45000.0,
None,
None
).await?;
// Create limit stop-loss order
let order = exchange.create_stop_loss_order(
"BTC/USDT",
OrderSide::Sell,
0.1,
45000.0,
Some(44900.0),
None
).await?;Sourcepub async fn create_take_profit_order(
&self,
symbol: &str,
side: OrderSide,
amount: f64,
take_profit_price: f64,
price: Option<f64>,
params: Option<HashMap<String, String>>,
) -> Result<Order, Error>
pub async fn create_take_profit_order( &self, symbol: &str, side: OrderSide, amount: f64, take_profit_price: f64, price: Option<f64>, 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.take_profit_price- Take-profit trigger price.price- Optional limit price (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.
§Example
// Create market take-profit order
let order = exchange.create_take_profit_order(
"BTC/USDT",
OrderSide::Sell,
0.1,
55000.0,
None,
None
).await?;
// Create limit take-profit order
let order = exchange.create_take_profit_order(
"BTC/USDT",
OrderSide::Sell,
0.1,
55000.0,
Some(55100.0),
None
).await?;Sourcepub async fn create_trailing_stop_order(
&self,
symbol: &str,
side: OrderSide,
amount: f64,
trailing_percent: f64,
activation_price: Option<f64>,
params: Option<HashMap<String, String>>,
) -> Result<Order, Error>
pub async fn create_trailing_stop_order( &self, symbol: &str, side: OrderSide, amount: f64, trailing_percent: f64, activation_price: Option<f64>, 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.trailing_percent- Trailing percentage (e.g., 2.0 for 2%).activation_price- Optional activation price (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.
§Example
// Spot market: create trailing stop order with 2% trail
let order = exchange.create_trailing_stop_order(
"BTC/USDT",
OrderSide::Sell,
0.1,
2.0,
None,
None
).await?;
// Futures market: create trailing stop order with 1.5% trail, activation price 50000
let order = exchange.create_trailing_stop_order(
"BTC/USDT:USDT",
OrderSide::Sell,
0.1,
1.5,
Some(50000.0),
None
).await?;Sourcepub async fn fetch_balance_simple(&self) -> Result<Balance, Error>
pub async fn fetch_balance_simple(&self) -> Result<Balance, Error>
Sourcepub async fn fetch_my_trades(
&self,
symbol: &str,
since: Option<u64>,
limit: Option<u32>,
) -> Result<Vec<Trade>, Error>
pub async fn fetch_my_trades( &self, symbol: &str, since: Option<u64>, 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_currencies(&self) -> Result<Vec<Currency>, Error>
pub async fn fetch_currencies(&self) -> Result<Vec<Currency>, Error>
Fetch all currency information.
§Returns
Returns a vector of Currency structures.
§Errors
Returns an error if authentication fails or the API request fails.
§Example
let currencies = binance.fetch_currencies().await?;
for currency in ¤cies {
println!("{}: {} - {}", currency.code, currency.name, currency.active);
}Sourcepub async fn fetch_closed_orders(
&self,
symbol: Option<&str>,
since: Option<u64>,
limit: Option<u32>,
) -> Result<Vec<Order>, Error>
pub async fn fetch_closed_orders( &self, symbol: Option<&str>, since: Option<u64>, 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.
§Note
This method calls fetch_orders to get all orders, then filters for “closed” status.
This matches the Go version’s implementation logic.
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<u64>,
limit: Option<u32>,
) -> Result<Vec<Order>, Error>
pub async fn fetch_orders( &self, symbol: Option<&str>, since: Option<u64>, 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 all Order structures.
§Errors
Returns an error if authentication fails or the API request fails.
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 funding rate for a single trading pair.
§Arguments
symbol- Trading pair symbol (e.g., “BTC/USDT:USDT”).params- Optional parameters.
§Returns
Returns the [FundingRate] information.
§Errors
Returns an error if the API request fails.
§Example
let binance = Binance::new_futures(ExchangeConfig::default())?;
let funding_rate = binance.fetch_funding_rate("BTC/USDT:USDT", None).await?;Fetch funding rates for multiple trading pairs.
§Arguments
symbols- Optional vector of trading pair symbols, fetches all ifNone.params- Optional parameters.
§Returns
Returns a vector of [FundingRate] structures.
§Errors
Returns an error if the API request fails.
§Example
let binance = Binance::new_futures(ExchangeConfig::default())?;
let funding_rates = binance.fetch_funding_rates(None, None).await?;Fetch funding rate history.
§Arguments
symbol- Optional trading pair symbol.since- Optional start timestamp (milliseconds).limit- Optional limit on number of records (default 100, max 1000).params- Optional parameters.
§Returns
Returns a vector of historical [FundingRate] structures.
§Errors
Returns an error if the API request fails.
§Example
let binance = Binance::new_futures(ExchangeConfig::default())?;
let history = binance.fetch_funding_rate_history(
Some("BTC/USDT:USDT"),
None,
Some(100),
None
).await?;Fetch position for a single trading pair.
§Arguments
symbol- Trading pair symbol (e.g., “BTC/USDT:USDT”).params- Optional parameters.
§Returns
Returns the [Position] information.
§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_futures(config)?;
let position = binance.fetch_position("BTC/USDT:USDT", None).await?;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_futures(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_leverages(
&self,
symbols: Option<Vec<String>>,
params: Option<Value>,
) -> Result<HashMap<String, Leverage>, Error>
pub async fn fetch_leverages( &self, symbols: Option<Vec<String>>, params: Option<Value>, ) -> Result<HashMap<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
let exchange = Binance::new(Default::default());
// 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
let exchange = Binance::new(Default::default());
// 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_futures(config)?;
let result = binance.set_leverage("BTC/USDT:USDT", 10, 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_futures(config)?;
let result = binance.set_margin_mode("BTC/USDT:USDT", "isolated", None).await?;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 fee for a single trading pair.
§Arguments
symbol- Trading pair symbol (e.g., “BTC/USDT”).params- Optional parameters.
§Returns
Returns trading fee information.
§Errors
Returns an error if:
- Authentication credentials are missing
- The market type is not supported
- 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 trading pairs.
§Arguments
symbols- Optional list of trading pairs.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?;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 single trading pair.
§Arguments
symbol- Trading pair symbol (e.g., “BTC/USDT:USDT”).params- Optional parameters.
§Returns
Returns 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_futures(ExchangeConfig::default())?;
let rate = binance.fetch_funding_rate("BTC/USDT:USDT", None).await?;
println!("Funding rate: {:?}", rate.funding_rate);Sourcepub async fn fetch_funding_rate_history(
&self,
symbol: &str,
since: Option<u64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<FundingRateHistory>, Error>
pub async fn fetch_funding_rate_history( &self, symbol: &str, since: Option<u64>, 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_futures(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_rates(
&self,
symbols: Option<Vec<String>>,
params: Option<HashMap<String, String>>,
) -> Result<HashMap<String, FundingRate>, Error>
pub async fn fetch_funding_rates( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, String>>, ) -> Result<HashMap<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_futures(ExchangeConfig::default())?;
let rates = binance.fetch_funding_rates(None, None).await?;
println!("Found {} funding rates", rates.len());Sourcepub async fn fetch_leverage_tiers(
&self,
symbols: Option<Vec<String>>,
params: Option<HashMap<String, String>>,
) -> Result<HashMap<String, Vec<LeverageTier>>, Error>
pub async fn fetch_leverage_tiers( &self, symbols: Option<Vec<String>>, params: Option<HashMap<String, String>>, ) -> Result<HashMap<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_futures(config)?;
let tiers = binance.fetch_leverage_tiers(None, None).await?;Sourcepub async fn fetch_funding_history(
&self,
symbol: Option<&str>,
since: Option<u64>,
limit: Option<u32>,
params: Option<Value>,
) -> Result<Vec<FundingHistory>, Error>
pub async fn fetch_funding_history( &self, symbol: Option<&str>, since: Option<u64>, limit: Option<u32>, params: Option<Value>, ) -> Result<Vec<FundingHistory>, Error>
Fetch funding fee history.
§Arguments
symbol- Optional trading pair symbol.since- Optional start timestamp in milliseconds.limit- Optional record limit (default 100, max 1000).params- Optional parameters.
§Returns
Returns a vector of funding fee history records.
§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_futures(config)?;
let history = binance.fetch_funding_history(
Some("BTC/USDT:USDT"),
None,
Some(100),
None
).await?;Sourcepub async fn fetch_my_funding_history(
&self,
symbol: Option<&str>,
start_time: Option<u64>,
end_time: Option<u64>,
limit: Option<u32>,
) -> Result<Vec<FundingFee>, Error>
pub async fn fetch_my_funding_history( &self, symbol: Option<&str>, start_time: Option<u64>, end_time: Option<u64>, limit: Option<u32>, ) -> Result<Vec<FundingFee>, Error>
Fetch my funding fee history
§Arguments
symbol- Optional trading pair symbol.start_time- Optional start timestamp.end_time- Optional end timestamp.limit- Optional record limit (default 100, max 1000).
§Returns
Returns a vector of funding fee history records.
§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_futures(config)?;
let fees = binance.fetch_my_funding_history(Some("BTC/USDT:USDT"), None, None, Some(50)).await?;Sourcepub async fn fetch_next_funding_rate(
&self,
symbol: &str,
) -> Result<NextFundingRate, Error>
pub async fn fetch_next_funding_rate( &self, symbol: &str, ) -> Result<NextFundingRate, Error>
Fetch next funding rate (prediction) for a trading pair.
§Arguments
symbol- Trading pair symbol.
§Returns
Returns next funding rate information.
§Errors
Returns an error if the API request fails.
§Example
let binance = Binance::new_futures(ExchangeConfig::default())?;
let next_rate = binance.fetch_next_funding_rate("BTC/USDT:USDT").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 (one-way or hedge mode).
§Arguments
dual_side- Enable hedge mode (dual-side position).true: Hedge mode (can hold both long and short positions simultaneously).false: One-way mode (can only hold one direction).
params- Optional parameters.
§Returns
Returns the operation result.
§Errors
Returns an error if:
- Authentication fails
- Positions are currently open (cannot switch modes with open positions)
- The API request fails
§Notes
- This setting applies globally to the account, not per trading pair.
- In hedge mode, orders must specify
positionSide(LONG/SHORT). - In one-way mode,
positionSideis fixed to BOTH. - Cannot switch modes while holding positions.
§Example
let binance = Binance::new_futures(ExchangeConfig::default())?;
// Enable hedge mode
let result = binance.set_position_mode(true, None).await?;
// Switch back to one-way mode
let result = binance.set_position_mode(false, None).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.
§Arguments
params- Optional parameters.
§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_futures(ExchangeConfig::default())?;
let dual_side = binance.fetch_position_mode(None).await?;
println!("Hedge mode enabled: {}", dual_side);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.
let binance = Binance::new_futures(ExchangeConfig::default())?;
// Add 100 USDT to isolated margin
binance.modify_isolated_position_margin("BTC/USDT", dec!(100.0), None).await?;
// Reduce 50 USDT from isolated margin
binance.modify_isolated_position_margin("BTC/USDT", dec!(-50.0), None).await?;
// Adjust long position margin in hedge mode
let params = serde_json::json!({"positionSide": "LONG"});
binance.modify_isolated_position_margin("BTC/USDT", dec!(100.0), Some(params)).await?;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.
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 array.
§Errors
Returns an error if authentication fails or the API request fails.
§Examples
let binance = Binance::new_futures(ExchangeConfig::default())?;
// Fetch all position risks
let risks = binance.fetch_position_risk(None, None).await?;
// Fetch position risk for specific symbol
let risk = binance.fetch_position_risk(Some("BTC/USDT"), 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.
§Examples
let binance = Binance::new_futures(ExchangeConfig::default())?;
// Fetch all leverage brackets
let brackets = binance.fetch_leverage_bracket(None, None).await?;
// Fetch bracket for specific symbol
let bracket = binance.fetch_leverage_bracket(Some("BTC/USDT"), None).await?;§Response Example
[
{
"symbol": "BTCUSDT",
"brackets": [
{
"bracket": 1,
"initialLeverage": 125,
"notionalCap": 50000,
"notionalFloor": 0,
"maintMarginRatio": 0.004,
"cum": 0
},
{
"bracket": 2,
"initialLeverage": 100,
"notionalCap": 250000,
"notionalFloor": 50000,
"maintMarginRatio": 0.005,
"cum": 50
}
]
}
]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>
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>
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>
Sourcepub async fn repay_isolated_margin(
&self,
symbol: &str,
currency: &str,
amount: f64,
) -> Result<MarginRepay, Error>
pub async fn repay_isolated_margin( &self, symbol: &str, currency: &str, amount: f64, ) -> Result<MarginRepay, Error>
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- Start timestamp in millisecondslimit- Maximum number of records to return
§Returns
Returns a list of margin adjustments.
§Errors
Returns an error if authentication fails or the API request fails.
Sourcepub async fn fetch_balance(
&self,
params: Option<HashMap<String, Value>>,
) -> Result<Balance, Error>
pub async fn fetch_balance( &self, params: Option<HashMap<String, Value>>, ) -> Result<Balance, Error>
Fetch account balance.
Retrieves balance information for various account types including spot, margin, futures, savings, and funding accounts.
§Arguments
params- Optional parameterstype: Account type (“spot”, “margin”, “isolated”, “linear”, “inverse”, “savings”, “funding”, “papi”)marginMode: Margin mode (“cross”, “isolated”)symbols: List of isolated margin trading pairs (used with “isolated” type)
§Returns
Returns account balance information.
§Errors
Returns an error if authentication fails or the API request fails.
Sourcepub async fn fetch_cross_margin_max_borrowable(
&self,
code: &str,
params: Option<HashMap<String, Value>>,
) -> Result<MaxBorrowable, Error>
pub async fn fetch_cross_margin_max_borrowable( &self, code: &str, params: Option<HashMap<String, Value>>, ) -> Result<MaxBorrowable, Error>
Fetch maximum borrowable amount for cross margin.
Queries the maximum amount that can be borrowed for a specific currency in cross margin mode.
§Arguments
code- Currency code (e.g., “USDT”)params- Optional parameters (reserved for future use)
§Returns
Returns maximum borrowable amount information.
§Errors
Returns an error if authentication fails or the API request fails.
Sourcepub async fn fetch_isolated_margin_max_borrowable(
&self,
code: &str,
symbol: &str,
params: Option<HashMap<String, Value>>,
) -> Result<MaxBorrowable, Error>
pub async fn fetch_isolated_margin_max_borrowable( &self, code: &str, symbol: &str, params: Option<HashMap<String, Value>>, ) -> Result<MaxBorrowable, Error>
Fetch maximum borrowable amount for isolated margin.
Queries the maximum amount that can be borrowed for a specific currency in a specific isolated margin trading pair.
§Arguments
code- Currency code (e.g., “USDT”)symbol- Trading pair symbol (e.g., “BTC/USDT”)params- Optional parameters (reserved for future use)
§Returns
Returns maximum borrowable amount information.
§Errors
Returns an error if authentication fails or the API request fails.
Sourcepub async fn fetch_max_transferable(
&self,
code: &str,
params: Option<HashMap<String, Value>>,
) -> Result<MaxTransferable, Error>
pub async fn fetch_max_transferable( &self, code: &str, params: Option<HashMap<String, Value>>, ) -> Result<MaxTransferable, Error>
Fetch maximum transferable amount.
Queries the maximum amount that can be transferred out of margin account.
§Arguments
code- Currency code (e.g., “USDT”)params- Optional parameterssymbol: Isolated margin trading pair symbol (e.g., “BTC/USDT”)
§Returns
Returns maximum transferable amount information.
§Errors
Returns an error if authentication fails or the API request fails.
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 bid/ask prices (Book Ticker)
§Arguments
symbol- Optional trading pair symbol; if omitted, returns all symbols
§Returns
Returns bid/ask price information
§API Endpoint
- GET
/api/v3/ticker/bookTicker - Weight: 1 for single symbol, 2 for all symbols
- Requires signature: No
§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, bid_ask[0].ask);
// 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 latest price information.
§Errors
Returns an error if the API request fails.
§Examples
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 mark price information including funding rates.
§Errors
Returns an error if the API request fails.
§Note
This API only applies to futures markets.
§Examples
let binance = Binance::new(ExchangeConfig::default())?;
// Fetch mark price for single futures symbol
let mark_price = binance.fetch_mark_price(Some("BTC/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());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>
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
§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 millisecondspaginate- Whether to automatically paginate (default: false)
§Returns
Returns OHLCV data array: [timestamp, open, high, low, close, volume]
§Examples
let binance = Binance::new(Default::default());
// Basic usage
let ohlcv = binance.fetch_ohlcv("BTC/USDT", "1h", None, Some(100), None).await?;
// Using time range
let since = 1609459200000; // 2021-01-01
let until = 1612137600000; // 2021-02-01
let mut params = HashMap::new();
params.insert("until".to_string(), json!(until));
let ohlcv = binance.fetch_ohlcv("BTC/USDT", "1h", Some(since), None, Some(params)).await?;
// Futures mark price candlesticks
let mut params = HashMap::new();
params.insert("price".to_string(), json!("mark"));
let mark_ohlcv = binance.fetch_ohlcv("BTC/USDT:USDT", "1h", None, Some(100), Some(params)).await?;Sourcepub async fn fetch_time(&self) -> Result<ServerTime, Error>
pub async fn fetch_time(&self) -> Result<ServerTime, Error>
Fetch trading fee for a single trading pair
§Arguments
symbol- Trading pair symbol (e.g., BTC/USDT)
§Binance API
- Endpoint: GET /sapi/v1/asset/tradeFee
- Weight: 1
- Requires signature: Yes
§Examples
let config = ExchangeConfig {
api_key: Some("your-api-key".to_string()),
secret: Some("your-secret".to_string()),
..Default::default()
};
let binance = Binance::new(config)?;
// Fetch trading fee for BTC/USDT
let fee = binance.fetch_trading_fee("BTC/USDT").await?;
println!("Maker fee: {}%, Taker fee: {}%",
fee.maker * 100.0, fee.taker * 100.0);Fetch trading fees for multiple trading pairs
§Arguments
symbols- Trading pair symbols (e.g., vec![“BTC/USDT”, “ETH/USDT”]), or None for all pairs
§Binance API
- Endpoint: GET /sapi/v1/asset/tradeFee
- Weight: 1
- Signature required: Yes
§Examples
let config = ExchangeConfig {
api_key: Some("your-api-key".to_string()),
secret: Some("your-secret".to_string()),
..Default::default()
};
let binance = Binance::new(config)?;
// Fetch fees for all trading pairs
let all_fees = binance.fetch_trading_fees(None).await?;
println!("Total symbols with fees: {}", all_fees.len());
// Fetch fees for specific trading pairs
let fees = binance.fetch_trading_fees(Some(vec!["BTC/USDT", "ETH/USDT"])).await?;
for fee in &fees {
println!("{}: Maker {}%, Taker {}%",
fee.symbol, fee.maker * 100.0, fee.taker * 100.0);
}Fetch server time
§Binance API
- Endpoint: GET /api/v3/time
- Weight: 1
- Data source: Memory
§Examples
let config = ExchangeConfig::default();
let binance = Binance::new(config)?;
// Fetch Binance server time
let server_time = binance.fetch_time().await?;
println!("Server time: {} ({})", server_time.server_time, server_time.datetime);
// Check local time offset
let local_time = chrono::Utc::now().timestamp_millis();
let offset = server_time.server_time - local_time;
println!("Time offset: {} ms", offset);Sourcepub async fn fetch_canceled_and_closed_orders(
&self,
symbol: &str,
since: Option<u64>,
limit: Option<u64>,
) -> Result<Vec<Order>, Error>
pub async fn fetch_canceled_and_closed_orders( &self, symbol: &str, since: Option<u64>, limit: Option<u64>, ) -> Result<Vec<Order>, Error>
Fetch canceled orders
§Arguments
symbol- Trading pair symbol (e.g., “BTC/USDT”)since- Optional start timestamp in millisecondslimit- Optional record limit (default 500, max 1000)
§Returns
Returns vector of canceled orders
§Example
let binance = Binance::new(ExchangeConfig::default())?;
let orders = binance.fetch_canceled_orders("BTC/USDT", None, Some(10)).await?;
println!("Found {} canceled orders", orders.len());Fetch canceled and closed orders
§Arguments
symbol- Trading pair symbol (e.g., “BTC/USDT”)since- Optional start timestamp in millisecondslimit- Optional record limit (default 500, max 1000)
§Returns
Returns vector of canceled and closed orders
§Example
let binance = Binance::new(ExchangeConfig::default())?;
let orders = binance.fetch_canceled_and_closed_orders("BTC/USDT", None, Some(20)).await?;
println!("Found {} closed/canceled orders", orders.len());Sourcepub async fn fetch_open_order(
&self,
id: &str,
symbol: &str,
) -> Result<Order, Error>
pub async fn fetch_open_order( &self, id: &str, symbol: &str, ) -> Result<Order, Error>
Fetch a single open order
§Arguments
id- Order IDsymbol- Trading pair symbol (e.g., “BTC/USDT”)
§Returns
Returns order information
§Example
let binance = Binance::new(ExchangeConfig::default())?;
let order = binance.fetch_open_order("12345", "BTC/USDT").await?;
println!("Order status: {:?}", order.status);Sourcepub async fn edit_order(
&self,
id: &str,
symbol: &str,
order_type: OrderType,
side: OrderSide,
amount: Decimal,
price: Option<Decimal>,
params: Option<HashMap<String, String>>,
) -> Result<Order, Error>
pub async fn edit_order( &self, id: &str, symbol: &str, order_type: OrderType, side: OrderSide, amount: Decimal, price: Option<Decimal>, params: Option<HashMap<String, String>>, ) -> Result<Order, Error>
Fetch trades for a specific order
§Arguments
id- Order IDsymbol- Trading pair symbol (e.g., “BTC/USDT”)since- Optional start timestamp in millisecondslimit- Optional record limit (default 500, max 1000)
§Returns
Returns vector of trade records
§Example
let binance = Binance::new(ExchangeConfig::default())?;
let trades = binance.fetch_order_trades("12345", "BTC/USDT", None, Some(50)).await?;
println!("Order has {} trades", trades.len());Edit order (cancel and replace)
§Arguments
id- Original order IDsymbol- Trading pair symbol (e.g., “BTC/USDT”)order_type- Order typeside- Order side (Buy/Sell)amount- Order quantityprice- Optional order price (required for limit orders)params- Optional additional parameters
§Returns
Returns new order information
§Example
let binance = Binance::new(ExchangeConfig::default())?;
let order = binance.edit_order(
"12345",
"BTC/USDT",
OrderType::Limit,
OrderSide::Buy,
dec!(0.01),
Some(dec!(50000.0)),
None
).await?;
println!("New order ID: {}", order.id);Sourcepub async fn edit_orders(
&self,
orders: Vec<(&str, &str, OrderType, OrderSide, Decimal, Option<Decimal>)>,
) -> Result<Vec<Order>, Error>
pub async fn edit_orders( &self, orders: Vec<(&str, &str, OrderType, OrderSide, Decimal, Option<Decimal>)>, ) -> Result<Vec<Order>, Error>
Edit multiple orders in batch
§Arguments
orders- Vector of order edit parameters, each element contains:- id: Original order ID
- symbol: Trading pair symbol
- order_type: Order type
- side: Order side
- amount: Order quantity
- price: Optional order price
§Returns
Returns vector of new order information
§Note
Binance does not support native batch order editing API. This method implements batch editing by concurrent calls to single order edits.
§Example
let binance = Binance::new(ExchangeConfig::default())?;
let order_params = vec![
("12345", "BTC/USDT", OrderType::Limit, OrderSide::Buy, dec!(0.01), Some(dec!(50000.0))),
("12346", "ETH/USDT", OrderType::Limit, OrderSide::Sell, dec!(0.1), Some(dec!(3000.0))),
];
let orders = binance.edit_orders(order_params).await?;
println!("Edited {} orders", orders.len());Sourcepub async fn create_listen_key(&self) -> Result<String, Error>
pub async fn create_listen_key(&self) -> Result<String, Error>
Create listen key for user data stream
Creates a listen key with 60-minute validity for subscribing to WebSocket user data stream. The listen key must be refreshed periodically to keep the connection active.
§Returns
Returns the listen key string
§Errors
- If API credentials are not configured
- If 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
- If API credentials are not configured
- If listen key is invalid or expired
- If API request fails
§Example
let listen_key = binance.create_listen_key().await?;
// Refresh after 30 minutes
binance.refresh_listen_key(&listen_key).await?;Sourcepub async fn delete_listen_key(&self, listen_key: &str) -> Result<(), Error>
pub async fn delete_listen_key(&self, listen_key: &str) -> Result<(), Error>
Delete listen key to close user data stream
Closes the user data stream connection and invalidates the listen key.
§Arguments
listen_key- The listen key to delete
§Returns
Returns Ok(()) on success
§Errors
- If API credentials are not configured
- If API request fails
§Example
let listen_key = binance.create_listen_key().await?;
// Delete after use
binance.delete_listen_key(&listen_key).await?;Sourcepub async fn create_orders(
&self,
orders: Vec<BatchOrderRequest>,
params: Option<Value>,
) -> Result<Vec<BatchOrderResult>, Error>
pub async fn create_orders( &self, orders: Vec<BatchOrderRequest>, params: Option<Value>, ) -> Result<Vec<BatchOrderResult>, Error>
Create orders in batch (up to 5 orders)
Creates multiple orders in a single API request to improve order placement efficiency.
§Arguments
orders: List of order requests (maximum 5)params: Optional parameters
§Returns
Returns list of batch order results
§Examples
let binance = Binance::new_futures(ExchangeConfig::default())?;
// Batch create orders
let orders = vec![
BatchOrderRequest {
symbol: "BTCUSDT".to_string(),
side: "BUY".to_string(),
order_type: "LIMIT".to_string(),
quantity: "0.001".to_string(),
price: Some("40000".to_string()),
time_in_force: Some("GTC".to_string()),
reduce_only: None,
position_side: Some("LONG".to_string()),
new_client_order_id: None,
},
BatchOrderRequest {
symbol: "ETHUSDT".to_string(),
side: "SELL".to_string(),
order_type: "LIMIT".to_string(),
quantity: "0.01".to_string(),
price: Some("3000".to_string()),
time_in_force: Some("GTC".to_string()),
reduce_only: None,
position_side: Some("SHORT".to_string()),
new_client_order_id: None,
},
];
let results = binance.create_orders(orders, None).await?;§API Endpoint
- Endpoint: POST /fapi/v1/batchOrders
- Weight: 5
- Requires signature: Yes
Sourcepub async fn batch_edit_orders(
&self,
updates: Vec<BatchOrderUpdate>,
params: Option<Value>,
) -> Result<Vec<BatchOrderResult>, Error>
pub async fn batch_edit_orders( &self, updates: Vec<BatchOrderUpdate>, params: Option<Value>, ) -> Result<Vec<BatchOrderResult>, Error>
Modify multiple orders in batch
Modifies the price and quantity of multiple orders in a single API request.
§Arguments
updates: List of order update requests (maximum 5)params: Optional parameters
§Returns
Returns list of batch order results
§Examples
let binance = Binance::new_futures(ExchangeConfig::default())?;
// Batch modify orders
let updates = vec![
BatchOrderUpdate {
order_id: Some(12345),
orig_client_order_id: None,
symbol: "BTCUSDT".to_string(),
side: "BUY".to_string(),
quantity: "0.002".to_string(),
price: "41000".to_string(),
},
];
let results = binance.edit_orders(updates, None).await?;§API Endpoint
- Endpoint: PUT /fapi/v1/batchOrders
- Weight: 5
- Requires signature: Yes
Sourcepub async fn batch_cancel_orders(
&self,
symbol: &str,
order_ids: Vec<i64>,
params: Option<Value>,
) -> Result<Vec<BatchCancelResult>, Error>
pub async fn batch_cancel_orders( &self, symbol: &str, order_ids: Vec<i64>, params: Option<Value>, ) -> Result<Vec<BatchCancelResult>, Error>
Cancel orders in batch by order IDs
Cancels multiple orders in a single API request.
§Arguments
symbol: Trading pair symbolorder_ids: List of order IDs (maximum 10)params: Optional parametersorigClientOrderIdList: List of original client order IDs (alternative to order_ids)
§Returns
Returns list of batch cancel results
§Examples
let binance = Binance::new_futures(ExchangeConfig::default())?;
// Batch cancel orders
let order_ids = vec![12345, 12346, 12347];
let results = binance.cancel_orders("BTC/USDT", order_ids, None).await?;§API Endpoint
- Endpoint: DELETE /fapi/v1/batchOrders
- Weight: 1
- Requires signature: Yes
Sourcepub async fn cancel_all_orders_futures(
&self,
symbol: &str,
params: Option<Value>,
) -> Result<CancelAllOrdersResult, Error>
pub async fn cancel_all_orders_futures( &self, symbol: &str, params: Option<Value>, ) -> Result<CancelAllOrdersResult, Error>
Cancel all open orders for a trading pair
Cancels all open orders for the specified trading pair.
§Arguments
symbol: Trading pair symbolparams: Optional parameters
§Returns
Returns result of canceling all orders
§Examples
let binance = Binance::new_futures(ExchangeConfig::default())?;
// Cancel all open orders for BTC/USDT
let result = binance.cancel_all_orders("BTC/USDT", None).await?;§API Endpoint
- Endpoint: DELETE /fapi/v1/allOpenOrders
- Weight: 1
- Requires signature: Yes
Sourcepub async fn fetch_account_configuration(&self) -> Result<AccountConfig, Error>
pub async fn fetch_account_configuration(&self) -> Result<AccountConfig, Error>
Fetch account configuration information
Retrieves futures account configuration parameters including multi-asset mode status and fee tier.
§Returns
Returns account configuration information
§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_futures(config)?;
let account_config = binance.fetch_account_configuration().await?;
println!("Multi-asset mode: {}", account_config.multi_assets_margin);
println!("Fee tier: {}", account_config.fee_tier);Sourcepub async fn set_multi_assets_mode(
&self,
multi_assets: bool,
) -> Result<(), Error>
pub async fn set_multi_assets_mode( &self, multi_assets: bool, ) -> Result<(), Error>
Set multi-asset mode
Enable or disable multi-asset margin mode.
§Arguments
multi_assets-trueto enable multi-asset mode,falsefor single-asset mode
§Returns
Returns operation result
§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_futures(config)?;
binance.set_multi_assets_mode(true).await?;Sourcepub async fn fetch_commission_rate(
&self,
symbol: &str,
) -> Result<CommissionRate, Error>
pub async fn fetch_commission_rate( &self, symbol: &str, ) -> Result<CommissionRate, Error>
Fetch futures commission rate
Retrieves maker and taker commission rates for the specified trading pair.
§Arguments
symbol- Trading pair symbol
§Returns
Returns commission rate information
§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_futures(config)?;
let rate = binance.fetch_commission_rate("BTC/USDT:USDT").await?;
println!("Maker rate: {}", rate.maker_commission_rate);
println!("Taker rate: {}", rate.taker_commission_rate);Sourcepub async fn fetch_open_interest(
&self,
symbol: &str,
) -> Result<OpenInterest, Error>
pub async fn fetch_open_interest( &self, symbol: &str, ) -> Result<OpenInterest, Error>
Fetch futures open interest
Retrieves the total amount of outstanding (open) contracts.
§Arguments
symbol- Trading pair symbol, e.g. “BTC/USDT:USDT”
§Returns
Returns open interest information
§API Endpoint
GET /fapi/v1/openInterest (MARKET_DATA)
§Examples
let binance = Binance::new_futures(ExchangeConfig::default())?;
let open_interest = binance.fetch_open_interest("BTC/USDT:USDT").await?;
println!("Open interest: {}", open_interest.open_interest);Sourcepub async fn fetch_open_interest_history(
&self,
symbol: &str,
period: &str,
limit: Option<u32>,
start_time: Option<u64>,
end_time: Option<u64>,
) -> Result<Vec<OpenInterestHistory>, Error>
pub async fn fetch_open_interest_history( &self, symbol: &str, period: &str, limit: Option<u32>, start_time: Option<u64>, end_time: Option<u64>, ) -> Result<Vec<OpenInterestHistory>, Error>
Fetch open interest history
§Arguments
symbol- Trading pair symbol, e.g. “BTC/USDT:USDT”period- Time period: “5m”, “15m”, “30m”, “1h”, “2h”, “4h”, “6h”, “12h”, “1d”limit- Number of records to return (default 30, maximum 500)start_time- Start timestamp in millisecondsend_time- End timestamp in milliseconds
§Returns
Returns list of open interest history records
§API Endpoint
GET /futures/data/openInterestHist (MARKET_DATA)
§Examples
let binance = Binance::new_futures(ExchangeConfig::default())?;
let history = binance.fetch_open_interest_history(
"BTC/USDT:USDT",
"1h",
Some(100),
None,
None
).await?;
println!("History records: {}", history.len());Sourcepub async fn fetch_max_leverage(
&self,
symbol: &str,
) -> Result<MaxLeverage, Error>
pub async fn fetch_max_leverage( &self, symbol: &str, ) -> Result<MaxLeverage, Error>
Fetch maximum available leverage for trading pair
§Arguments
symbol- Trading pair symbol, e.g. “BTC/USDT:USDT”
§Returns
Returns maximum leverage information
§Notes
This method retrieves maximum leverage by querying leverage bracket data.
§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_futures(config)?;
let max_leverage = binance.fetch_max_leverage("BTC/USDT:USDT").await?;
println!("Maximum leverage: {}x", max_leverage.max_leverage);Sourcepub async fn fetch_index_price(&self, symbol: &str) -> Result<IndexPrice, Error>
pub async fn fetch_index_price(&self, symbol: &str) -> Result<IndexPrice, Error>
Fetch index price
§Arguments
symbol- Trading pair symbol, e.g. “BTC/USDT”
§Returns
Returns index price information
§Examples
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;
#[tokio::main]
async fn main() {
let config = ExchangeConfig::default();
let binance = Binance::new(config).unwrap();
let index_price = binance.fetch_index_price("BTC/USDT").await.unwrap();
println!("Index Price: {}", index_price.index_price);
}Fetch premium index including mark price and funding rate
§Arguments
symbol- Trading pair symbol, e.g. “BTC/USDT”; ifNone, returns all trading pairs
§Returns
Returns premium index information (single or multiple)
§Examples
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;
#[tokio::main]
async fn main() {
let config = ExchangeConfig::default();
let binance = Binance::new(config).unwrap();
// Query single trading pair
let premium = binance.fetch_premium_index(Some("BTC/USDT")).await.unwrap();
println!("Mark Price: {}", premium[0].mark_price);
// Query all trading pairs
let all_premiums = binance.fetch_premium_index(None).await.unwrap();
println!("Total pairs: {}", all_premiums.len());
}Sourcepub async fn fetch_liquidations(
&self,
symbol: Option<&str>,
start_time: Option<u64>,
end_time: Option<u64>,
limit: Option<u32>,
) -> Result<Vec<Liquidation>, Error>
pub async fn fetch_liquidations( &self, symbol: Option<&str>, start_time: Option<u64>, end_time: Option<u64>, limit: Option<u32>, ) -> Result<Vec<Liquidation>, Error>
Fetch liquidation orders
§Arguments
symbol- Trading pair symbol, e.g. “BTC/USDT”; ifNone, returns all trading pairsstart_time- Start time (millisecond timestamp)end_time- End time (millisecond timestamp)limit- Quantity limit (default 100, maximum 1000)
§Returns
Returns list of liquidation orders
§Examples
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;
#[tokio::main]
async fn main() {
let config = ExchangeConfig::default();
let binance = Binance::new(config).unwrap();
// Query recent liquidation orders
let liquidations = binance.fetch_liquidations(
Some("BTC/USDT"),
None,
None,
Some(50)
).await.unwrap();
for liq in liquidations {
println!("Liquidation: {} {} @ {}", liq.side, liq.quantity, liq.price);
}
}Sourcepub async fn transfer(
&self,
currency: &str,
amount: f64,
from_account: &str,
to_account: &str,
params: Option<HashMap<String, String>>,
) -> Result<Transfer, Error>
pub async fn transfer( &self, currency: &str, amount: f64, from_account: &str, to_account: &str, params: Option<HashMap<String, String>>, ) -> Result<Transfer, Error>
Execute internal transfer
Transfer assets between different account types (spot, margin, futures, funding, etc.)
§Arguments
currency- Asset code (e.g. “USDT”, “BTC”)amount- Transfer amountfrom_account- Source account type (spot/margin/future/funding, etc.)to_account- Target account typeparams- Optional additional parameters
§Binance API
- Endpoint: POST /sapi/v1/asset/transfer
- Weight: 900 (UID)
- Required permission: TRADE
- Signature required: Yes
§Supported Account Types
- MAIN: Spot account
- UMFUTURE: USDT-margined futures account
- CMFUTURE: Coin-margined futures account
- MARGIN: Cross margin account
- ISOLATED_MARGIN: Isolated margin account
- FUNDING: Funding account
- OPTION: Options account
§Examples
let config = ExchangeConfig {
api_key: Some("your_api_key".to_string()),
secret: Some("your_secret".to_string()),
..Default::default()
};
let binance = Binance::new(config)?;
// Transfer 100 USDT from spot to futures account
let transfer = binance.transfer(
"USDT",
100.0,
"spot", // From spot
"future", // To futures
None
).await?;
println!("Transfer ID: {:?}", transfer.id);
println!("Status: {}", transfer.status);Sourcepub async fn fetch_transfers(
&self,
currency: Option<&str>,
since: Option<u64>,
limit: Option<u64>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<Transfer>, Error>
pub async fn fetch_transfers( &self, currency: Option<&str>, since: Option<u64>, limit: Option<u64>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Transfer>, Error>
Fetch internal transfer history
Retrieve historical records of transfers between accounts
§Arguments
currency- Optional asset code filtersince- Optional start timestamp (milliseconds)limit- Optional quantity limit (default 100, maximum 100)params- Optional additional parameters (may include fromSymbol/toSymbol to specify transfer direction)
§API Endpoint
- Endpoint: GET /sapi/v1/asset/transfer
- Weight: 1
- Required permission: USER_DATA
- Signature required: Yes
§Examples
let config = ExchangeConfig {
api_key: Some("your_api_key".to_string()),
secret: Some("your_secret".to_string()),
..Default::default()
};
let binance = Binance::new(config)?;
// Query recent USDT transfer records
let transfers = binance.fetch_transfers(
Some("USDT"),
None,
Some(50),
None
).await?;
for transfer in transfers {
println!("{} {} from {:?} to {:?}",
transfer.amount,
transfer.currency,
transfer.from_account,
transfer.to_account
);
}Sourcepub async fn futures_transfer(
&self,
currency: &str,
amount: f64,
transfer_type: i32,
params: Option<HashMap<String, String>>,
) -> Result<Transfer, Error>
pub async fn futures_transfer( &self, currency: &str, amount: f64, transfer_type: i32, params: Option<HashMap<String, String>>, ) -> Result<Transfer, Error>
Execute futures account transfer
Transfer assets between spot account and futures accounts
§Arguments
currency- Asset code (e.g. “USDT”, “BTC”)amount- Transfer quantitytransfer_type- Transfer type:- 1: Spot account → USDT-M futures account
- 2: USDT-M futures account → Spot account
- 3: Spot account → COIN-M futures account
- 4: COIN-M futures account → Spot account
params- Optional additional parameters
§API Endpoint
- Endpoint: POST /sapi/v1/futures/transfer
- Weight: 1
- Required permission: TRADE
- Signature required: Yes
§Differences from transfer()
futures_transfer(): Futures-specific API with concise parameters, only requires type (1-4)transfer(): Generic API supporting 8 account types, requires fromSymbol/toSymbol parameters
§Examples
let config = ExchangeConfig {
api_key: Some("your_api_key".to_string()),
secret: Some("your_secret".to_string()),
..Default::default()
};
let binance = Binance::new(config)?;
// Transfer 100 USDT from spot to USDT-M futures account
let transfer = binance.futures_transfer(
"USDT",
100.0,
1, // type 1 = Spot → USDT-M futures
None
).await?;
println!("Transfer ID: {:?}", transfer.id);
println!("Status: {}", transfer.status);Sourcepub async fn fetch_futures_transfers(
&self,
currency: &str,
since: Option<u64>,
limit: Option<u64>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<Transfer>, Error>
pub async fn fetch_futures_transfers( &self, currency: &str, since: Option<u64>, limit: Option<u64>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Transfer>, Error>
Fetch futures transfer history
Retrieve historical records of transfers between spot and futures accounts
§Arguments
currency- Asset code (e.g. “USDT”, “BTC”)since- Optional start timestamp (milliseconds)limit- Optional quantity limit (default 10, maximum 100)params- Optional additional parametersendTime: End timestamp (milliseconds)current: Current page number (default 1)
§API Endpoint
- Endpoint: GET /sapi/v1/futures/transfer
- Weight: 10
- Required permission: USER_DATA
- Signature required: Yes
§Return Fields
- tranId: Transfer ID
- asset: Asset code
- amount: Transfer quantity
- type: Transfer type (1-4)
- timestamp: Transfer time
- status: Transfer status (CONFIRMED/FAILED/PENDING)
§Examples
let config = ExchangeConfig {
api_key: Some("your_api_key".to_string()),
secret: Some("your_secret".to_string()),
..Default::default()
};
let binance = Binance::new(config)?;
// Query USDT transfer records from the last 30 days
let since = chrono::Utc::now().timestamp_millis() as u64 - 30 * 24 * 60 * 60 * 1000;
let transfers = binance.fetch_futures_transfers(
"USDT",
Some(since),
Some(50),
None
).await?;
for transfer in transfers {
println!("{} {} from {:?} to {:?} - Status: {}",
transfer.amount,
transfer.currency,
transfer.from_account,
transfer.to_account,
transfer.status
);
}Sourcepub async fn fetch_deposit_withdraw_fees(
&self,
currency: Option<&str>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<DepositWithdrawFee>, Error>
pub async fn fetch_deposit_withdraw_fees( &self, currency: Option<&str>, params: Option<HashMap<String, String>>, ) -> Result<Vec<DepositWithdrawFee>, Error>
Fetch deposit and withdrawal fee information
Query deposit and withdrawal fee configuration for all assets
§Arguments
currency- Optional asset code filter (returns all assets if not specified)params- Optional additional parameters
§API Endpoint
- Endpoint: GET /sapi/v1/capital/config/getall
- Weight: 10
- Required permission: USER_DATA
- Signature required: Yes
§Return Information
- Withdrawal fee
- Minimum/maximum withdrawal amount
- Deposit/withdrawal support status
- Network configurations (BTC, ETH, BSC, etc.)
- Confirmation requirements
§Examples
let config = ExchangeConfig {
api_key: Some("your_api_key".to_string()),
secret: Some("your_secret".to_string()),
..Default::default()
};
let binance = Binance::new(config)?;
// Fetch fee information for all assets
let fees = binance.fetch_deposit_withdraw_fees(None, None).await?;
// Fetch fee information for specific asset (e.g. USDT)
let usdt_fees = binance.fetch_deposit_withdraw_fees(Some("USDT"), None).await?;
for fee in usdt_fees {
println!("{}: withdraw fee = {}, min = {}, max = {}",
fee.currency,
fee.withdraw_fee,
fee.withdraw_min,
fee.withdraw_max
);
for network in &fee.networks {
println!(" Network {}: fee = {}", network.network, network.withdraw_fee);
}
}Sourcepub async fn withdraw(
&self,
code: &str,
amount: &str,
address: &str,
params: Option<HashMap<String, String>>,
) -> Result<Transaction, Error>
pub async fn withdraw( &self, code: &str, amount: &str, address: &str, params: Option<HashMap<String, String>>, ) -> Result<Transaction, Error>
Withdraw to external address
§Arguments
code- Currency code (e.g. “BTC”, “USDT”)amount- Withdrawal amountaddress- Withdrawal addressparams- Optional parameterstag: Address tag (e.g. XRP tag)network: Network type (e.g. “ETH”, “BSC”, “TRX”)addressTag: Address tag (alias)name: Address memo namewalletType: Wallet type (0=spot, 1=funding)
§API Endpoint
- Endpoint: POST /sapi/v1/capital/withdraw/apply
- Required permission: API key with withdrawal enabled
§Examples
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 = HashMap::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<HashMap<String, String>>,
) -> Result<Vec<Transaction>, Error>
pub async fn fetch_deposits( &self, code: Option<&str>, since: Option<i64>, limit: Option<i64>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Transaction>, Error>
Fetch deposit history
§Arguments
code- Optional currency code (e.g. “BTC”, “USDT”)since- Optional start timestamp (milliseconds)limit- Optional quantity limitparams- Optional parameterscoin: Currency (overrides code parameter)status: Status filter (0=pending, 6=credited, 1=success)startTime: Start timestamp (milliseconds)endTime: End timestamp (milliseconds)offset: Offset (for pagination)txId: Transaction ID filter
§API Endpoint
- Endpoint: GET /sapi/v1/capital/deposit/hisrec
- Required permission: API key
§Time Range Limit
- Maximum query range: 90 days
- Default returns last 90 days if no time range provided
§Examples
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<HashMap<String, String>>,
) -> Result<Vec<Transaction>, Error>
pub async fn fetch_withdrawals( &self, code: Option<&str>, since: Option<i64>, limit: Option<i64>, params: Option<HashMap<String, String>>, ) -> Result<Vec<Transaction>, Error>
Fetch withdrawal history
§Arguments
code- Optional currency code (e.g. “BTC”, “USDT”)since- Optional start timestamp (milliseconds)limit- Optional quantity limitparams- Optional parameterscoin: Currency (overrides code parameter)withdrawOrderId: Withdrawal order IDstatus: Status filter (0=email sent, 1=cancelled, 2=awaiting approval, 3=rejected, 4=processing, 5=failure, 6=completed)startTime: Start timestamp (milliseconds)endTime: End timestamp (milliseconds)offset: Offset (for pagination)
§API Endpoint
- Endpoint: GET /sapi/v1/capital/withdraw/history
- Required permission: API key
§Time Range Limit
- Maximum query range: 90 days
- Default returns last 90 days if no time range provided
§Examples
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_address(
&self,
code: &str,
params: Option<HashMap<String, String>>,
) -> Result<DepositAddress, Error>
pub async fn fetch_deposit_address( &self, code: &str, params: Option<HashMap<String, String>>, ) -> Result<DepositAddress, Error>
Fetch deposit address
§Arguments
code- Currency code (e.g. “BTC”, “USDT”)params- Optional parametersnetwork: Network type (e.g. “ETH”, “BSC”, “TRX”)coin: Currency (overrides code parameter)
§API Endpoint
- Endpoint: GET /sapi/v1/capital/deposit/address
- Required permission: API key
§Notes
- Binance automatically generates new address if none exists
- Some currencies require network parameter (e.g. USDT can be ETH/BSC/TRX network)
§Examples
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 = HashMap::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 create_oco_order(
&self,
symbol: &str,
side: OrderSide,
amount: f64,
price: f64,
stop_price: f64,
stop_limit_price: Option<f64>,
params: Option<HashMap<String, String>>,
) -> Result<OcoOrder, Error>
pub async fn create_oco_order( &self, symbol: &str, side: OrderSide, amount: f64, price: f64, stop_price: f64, stop_limit_price: Option<f64>, params: Option<HashMap<String, String>>, ) -> Result<OcoOrder, Error>
Create OCO order (One-Cancels-the-Other)
OCO order contains two orders: take-profit order (limit) + stop-loss order (stop-limit). When one order is filled, the other is automatically cancelled.
§Arguments
symbol- Trading pair symbol, e.g. “BTC/USDT”side- Order side (Buy or Sell)amount- Order quantityprice- Take-profit price (limit order price)stop_price- Stop-loss trigger pricestop_limit_price- Optional stop-limit order price, defaults to stop_priceparams- Optional additional parameters
§Returns
Returns created OCO order information
§Example
let binance = Binance::new(ExchangeConfig::default())?;
// Long BTC position: take profit at 50000, stop loss at 45000
let oco = binance.create_oco_order(
"BTC/USDT",
OrderSide::Sell,
0.1,
50000.0,
45000.0,
Some(44500.0),
None
).await?;
println!("OCO order ID: {}", oco.order_list_id);Sourcepub async fn fetch_oco_order(
&self,
order_list_id: i64,
symbol: &str,
params: Option<HashMap<String, String>>,
) -> Result<OcoOrder, Error>
pub async fn fetch_oco_order( &self, order_list_id: i64, symbol: &str, params: Option<HashMap<String, String>>, ) -> Result<OcoOrder, Error>
Sourcepub async fn fetch_oco_orders(
&self,
symbol: &str,
since: Option<u64>,
limit: Option<u32>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<OcoOrder>, Error>
pub async fn fetch_oco_orders( &self, symbol: &str, since: Option<u64>, limit: Option<u32>, params: Option<HashMap<String, String>>, ) -> Result<Vec<OcoOrder>, Error>
Sourcepub async fn cancel_oco_order(
&self,
order_list_id: i64,
symbol: &str,
params: Option<HashMap<String, String>>,
) -> Result<OcoOrder, Error>
pub async fn cancel_oco_order( &self, order_list_id: i64, symbol: &str, params: Option<HashMap<String, String>>, ) -> Result<OcoOrder, Error>
Sourcepub async fn create_test_order(
&self,
symbol: &str,
order_type: OrderType,
side: OrderSide,
amount: f64,
price: Option<f64>,
params: Option<HashMap<String, String>>,
) -> Result<Order, Error>
pub async fn create_test_order( &self, symbol: &str, order_type: OrderType, side: OrderSide, amount: f64, price: Option<f64>, params: Option<HashMap<String, String>>, ) -> Result<Order, Error>
Create test order (does not place actual order)
Used to test if order parameters are correct without submitting to exchange.
§Arguments
symbol- Trading pair symbolorder_type- Order typeside- Order side (Buy/Sell)amount- Order quantityprice- Optional priceparams- Optional additional parameters
§Returns
Returns empty order information (validation result only)
§Example
let binance = Binance::new(ExchangeConfig::default())?;
// Test if order parameters are correct
let test = binance.create_test_order(
"BTC/USDT",
OrderType::Limit,
OrderSide::Buy,
0.001,
40000.0,
None
).await?;
println!("Order parameters validated successfully");Sourcepub async fn fetch_isolated_borrow_rates(
&self,
params: Option<HashMap<String, String>>,
) -> Result<HashMap<String, IsolatedBorrowRate>, Error>
pub async fn fetch_isolated_borrow_rates( &self, params: Option<HashMap<String, String>>, ) -> Result<HashMap<String, IsolatedBorrowRate>, Error>
Fetch all isolated margin borrow rates
§Arguments
params- Optional parameters
§Returns
HashMap<Symbol, IsolatedBorrowRate>
§API Endpoint
GET /sapi/v1/margin/isolatedMarginData
§Examples
let binance = Binance::new(ExchangeConfig::default())?;
let rates = binance.fetch_isolated_borrow_rates(None).await?;
println!("Got {} symbols", rates.len());Sourcepub async fn fetch_borrow_interest(
&self,
code: Option<&str>,
symbol: Option<&str>,
since: Option<u64>,
limit: Option<u64>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<BorrowInterest>, Error>
pub async fn fetch_borrow_interest( &self, code: Option<&str>, symbol: Option<&str>, since: Option<u64>, limit: Option<u64>, params: Option<HashMap<String, String>>, ) -> Result<Vec<BorrowInterest>, Error>
Fetch borrow interest history
§Arguments
code- Asset code (optional, e.g., “BTC”)symbol- Trading pair symbol (optional, for isolated margin only, e.g., “BTC/USDT”)since- Start timestamp (milliseconds)limit- Number of records to return (default 10, max 100)params- Optional parametersendTime: End timestampisolatedSymbol: Isolated margin trading pair (overrides symbol parameter)archived: Whether to query archived data (default false)
§API Endpoint
- Spot Margin: GET /sapi/v1/margin/interestHistory
- Portfolio Margin: GET /papi/v1/margin/marginInterestHistory
§Examples
let binance = Binance::new(ExchangeConfig::default())?;
// Fetch cross-margin BTC borrow interest
let interests = binance.fetch_borrow_interest(
Some("BTC"),
None,
None,
Some(10),
None
).await?;
// Fetch isolated margin BTC/USDT borrow interest
let interests = binance.fetch_borrow_interest(
None,
Some("BTC/USDT"),
None,
Some(10),
None
).await?;Sourcepub async fn fetch_borrow_rate_history(
&self,
code: &str,
since: Option<u64>,
limit: Option<u64>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<BorrowRateHistory>, Error>
pub async fn fetch_borrow_rate_history( &self, code: &str, since: Option<u64>, limit: Option<u64>, params: Option<HashMap<String, String>>, ) -> Result<Vec<BorrowRateHistory>, Error>
Fetch margin borrow rate history
§Arguments
code- Asset code (e.g., “USDT”)since- Start timestamp in millisecondslimit- Number of records to return (default 10, max 100, but actual limit is 92)params- Optional parametersendTime: End timestampvipLevel: VIP level
§Notes
- Binance API has special limit restriction, cannot exceed 92
- For more data, use multiple requests with pagination
§API Endpoint
GET /sapi/v1/margin/interestRateHistory
§Examples
let binance = Binance::new(ExchangeConfig::default())?;
let history = binance.fetch_borrow_rate_history(
"USDT",
None,
Some(50),
None
).await?;
println!("Got {} records", history.len());Sourcepub async fn fetch_ledger(
&self,
code: Option<String>,
since: Option<i64>,
limit: Option<i64>,
params: Option<HashMap<String, String>>,
) -> Result<Vec<LedgerEntry>, Error>
pub async fn fetch_ledger( &self, code: Option<String>, since: Option<i64>, limit: Option<i64>, params: Option<HashMap<String, String>>, ) -> Result<Vec<LedgerEntry>, Error>
Fetch ledger history
Important Notes:
- Only supports futures wallets (option, USDT-M, COIN-M)
- Spot wallet is not supported, returns NotSupported error
- For portfolioMargin accounts, uses unified account API
§API Endpoint Mapping
| Market Type | Endpoint | Field Format |
|---|---|---|
| Option | GET /eapi/v1/bill | id, asset, amount, type |
| USDT-M (linear) | GET /fapi/v1/income | tranId, asset, income, incomeType |
| USDT-M+Portfolio | GET /papi/v1/um/income | tranId, asset, income, incomeType |
| COIN-M (inverse) | GET /dapi/v1/income | tranId, asset, income, incomeType |
| COIN-M+Portfolio | GET /papi/v1/cm/income | tranId, asset, income, incomeType |
§Arguments
code- Currency code (required for option market)since- Start timestamp in millisecondslimit- Maximum number of records to returnparams- Additional parameters:until: End timestamp in millisecondsportfolioMargin: Whether to use portfolio margin account (unified account)type: Market type (“spot”, “margin”, “future”, “swap”, “option”)subType: Sub-type (“linear”, “inverse”)
§Returns
Returns list of LedgerEntry, sorted by time in descending order
§Errors
- Returns NotSupported error if market type is spot
- Returns ArgumentsRequired error if code parameter is not provided for option market
§Examples
use ccxt_exchanges::binance::Binance;
use ccxt_core::ExchangeConfig;
use std::collections::HashMap;
#[tokio::main]
async fn main() {
let mut config = ExchangeConfig::default();
config.api_key = Some("your-api-key".to_string());
config.secret = Some("your-api-secret".to_string());
let binance = Binance::new(config).unwrap();
// USDT-M futures ledger
let mut params = HashMap::new();
params.insert("type".to_string(), "future".to_string());
params.insert("subType".to_string(), "linear".to_string());
let ledger = binance.fetch_ledger(
Some("USDT".to_string()),
None,
Some(100),
Some(params)
).await.unwrap();
// Option ledger (code is required)
let mut params = HashMap::new();
params.insert("type".to_string(), "option".to_string());
let ledger = binance.fetch_ledger(
Some("USDT".to_string()),
None,
Some(100),
Some(params)
).await.unwrap();
}Sourcepub async fn fetch_order_trades(
&self,
id: &str,
symbol: &str,
since: Option<u64>,
limit: Option<u32>,
) -> Result<Vec<Trade>, Error>
pub async fn fetch_order_trades( &self, id: &str, symbol: &str, since: Option<u64>, limit: Option<u32>, ) -> Result<Vec<Trade>, Error>
Fetch trades for a specific order
§Arguments
id- Order IDsymbol- Trading pair symbol (required)since- Optional start timestamp in millisecondslimit- Optional maximum number of records
§Returns
Returns all trades for the specified order
§Notes
symbolparameter is required- Only supports spot markets
- Internally calls fetch_my_trades method with orderId filter
- API endpoint: GET /api/v3/myTrades
§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(config)?;
let trades = binance.fetch_order_trades("123456789", "BTC/USDT", None, None).await?;
println!("Order has {} trades", trades.len());Sourcepub async fn fetch_canceled_orders(
&self,
symbol: &str,
since: Option<u64>,
limit: Option<u32>,
) -> Result<Vec<Order>, Error>
pub async fn fetch_canceled_orders( &self, symbol: &str, since: Option<u64>, limit: Option<u32>, ) -> Result<Vec<Order>, Error>
Fetch canceled orders
§Arguments
symbol- Trading pair symbol (required)since- Optional start timestamp in millisecondslimit- Optional maximum number of records
§Returns
Returns list of canceled orders
§Notes
symbolparameter is required- Calls fetch_orders to get all orders, then filters for canceled status
limitparameter is applied client-side (fetch all orders first, then take first N)- Implementation logic matches Go version
§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(config)?;
let canceled_orders = binance.fetch_canceled_orders("BTC/USDT", None, Some(10)).await?;
println!("Found {} canceled orders", canceled_orders.len());Sourcepub async fn create_market_buy_order_with_cost(
&self,
symbol: &str,
cost: f64,
params: Option<HashMap<String, String>>,
) -> Result<Order, Error>
pub async fn create_market_buy_order_with_cost( &self, symbol: &str, cost: f64, params: Option<HashMap<String, String>>, ) -> Result<Order, Error>
Create market buy order by cost amount
§Arguments
symbol- Trading pair symbolcost- Amount in quote currency to spend (e.g., spend 100 USDT to buy BTC)params- Optional additional parameters
§Returns
Returns created order information
§Notes
- Only supports spot markets
costparameter is converted to Binance API’squoteOrderQtyparameter- This is a convenience method to simplify market buy order creation
- Internally calls create_order method
§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(config)?;
// Spend 100 USDT to buy BTC (market order)
let order = binance.create_market_buy_order_with_cost("BTC/USDT", 100.0, None).await?;
println!("Order created: {:?}", order);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();
let ticker = exchange.watch_ticker("BTC/USDT", None).await?;
println!("Price: {}", ticker.last.unwrap_or(0.0));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();
// 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();
// 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();
// 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();
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 = Binance::new(config)?;
// Watch spot account balance
let balance = exchange.watch_balance(None).await?;
// Watch futures account balance
let mut params = HashMap::new();
params.insert("type".to_string(), json!("future"));
let futures_balance = exchange.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.watch_orders(None, None, None, None).await?;
println!("Received {} order updates", orders.len());
// Watch updates for a specific trading pair
let btc_orders = exchange.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;
#[tokio::main]
async fn main() {
let exchange = Arc::new(Binance::new(Default::default()));
let ws = exchange.create_authenticated_ws();
// Subscribe to BTC/USDT trade updates
let trades = ws.watch_my_trades(Some("BTC/USDT"), None, None, None).await.unwrap();
println!("My trades: {:?}", trades);
}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());
// Watch all positions
let positions = exchange.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.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;
let config = ExchangeConfig::default();
let options = BinanceOptions {
default_type: "future".to_string(),
..Default::default()
};
let binance = Binance::new_with_options(config, options).unwrap();Sourcepub fn new_futures(config: ExchangeConfig) -> Result<Binance, Error>
pub fn new_futures(config: ExchangeConfig) -> Result<Binance, Error>
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 rate_limit(&self) -> f64
pub fn rate_limit(&self) -> f64
Returns the rate limit in requests per second.
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 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.).
§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.
§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?;