Module binance_websocket_trading

Source
Expand description

Binance WebSocket trading client Binance WebSocket Trading Implementation

This module provides a high-performance WebSocket trading client for Binance exchange with robust connection management, automatic reconnection, and comprehensive health monitoring.

§Features

  • Dual-level ping/pong mechanism: Both WebSocket protocol-level and JSON API-level
  • Automatic reconnection: Configurable backoff strategy with exponential delays
  • Connection health monitoring: Real-time metrics and health status
  • Ed25519 authentication: Support for both raw and DER-encoded private keys
  • Zero-copy message processing: Optimized for low-latency trading

§Connection Management

The client maintains connection health through:

  • WebSocket ping frames sent every 30 seconds
  • JSON ping requests for API-level health checks
  • Automatic reconnection on connection loss
  • Configurable pong timeout (default: 10 seconds)

§Reconnection Behavior

When connection is lost, the client will:

  1. Detect timeout through missing pong responses
  2. Kill the existing socket connection
  3. Wait for backoff period (starts at 1s, doubles each attempt)
  4. Attempt to reconnect and re-authenticate
  5. Reset backoff on successful connection

Configuration:

  • Initial backoff: 1 second
  • Max backoff: 60 seconds
  • Max attempts: 10 (configurable via MAX_RECONNECTION_ATTEMPTS)

§Usage Example

use rusty_common::auth::exchanges::binance::BinanceAuth;
use rusty_ems::exchanges::binance_websocket_trading::BinanceWebSocketTrader;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<()> {
    let auth = Arc::new(BinanceAuth::new_ed25519(
        "api_key".into(),
        "private_key_base64".into()
    )?);

    let trader = BinanceWebSocketTrader::new(auth);
    let (report_tx, report_rx) = flume::bounded(100);

    // Connect and authenticate
    trader.connect(report_tx).await?;

    // Check connection health
    let health = trader.get_connection_health();
    println!("Connection healthy: {}", health.is_healthy);

    // Send JSON ping
    trader.send_ping().await?;

    Ok(())
}

Structs§

BinanceWebSocketTrader
High-performance WebSocket-only trading client for Binance
ConnectionHealth
Detailed connection health information
ConnectionMetrics
Connection metrics for observability Cache-line aligned to prevent false sharing in multi-threaded scenarios
ModifyOrderParams
Parameters for modifying an order

Enums§

ConnectionState
Connection state for proper state machine tracking