Crate binance_futures_rs

Crate binance_futures_rs 

Source
Expand description

§Binance Futures API Rust Client

A comprehensive Rust client library for the Binance Futures API. This library provides async/await support for all Binance Futures endpoints including market data, trading, account management, and WebSocket streams.

§Features

  • Async/Await Support: Built on tokio for high-performance async operations
  • Type Safety: Strong typing with serde serialization/deserialization
  • Market Data: Access to real-time market data, depth, trades, and klines
  • Trading: Full trading functionality including orders, positions, and account management
  • WebSocket Streams: Real-time data streams for market data and user events
  • Error Handling: Comprehensive error types with detailed error information
  • Testnet Support: Built-in support for Binance testnet environment

§Quick Start

§Public Market Data

use binance_futures_rs::BinanceClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = BinanceClient::new();
     
    // Get server time
    let time = client.market().server_time().await?;
    println!("Server time: {}", time.server_time);
     
    // Get 24hr ticker
    let ticker = client.market().ticker_24hr("BTCUSDT").await?;
    println!("BTC price: {}", ticker.last_price);
     
    Ok(())
}

§Authenticated Trading

use binance_futures_rs::{BinanceClient, Credentials, OrderSide, OrderType, TimeInForce};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let credentials = Credentials::new(
        "your_api_key".to_string(),
        "your_secret_key".to_string(),
    );
    let client = BinanceClient::new_with_credentials(credentials);
     
    // Place a limit order
    let order = client.trading().new_order(
        "BTCUSDT",
        OrderSide::Buy,
        OrderType::Limit,
        Some(TimeInForce::Gtc),
        Some("0.001".to_string()),
        Some("50000.0".to_string()),
        None, None, None, None,
    ).await?;
     
    println!("Order placed: {}", order.order_id);
    Ok(())
}

§WebSocket Streams

use binance_futures_rs::websocket::{StreamBuilder, WebSocketClient, WebSocketMessage};
use futures_util::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut ws = StreamBuilder::new()
        .depth("BTCUSDT", Some(5))
        .trade("ETHUSDT")
        .connect()
        .await?;
     
    while let Some(msg) = ws.next().await {
        // Handle WebSocket messages
        if let Ok(text) = msg {
            match WebSocketClient::parse_message(&text.to_string()) {
                Ok(WebSocketMessage::DepthUpdate(depth)) => {
                    println!("Depth update for {}", depth.symbol);
                }
                Ok(WebSocketMessage::Trade(trade)) => {
                    println!("Trade: {} @ {}", trade.quantity, trade.price);
                }
                _ => {}
            }
        }
    }
    Ok(())
}

§Quick Start

use binance_futures_rs::{BinanceClient, KlineInterval};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create client for public endpoints (no authentication required)
    let client = BinanceClient::new();
     
    // Get current Bitcoin price
    let price = client.market().price_ticker(Some("BTCUSDT")).await?;
    println!("BTC Price: {}", price[0].price);
     
    // For authenticated endpoints, provide credentials
    let credentials = Credentials::new(
        "your_api_key".to_string(),
        "your_secret_key".to_string(),
    );
    let auth_client = BinanceClient::new_with_credentials(credentials);
     
    // Get account information
    let account = auth_client.account().account_info().await?;
    println!("Account balance: {}", account.total_wallet_balance);
     
    Ok(())
}

Re-exports§

pub use api::AccountApi;
pub use api::MarketApi;
pub use api::TradingApi;
pub use client::Credentials;
pub use client::HttpClient;
pub use error::BinanceError;
pub use error::Result;
pub use websocket::StreamBuilder;
pub use websocket::WebSocketClient;
pub use websocket::WebSocketMessage;
pub use websocket::UserDataStream;
pub use websocket::UserDataStreamConfig;
pub use types::*;

Modules§

api
client
error
types
utils
websocket
WebSocket module for real-time data streams

Structs§

BinanceClient
Main client for interacting with Binance Futures API