This module provides the official Rust client for Binance's SPOT API, enabling developers to interact programmatically with Binance's SPOT trading platform. The library provides tools for retrieving market data, executing trades, and managing orders through three distinct endpoints:
- Supported Features
- Installation
- Documentation
- REST APIs
- Websocket APIs
- Websocket Streams
- Logging
- Testing
- Migration Guide
- Contributing
- License
- REST API Endpoints:
/api/*
- WebSocket Endpoints: Real-time data streaming and request-response communication.
- Inclusion of test cases and examples for quick onboarding.
Enable the spot feature in your Cargo.toml under binance-sdk:
[dependencies]
binance-sdk = { version = "1.0.0", features = ["spot"] }In your code, import the spot client:
use binance_sdk::spot;- Crate documentation: docs.rs/binance_sdk
- Official Binance SPOT API docs: Binance API Documentation
All REST API endpoints are available through the rest_api module. Note that some endpoints require authentication using your Binance API credentials.
use binance_sdk::config::ConfigurationRestApi;
use binance_sdk::spot;
let configuration = ConfigurationRestApi::builder()
.api_key("YOUR_API_KEY")
.api_secret("YOUR_SECRET_KEY")
.build()?;
let client = spot::SpotRestApi::production(configuration);
let params = spot::rest_api::ExchangeInfoParams::default();
let response = client.exchange_info(params).await?;
let data = response.data().await?;
println!("{:#?}", data);The spot module can be configured with the following options via the ConfigurationRestApi builder pattern:
timeout(u64): Request timeout in milliseconds (default: 1000)proxy(ProxyConfig): HTTP/HTTPS proxy settingshost(String): Proxy server hostname.port(u16): Proxy server port.protocol(String): Proxy protocol (http or https).auth(ProxyAuth): Proxy authentication credentials:username(String): Proxy username.password(String): Proxy password.
keep_alive(bool): Enable HTTP keep-alive (default: true)compression(bool): Enable response compression (default: true)retries(u32): Number of retry attempts for failed requests (default: 3)backoff(u64): Delay in milliseconds between retries (default: 1000)agent(HttpAgent): Custom HTTP agent for advanced TLS configurationprivate_key(PrivateKey): RSA or ED25519 private key for request signing (raw string or PEM file path)private_key_passphrase(String): Passphrase for the private key, if encryptedtime_unit(TimeUnit): Specify the time unit for timestamps (e.g., milliseconds or microseconds)
Refer to the configuration for more details.
You can configure a timeout for requests in milliseconds. If the request exceeds the specified timeout, it will be aborted. See the Timeout example for detailed usage.
The REST API supports HTTP/HTTPS proxy configurations. See the Proxy example for detailed usage.
Enable HTTP keep-alive for persistent connections. See the Keep-Alive example for detailed usage.
Enable or disable response compression. See the Compression example for detailed usage.
Configure the number of retry attempts and delay in milliseconds between retries for failed requests. See the Retries example for detailed usage.
Customize the HTTPS agent for advanced TLS configurations. See the HTTPS Agent example for detailed usage.
The REST API supports key pair-based authentication for secure communication. You can use RSA or Ed25519 keys for signing requests. See the Key Pair Based Authentication example for detailed usage.
To enhance security, you can use certificate pinning with the agent option in the configuration. This ensures the client only communicates with servers using specific certificates. See the Certificate Pinning example for detailed usage.
Specify the time unit for REST API timestamps (e.g., milliseconds or microseconds). See the Time Unit example for detailed usage.
Errors are represented by the following types:
ConnectorClientError: General client errorUnauthorizedError: Invalid or missing authenticationForbiddenError: Access to resource forbiddenTooManyRequestsError: Rate limit exceededRateLimitBanError: IP banned due to rate limitsServerError: Internal server errorNetworkError: Network connectivity issuesNotFoundError: Resource not foundBadRequestError: Invalid request parameters
See the Error Handling example for detailed usage. Refer to the error module for more information.
For testing purposes, the REST APIs also supports a testnet environment:
use binance_sdk::config::ConfigurationRestApi;
use binance_sdk::spot;
let configuration = ConfigurationRestApi::builder()
.api_key("YOUR_API_KEY")
.api_secret("YOUR_SECRET_KEY")
.build()?;
let client = spot::SpotRestApi::testnet(configuration);The WebSocket API provides request-response communication for market data and trading actions. Use the websocket_api module to interact with these endpoints.
use binance_sdk::config::ConfigurationWebsocketApi;
use binance_sdk::spot;
let configuration = ConfigurationWebsocketApi::builder()
.api_key("YOUR_API_KEY")
.api_secret("YOUR_SECRET_KEY")
.build()?;
let client = spot::SpotWsApi::production(configuration);
let connection = client.connect().await?;
let params = spot::websocket_api::ExchangeInfoParams::default();
let response = connection.exchange_info(params).await?;
let data = response.data().await?;
println!("{:#?}", data);The spot module can be configured with the following options via the ConfigurationWebsocketApi builder pattern:
timeout(u64): WS request timeout in milliseconds (default: 5000)reconnect_delay(u64): Specify the delay between reconnection attempts in milliseconds (default: 5000)mode(WebsocketMode): Choose betweensingleandpoolconnection modesSingle: A single WebSocket connectionPool: A pool of WebSocket connections
agent(AgentConnector): Customize the WebSocket agent for advanced configurationsprivate_key(PrivateKey): RSA or ED25519 private key for request signing (raw string or PEM file path)private_key_passphrase(String): Passphrase for the private key, if encryptedtime_unit(TimeUnit): Specify the time unit for timestamps (e.g., milliseconds or microseconds)
Refer to the configuration for more details.
Set the timeout for WebSocket API requests in milliseconds. See the Timeout example for detailed usage.
Specify the delay in milliseconds between WebSocket reconnection attempts. See the Reconnect Delay example for detailed usage.
Customize the agent for advanced configurations. See the WebSocket Agent example for detailed usage.
Choose between Single and Pool connection modes for WebSocket connections. The Single mode uses a single WebSocket connection, while the Pool mode uses a pool of WebSocket connections. See the Connection Mode example for detailed usage.
Use RSA or ED25519 private keys for WebSocket API authentication. See the Key Pair Authentication example for detailed usage.
To enhance security, you can use certificate pinning with the agent option in the configuration. This ensures the client only communicates with servers using specific certificates. See the Certificate Pinning example for detailed usage.
Specify the time unit for WebSocket API timestamps (e.g., milliseconds or microseconds). See the Time Unit example for detailed usage.
You can consume the user data stream, which sends account-level events such as account and order updates. First do a logon to the websocket connection via WebSocket API; then:
use tracing::info;
use binance_sdk::config::ConfigurationWebsocketApi;
use binance_sdk::spot::{SpotWsApi, websocket_api::{SessionLogonParams, UserDataStreamSubscribeParams, UserDataStreamEventsResponse}};
let configuration = ConfigurationWebsocketApi::builder().build()?;
let client = SpotWsApi::production(configuration);
let connection = client.connect().await?;
let params = SessionLogonParams::default();
// Make the WS API call
let response = connection
.session_logon(SessionLogonParams::default())
.await?;
let (response, stream) = connection
.user_data_stream_subscribe(UserDataStreamSubscribeParams::default())
.await?;
stream.on_message(|data: UserDataStreamEventsResponse| {
match data {
UserDataStreamEventsResponse::OutboundAccountPosition(data) => {
info!("outbound account position stream {:?}", data);
}
UserDataStreamEventsResponse::BalanceUpdate(data) => {
info!("balance update stream {:?}", data);
}
UserDataStreamEventsResponse::Other(data) => {
info!("unknown stream {:?}", data);
}
// …handle other variants…
}
});For testing purposes, the Websocket API also supports a testnet environment:
use binance_sdk::config::ConfigurationWebsocketApi;
use binance_sdk::spot;
let configuration = ConfigurationWebsocketApi::builder()
.api_key("YOUR_API_KEY")
.api_secret("YOUR_SECRET_KEY")
.build()?;
let client = spot::SpotWsApi::testnet(configuration);The WebSocket Streams provide real-time data feeds for market trades, candlesticks, and more. Use the websocket_streams module to interact with these endpoints.
use binance_sdk::config::ConfigurationWebsocketStreams;
use binance_sdk::spot;
let configuration = ConfigurationWebsocketStreams::builder().build()?;
let client = spot::SpotWsStreams::production(configuration);
let connection = client.connect().await?;
let params = spot::websocket_streams::AggTradeParams::default();
let stream = connection.agg_trade(params).await?;
stream.on_message(|data| {
println!("{:#?}", data);
});The spot module can be configured with the following options via the ConfigurationWebsocketStreams builder pattern:
reconnect_delay(u64): Specify the delay between reconnection attempts in milliseconds (default: 5000)mode(WebsocketMode): Choose betweensingleandpoolconnection modesSingle: A single WebSocket connectionPool: A pool of WebSocket connections
agent(AgentConnector): Customize the WebSocket agent for advanced configurationstime_unit(TimeUnit): Specify the time unit for timestamps (e.g., milliseconds or microseconds)
Refer to the configuration for more details.
Specify the delay in milliseconds between WebSocket reconnection attempts. See the Reconnect Delay example for detailed usage.
Customize the agent for advanced configurations. See the WebSocket Agent example for detailed usage.
Choose between Single and Pool connection modes for WebSocket connections. The Single mode uses a single WebSocket connection, while the Pool mode uses a pool of WebSocket connections. See the Connection Mode example for detailed usage.
To enhance security, you can use certificate pinning with the agent option in the configuration. This ensures the client only communicates with servers using specific certificates. See the Certificate Pinning example for detailed usage.
Specify the time unit for WebSocket API timestamps (e.g., milliseconds or microseconds). See the Time Unit example for detailed usage.
You can unsubscribe from specific WebSocket streams using the unsubscribe method. This is useful for managing active subscriptions without closing the connection.
use tokio::time::{Duration, sleep};
use binance_sdk::config::ConfigurationWebsocketStreams;
use binance_sdk::spot;
let configuration = ConfigurationWebsocketStreams::builder().build()?;
let client = spot::SpotWsStreams::production(configuration);
let connection = client.connect().await?;
let params = spot::websocket_streams::AggTradeParams::default();
let stream = connection.agg_trade(params).await?;
stream.on_message(|data| {
println!("{:#?}", data);
});
sleep(Duration::from_secs(10)).await;
stream.unsubscribe().await;For testing purposes, the Websocket Streams also supports a testnet environment:
use binance_sdk::config::ConfigurationWebsocketStreams;
use binance_sdk::spot;
let configuration = ConfigurationWebsocketStreams::builder().build()?;
let client = spot::SpotWsStreams::testnet(configuration);The WebSocket connection is automatically renewed for both WebSocket API and WebSocket Streams connections, before the 24 hours expiration of the API key. This ensures continuous connectivity.
This crate ships with an optional default logger that you can enable with a single call:
use binance_sdk::logger;
fn main() {
// Initialize the default logger once at the start of your application
logger::init();
// ... rest of your code
}The logger integrates with the Rust tracing ecosystem and behaves as follows:
- If another global subscriber is already set,
logger::init()is a no-op and does not override your existing logging setup. - If no subscriber is set yet, it installs the crate’s default global subscriber (with sensible defaults) so you immediately get structured logs from the connector.
To run the tests for the SPOT module:
cargo test --features spotTests cover:
- REST API endpoint integration
- Error scenarios and edge cases
If you are upgrading from a legacy, single-crate connector that included SPOT support, see the Migration Guide for instructions on enabling the spot feature.
Contributions are welcome!
Since this repository contains auto-generated code, we encourage you to start by opening a GitHub issue to discuss your ideas or suggest improvements. This helps ensure that changes align with the project's goals and auto-generation processes.
To contribute:
- Open a GitHub issue describing your suggestion or the bug you've identified.
- If it's determined that changes are necessary, the maintainers will merge the changes into the main branch.
Please ensure that all tests pass with --features spot if you're making a direct contribution. Submit a pull request only after discussing and confirming the change.
Thank you for your contributions!
This project is licensed under the MIT License. See the LICENSE file for details.