deribit-websocket 0.3.0

WebSocket client for Deribit trading platform real-time data
Documentation
//! Basic WebSocket client example for Deribit
//!
//! This example demonstrates how to:
//! - Connect to Deribit WebSocket API
//! - Subscribe to market data channels
//! - Handle incoming messages
//! - Gracefully disconnect

use deribit_websocket::config::WebSocketConfig;
use deribit_websocket::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Install the rustls crypto provider that matches the active TLS feature.
    deribit_websocket::install_default_crypto_provider()?;

    // Initialize logging
    unsafe {
        std::env::set_var("DERIBIT_LOG_LEVEL", "DEBUG");
    }
    setup_logger();

    tracing::info!("๐Ÿš€ Starting Deribit WebSocket Client Example");

    // Create client configuration for testnet
    let config = WebSocketConfig::default()
        .with_heartbeat_interval(std::time::Duration::from_secs(30))
        .with_max_reconnect_attempts(3);

    // Create the WebSocket client
    let client = DeribitWebSocketClient::new(&config)?;
    tracing::info!("โœ… Client created successfully");

    // Connect to the server
    tracing::info!("๐Ÿ”Œ Connecting to Deribit WebSocket...");
    client.connect().await?;
    tracing::info!("โœ… Connected to Deribit WebSocket");

    // Test the connection
    tracing::info!("๐Ÿงช Testing connection...");
    match client.test_connection().await {
        Ok(response) => tracing::info!("โœ… Connection test successful: {:?}", response),
        Err(e) => tracing::error!("โŒ Connection test failed: {}", e),
    }

    // Get server time
    tracing::info!("โฐ Getting server time...");
    match client.get_time().await {
        Ok(response) => tracing::info!("โœ… Server time: {:?}", response),
        Err(e) => tracing::error!("โŒ Failed to get server time: {}", e),
    }

    // Subscribe to market data channels
    tracing::info!("๐Ÿ“ก Subscribing to BTC-PERPETUAL ticker...");
    let channels = vec![
        "ticker.BTC-PERPETUAL".to_string(),
        "book.BTC-PERPETUAL.100ms".to_string(),
    ];

    match client.subscribe(channels).await {
        Ok(response) => {
            tracing::info!("โœ… Subscription successful!");
            tracing::info!("โœ… Subscription successful: {:?}", response)
        }
        Err(e) => {
            tracing::error!("โŒ Subscription failed: {}", e);
        }
    }

    // Display active subscriptions
    let subscriptions = client.get_subscriptions().await;
    tracing::info!("๐Ÿ“‹ Active subscriptions: {:?}", subscriptions);

    // Simulate receiving messages for a short time
    tracing::info!("โณ Processing messages for 10 seconds...");
    let start_time = std::time::Instant::now();
    let mut message_count = 0;

    while start_time.elapsed() < std::time::Duration::from_secs(5) {
        match tokio::time::timeout(
            std::time::Duration::from_millis(500),
            client.receive_message(),
        )
        .await
        {
            Ok(Ok(message)) => {
                message_count += 1;
                tracing::info!("๐Ÿ“จ Message #{}: {}", message_count, message);
            }
            Ok(Err(e)) => {
                tracing::error!("โŒ Error receiving message: {}", e);
                break;
            }
            Err(_) => {
                tracing::debug!("โณ No message received (timeout)");
            }
        }
    }

    tracing::info!("๐Ÿ“Š Total messages received: {}", message_count);

    // Unsubscribe from channels
    tracing::info!("๐Ÿ“ก Unsubscribing from channels...");
    let channels = vec![
        "ticker.BTC-PERPETUAL".to_string(),
        "book.BTC-PERPETUAL.100ms".to_string(),
    ];

    match client.unsubscribe(channels).await {
        Ok(response) => tracing::info!("โœ… Unsubscription successful: {:?}", response),
        Err(e) => tracing::error!("โŒ Unsubscription failed: {}", e),
    }

    // Disconnect from the server
    tracing::info!("๐Ÿ‘‹ Disconnecting...");
    client.disconnect().await?;
    tracing::info!("โœ… Disconnected successfully");

    tracing::info!("๐ŸŽ‰ Example completed successfully!");
    Ok(())
}