binance_futures_rs/
lib.rs

1//! # Binance Futures API Rust Client
2//! 
3//! A comprehensive Rust client library for the Binance Futures API.
4//! This library provides async/await support for all Binance Futures endpoints
5//! including market data, trading, account management, and WebSocket streams.
6//!
7//! ## Features
8//!
9//! - **Async/Await Support**: Built on tokio for high-performance async operations
10//! - **Type Safety**: Strong typing with serde serialization/deserialization
11//! - **Market Data**: Access to real-time market data, depth, trades, and klines
12//! - **Trading**: Full trading functionality including orders, positions, and account management
13//! - **WebSocket Streams**: Real-time data streams for market data and user events
14//! - **Error Handling**: Comprehensive error types with detailed error information
15//! - **Testnet Support**: Built-in support for Binance testnet environment
16//!
17//! ## Quick Start
18//!
19//! ### Public Market Data
20//!
21//! ```rust,no_run
22//! use binance_futures_rs::BinanceClient;
23//!
24//! #[tokio::main]
25//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
26//!     let client = BinanceClient::new();
27//!     
28//!     // Get server time
29//!     let time = client.market().server_time().await?;
30//!     println!("Server time: {}", time.server_time);
31//!     
32//!     // Get 24hr ticker
33//!     let ticker = client.market().ticker_24hr("BTCUSDT").await?;
34//!     println!("BTC price: {}", ticker.last_price);
35//!     
36//!     Ok(())
37//! }
38//! ```
39//!
40//! ### Authenticated Trading
41//!
42//! ```rust,no_run
43//! use binance_futures_rs::{BinanceClient, Credentials, OrderSide, OrderType, TimeInForce};
44//!
45//! #[tokio::main]
46//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
47//!     let credentials = Credentials::new(
48//!         "your_api_key".to_string(),
49//!         "your_secret_key".to_string(),
50//!     );
51//!     let client = BinanceClient::new_with_credentials(credentials);
52//!     
53//!     // Place a limit order
54//!     let order = client.trading().new_order(
55//!         "BTCUSDT",
56//!         OrderSide::Buy,
57//!         OrderType::Limit,
58//!         Some(TimeInForce::Gtc),
59//!         Some("0.001".to_string()),
60//!         Some("50000.0".to_string()),
61//!         None, None, None, None,
62//!     ).await?;
63//!     
64//!     println!("Order placed: {}", order.order_id);
65//!     Ok(())
66//! }
67//! ```
68//!
69//! ### WebSocket Streams
70//!
71//! ```rust,no_run
72//! use binance_futures_rs::websocket::{StreamBuilder, WebSocketClient, WebSocketMessage};
73//! use futures_util::StreamExt;
74//!
75//! #[tokio::main]
76//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
77//!     let mut ws = StreamBuilder::new()
78//!         .depth("BTCUSDT", Some(5))
79//!         .trade("ETHUSDT")
80//!         .connect()
81//!         .await?;
82//!     
83//!     while let Some(msg) = ws.next().await {
84//!         // Handle WebSocket messages
85//!         if let Ok(text) = msg {
86//!             match WebSocketClient::parse_message(&text.to_string()) {
87//!                 Ok(WebSocketMessage::DepthUpdate(depth)) => {
88//!                     println!("Depth update for {}", depth.symbol);
89//!                 }
90//!                 Ok(WebSocketMessage::Trade(trade)) => {
91//!                     println!("Trade: {} @ {}", trade.quantity, trade.price);
92//!                 }
93//!                 _ => {}
94//!             }
95//!         }
96//!     }
97//!     Ok(())
98//! }
99//! ```
100//! ## Quick Start
101//!
102//! ```rust,no_run
103//! use binance_futures_rs::{BinanceClient, KlineInterval};
104//!
105//! #[tokio::main]
106//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
107//!     // Create client for public endpoints (no authentication required)
108//!     let client = BinanceClient::new();
109//!     
110//!     // Get current Bitcoin price
111//!     let price = client.market().price_ticker(Some("BTCUSDT")).await?;
112//!     println!("BTC Price: {}", price[0].price);
113//!     
114//!     // For authenticated endpoints, provide credentials
115//!     let credentials = Credentials::new(
116//!         "your_api_key".to_string(),
117//!         "your_secret_key".to_string(),
118//!     );
119//!     let auth_client = BinanceClient::new_with_credentials(credentials);
120//!     
121//!     // Get account information
122//!     let account = auth_client.account().account_info().await?;
123//!     println!("Account balance: {}", account.total_wallet_balance);
124//!     
125//!     Ok(())
126//! }
127//! ```
128
129pub mod api;
130pub mod client;
131pub mod error;
132pub mod types;
133pub mod utils;
134pub mod websocket;
135
136/// Main client for interacting with Binance Futures API
137pub struct BinanceClient {
138    http_client: HttpClient,
139}
140
141pub use api::{AccountApi, MarketApi, TradingApi};
142pub use client::{Credentials, HttpClient};
143pub use error::{BinanceError, Result};
144pub use types::*;
145pub use websocket::{StreamBuilder, WebSocketClient, WebSocketMessage, UserDataStream, UserDataStreamConfig};
146
147
148impl BinanceClient {
149    /// Create a new client for public endpoints (no authentication)
150    pub fn new() -> Self {
151        Self {
152            http_client: HttpClient::new(),
153        }
154    }
155
156    /// Create a new client with credentials for authenticated endpoints
157    pub fn new_with_credentials(credentials: Credentials) -> Self {
158        Self {
159            http_client: HttpClient::new_with_credentials(credentials),
160        }
161    }
162
163    /// Create a new testnet client
164    pub fn testnet() -> Self {
165        Self {
166            http_client: HttpClient::testnet(),
167        }
168    }
169
170    /// Create a new testnet client with credentials
171    pub fn testnet_with_credentials(credentials: Credentials) -> Self {
172        Self {
173            http_client: HttpClient::testnet_with_credentials(credentials),
174        }
175    }
176
177    /// Get market data API
178    pub fn market(&self) -> MarketApi {
179        MarketApi::new(self.http_client.clone())
180    }
181
182    /// Get trading API client
183    pub fn trading(&self) -> TradingApi {
184        TradingApi::new(self.http_client.clone())
185    }
186
187    /// Get account API client
188    pub fn account(&self) -> AccountApi {
189        AccountApi::new(self.http_client.clone())
190    }
191
192
193    /// Get HTTP client (for advanced usage)
194    pub fn http_client(&self) -> &HttpClient {
195        &self.http_client
196    }
197}
198
199impl Default for BinanceClient {
200    fn default() -> Self {
201        Self::new()
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn test_client_creation() {
211        let client = BinanceClient::new();
212        let _market_api = client.market();
213        assert!(true);
214    }
215
216    #[test]
217    fn test_client_with_credentials() {
218        let credentials = Credentials::new("test_key".to_string(), "test_secret".to_string());
219        let client = BinanceClient::new_with_credentials(credentials);
220        let _trading_api = client.trading();
221        let _account_api = client.account();
222        assert!(true);
223    }
224
225    #[test]
226    fn test_testnet_client() {
227        let client = BinanceClient::testnet();
228        let _market_api = client.market();
229        assert!(true);
230    }
231
232}