A high-performance, production-ready WebSocket client for the Deribit cryptocurrency derivatives exchange. This crate provides comprehensive real-time market data streaming, trading operations, and account management through Deribit's WebSocket API v2.
- π WebSocket Connection Management - Robust connection handling with automatic reconnection and heartbeat
- π‘ JSON-RPC Protocol - Complete JSON-RPC 2.0 implementation for Deribit API
- π Real-time Market Data - Live ticker, order book, trades, and chart data streaming
- π Advanced Subscriptions - Chart data aggregation and user position change notifications
- π° Mass Quote System - High-performance mass quoting with MMP (Market Maker Protection) groups
- π Authentication - Secure API key and signature-based authentication
- π‘οΈ Error Handling - Comprehensive error types with detailed recovery mechanisms
- β‘ Async/Await - Full async support with tokio runtime for high concurrency
- π Callback System - Flexible message processing with primary and error callbacks
- π Subscription Management - Intelligent subscription tracking and channel management
- π§ͺ Testing Support - Complete test coverage with working examples
ticker.{instrument}- Real-time ticker updatesbook.{instrument}.{group}- Order book snapshots and updatestrades.{instrument}- Live trade executionschart.trades.{instrument}.{resolution}- Aggregated chart data for technical analysis
user.orders- Order status updates and fillsuser.trades- User trade executionsuser.changes.{instrument}.{interval}- Position and portfolio changes
| Feature | Status | Description |
|---|---|---|
| JSON-RPC over WebSocket | β Full Support | Complete JSON-RPC 2.0 implementation |
| Market Data Subscriptions | β Full Support | All public channels supported |
| User Data Subscriptions | β Full Support | Private channels with authentication |
| Chart Data Streaming | β Full Support | Real-time OHLCV data aggregation |
| Authentication | β API Key + Signature | Secure credential-based auth |
| Connection Management | β Auto-reconnect | Robust connection handling |
| Error Recovery | β Comprehensive | Detailed error types and handling |
use deribit_websocket::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize crypto provider for TLS connections
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.map_err(|_| "Failed to install crypto provider")?;
// Create client for testnet
let config = WebSocketConfig::default();
let mut client = DeribitWebSocketClient::new(&config)?;
// Set up message processing
client.set_message_handler(
|message| {
tracing::info!("Received: {}", message);
Ok(())
},
|message, error| {
tracing::error!("Error processing {}: {}", message, error);
}
);
// Connect and subscribe
client.connect().await?;
client.subscribe(vec!["ticker.BTC-PERPETUAL".to_string()]).await?;
// Start processing messages
client.start_message_processing_loop().await?;
Ok(())
}The client supports advanced subscription patterns for professional trading applications:
// Subscribe to 1-minute chart data for BTC perpetual
client.subscribe(vec!["chart.trades.BTC-PERPETUAL.1".to_string()]).await?;// Monitor real-time position changes (requires authentication)
client.authenticate("client_id", "client_secret").await?;
client.subscribe(vec!["user.changes.BTC-PERPETUAL.raw".to_string()]).await?;// Set up MMP group for mass quoting
let mmp_config = MmpGroupConfig::new(
"btc_market_making".to_string(),
10.0, // quantity_limit
5.0, // delta_limit
1000, // interval (ms)
5000, // frozen_time (ms)
)?;
client.set_mmp_config(mmp_config).await?;
// Create and place mass quotes
let quotes = vec![
Quote::buy("BTC-PERPETUAL".to_string(), 0.1, 45000.0),
Quote::sell("BTC-PERPETUAL".to_string(), 0.1, 55000.0),
];
let request = MassQuoteRequest::new("btc_market_making".to_string(), quotes);
let response = client.mass_quote(request).await?;The crate includes comprehensive examples demonstrating:
basic_client.rs- Basic connection, subscription, and message handlingcallback_example.rs- Advanced callback system with error handlingadvanced_subscriptions.rs- Chart data and position change subscriptionsmass_quote_basic.rs- Basic mass quoting with MMP group setupmass_quote_advanced.rs- Advanced mass quoting with multiple MMP groups and monitoringmass_quote_options.rs- Options-specific mass quoting with delta management
The client is built with a modular architecture:
- Connection Layer - Low-level WebSocket connection management
- Session Layer - Protocol-aware session handling with authentication
- Message Layer - JSON-RPC request/response and notification handling
- Subscription Layer - Channel management and subscription tracking
- Callback Layer - Flexible message processing with error recovery
We welcome contributions to this project! If you would like to contribute, please follow these steps:
- Fork the repository.
- Create a new branch for your feature or bug fix.
- Make your changes and ensure that the project still builds and all tests pass.
- Commit your changes and push your branch to your forked repository.
- Submit a pull request to the main repository.
If you have any questions, issues, or would like to provide feedback, please feel free to contact the project maintainer:
Joaquin Bejar Garcia
- Email: jb@taunais.com
- GitHub: joaquinbejar
We appreciate your interest and look forward to your contributions!
Licensed under MIT license
This software is not officially associated with Deribit. Trading financial instruments carries risk, and this library is provided as-is without any guarantees. Always test thoroughly with a demo account before using in a live trading environment.
