2 releases
Uses new Rust 2024
| 0.1.1 | Aug 19, 2025 |
|---|---|
| 0.1.0 | Jul 21, 2025 |
#172 in WebSocket
385KB
2K
SLoC
Deribit WebSocket Client
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.
Features
- ๐ 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
Supported Subscription Channels
Market Data Channels
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 Data Channels (Requires Authentication)
user.orders- Order status updates and fillsuser.trades- User trade executionsuser.changes.{instrument}.{interval}- Position and portfolio changes
Protocol Support
| 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 |
Quick Start
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(())
}
Advanced Usage
The client supports advanced subscription patterns for professional trading applications:
Chart Data Streaming
// Subscribe to 1-minute chart data for BTC perpetual
client.subscribe(vec!["chart.trades.BTC-PERPETUAL.1".to_string()]).await?;
Position Change Monitoring
// 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?;
Mass Quote System
// 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?;
Examples
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
Architecture
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
Contribution and Contact
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!
โ๏ธ License
Licensed under MIT license
Disclaimer
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.
Dependencies
~19โ33MB
~536K SLoC