use deribit_websocket::config::WebSocketConfig;
use deribit_websocket::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
deribit_websocket::install_default_crypto_provider()?;
unsafe {
std::env::set_var("DERIBIT_LOG_LEVEL", "DEBUG");
}
setup_logger();
tracing::info!("๐ Starting Deribit WebSocket Client Example");
let config = WebSocketConfig::default()
.with_heartbeat_interval(std::time::Duration::from_secs(30))
.with_max_reconnect_attempts(3);
let client = DeribitWebSocketClient::new(&config)?;
tracing::info!("โ
Client created successfully");
tracing::info!("๐ Connecting to Deribit WebSocket...");
client.connect().await?;
tracing::info!("โ
Connected to Deribit WebSocket");
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),
}
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),
}
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);
}
}
let subscriptions = client.get_subscriptions().await;
tracing::info!("๐ Active subscriptions: {:?}", subscriptions);
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);
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),
}
tracing::info!("๐ Disconnecting...");
client.disconnect().await?;
tracing::info!("โ
Disconnected successfully");
tracing::info!("๐ Example completed successfully!");
Ok(())
}