Expand description
Β§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 with typed responses
- π Trading Operations - Full order lifecycle: buy, sell, cancel, edit orders
- πΌ Account Management - Position queries, account summaries, order history
- π Session Management - Heartbeat control, client identification, cancel-on-disconnect
- π‘οΈ 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>> {
// Install the rustls crypto provider that matches the active TLS feature.
// See the crate-level "TLS backends" section or `Cargo features` in the
// README for the available backends.
deribit_websocket::install_default_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:
Β§Core Examples
basic_client.rs- Basic connection, subscription, and message handlingcallback_example.rs- Advanced callback system with error handlingadvanced_subscriptions.rs- Chart data and position change subscriptions
Β§Trading & Account Management (v0.2.0)
trading_operations.rs- Buy, sell, cancel, edit ordersaccount_operations.rs- Get positions, account summary, order historyposition_management.rs- Close positions, move positions between subaccounts
Β§Session Management (v0.2.0)
session_management.rs- Hello, heartbeat, typed responses (AuthResponse, HelloResponse, TestResponse)cancel_on_disconnect.rs- Enable/disable/get cancel-on-disconnect statusunsubscribe_all.rs- Public and private unsubscribe_all operations
Β§Market Data Subscriptions
new_channels_subscription.rs- Grouped order book, incremental ticker, trades by kindperpetual_subscription.rs- Perpetual funding rate subscriptionsquote_subscription.rs- Quote data subscriptionsprice_index_subscription.rs- Price index subscriptions
Β§Mass Quoting
mass_quote_basic.rs- Basic mass quoting with MMP group setupmass_quote_advanced.rs- Advanced mass quoting with multiple MMP groupsmass_quote_options.rs- Options-specific mass quoting with delta management
Β§Timeouts
Two deadlines bound the most common sources of indefinite hangs in a
network client. Both live on WebSocketConfig and can be set via
builder methods or the corresponding environment variables:
connection_timeout(default 10s, envDERIBIT_CONNECTION_TIMEOUT) β upper bound on the WebSocket handshake (TCP + TLS + HTTP upgrade). A peer that accepts the TCP connection but never completes the upgrade makesDeribitWebSocketClient::connect/Dispatcher::connectfail withWebSocketError::Timeoutinstead of hanging.request_timeout(default 30s, envDERIBIT_REQUEST_TIMEOUT) β upper bound on eachsend_requestcall, covering enqueue, write, and response wait. On the deadline the dispatcher evicts the now-orphaned waiter so the id-map stays small under repeated timeouts.
Planned follow-ups: read_idle_timeout (maximum gap between frames)
and granular per-operation overrides.
Β§Backpressure
The client and dispatcher communicate over two bounded
tokio::sync::mpsc channels, both using Strategy A (await-send) β
the producer blocks on a full channel, so frames are not dropped due
to backpressure. Frames can still be discarded if the notification
receiver has already been closed (for example during shutdown or
disconnect).
notification_channel_capacity(default 1024) β notifications from the dispatcher to the consumer. When full, the dispatcher stops polling the WebSocket stream and the TCP recv buffer fills, which makes the Deribit server apply flow control. Every full-channel event emits atracing::warn!so slow consumers are visible in logs.dispatcher_command_capacityβ outbound commands from the client to the dispatcher (request sends, cancel-request on timeout, shutdown). When full, the caller blocks until the dispatcher drains a slot;request_timeoutonsend_requeststill applies, so the caller surfacesWebSocketError::Timeoutif the deadline elapses while waiting on the channel.
Strategy A was chosen over drop-oldest / drop-newest variants because the notification stream carries private trading events (order updates, trade reports) where silent loss is unacceptable.
Β§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
Β§TLS backends
deribit-websocket exposes three mutually-exclusive TLS backends as
Cargo features, with a compile-time mutex (see the tls module)
that rejects any other combination:
| Feature | Default | Behaviour |
|---|---|---|
rustls-aws-lc | β | rustls with the aws-lc-rs crypto provider + OS root store |
rustls-ring | rustls with the ring crypto provider + OS root store | |
native-tls | OS-native TLS stack (SChannel / SecureTransport / OpenSSL) |
Selecting a non-default backend:
# Cargo.toml
[dependencies]
deribit-websocket = { version = "0.2", default-features = false, features = ["rustls-ring"] }or, from the command line:
cargo add deribit-websocket --no-default-features --features native-tlsApplications must call install_default_crypto_provider once at
startup β it picks the right provider for the active feature and is
a no-op under native-tls.
Because both rustls-* backends use the OS-native root store via
rustls-native-certs, minimal container images (Alpine, distroless)
must have ca-certificates (or equivalent) installed so the trust
store is populated.
Re-exportsΒ§
pub use tls::CryptoProviderError;pub use tls::install_default_crypto_provider;
ModulesΒ§
- callback
- Callback system for message handling
- client
- WebSocket client implementation for Deribit.
- config
- Configuration for WebSocket client
- connection
- Connection module for WebSocket client
- constants
- Constants for WebSocket client
- error
- Error handling module for WebSocket client
- message
- Message handling module for WebSocket client
- model
- Model definitions for WebSocket client
- prelude
- Prelude module with commonly used types Curated glob-importable re-exports for common use cases.
- session
- Session management module for WebSocket client
- subscriptions
- WebSocket subscription management
- tls
- TLS backend selection and
rustlscrypto-provider installation. - utils
- Utility functions and helpers Shared helpers for crate consumers.