Skip to main content

Crate deribit_websocket

Crate deribit_websocket 

Source
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 updates
  • book.{instrument}.{group} - Order book snapshots and updates
  • trades.{instrument} - Live trade executions
  • chart.trades.{instrument}.{resolution} - Aggregated chart data for technical analysis

Β§User Data Channels (Requires Authentication)

  • user.orders - Order status updates and fills
  • user.trades - User trade executions
  • user.changes.{instrument}.{interval} - Position and portfolio changes

Β§Protocol Support

FeatureStatusDescription
JSON-RPC over WebSocketβœ… Full SupportComplete JSON-RPC 2.0 implementation
Market Data Subscriptionsβœ… Full SupportAll public channels supported
User Data Subscriptionsβœ… Full SupportPrivate channels with authentication
Chart Data Streamingβœ… Full SupportReal-time OHLCV data aggregation
Authenticationβœ… API Key + SignatureSecure credential-based auth
Connection Managementβœ… Auto-reconnectRobust connection handling
Error Recoveryβœ… ComprehensiveDetailed 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 handling
  • callback_example.rs - Advanced callback system with error handling
  • advanced_subscriptions.rs - Chart data and position change subscriptions

Β§Trading & Account Management (v0.2.0)

  • trading_operations.rs - Buy, sell, cancel, edit orders
  • account_operations.rs - Get positions, account summary, order history
  • position_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 status
  • unsubscribe_all.rs - Public and private unsubscribe_all operations

Β§Market Data Subscriptions

  • new_channels_subscription.rs - Grouped order book, incremental ticker, trades by kind
  • perpetual_subscription.rs - Perpetual funding rate subscriptions
  • quote_subscription.rs - Quote data subscriptions
  • price_index_subscription.rs - Price index subscriptions

Β§Mass Quoting

  • mass_quote_basic.rs - Basic mass quoting with MMP group setup
  • mass_quote_advanced.rs - Advanced mass quoting with multiple MMP groups
  • mass_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, env DERIBIT_CONNECTION_TIMEOUT) β€” upper bound on the WebSocket handshake (TCP + TLS + HTTP upgrade). A peer that accepts the TCP connection but never completes the upgrade makes DeribitWebSocketClient::connect / Dispatcher::connect fail with WebSocketError::Timeout instead of hanging.
  • request_timeout (default 30s, env DERIBIT_REQUEST_TIMEOUT) β€” upper bound on each send_request call, 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 a tracing::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_timeout on send_request still applies, so the caller surfaces WebSocketError::Timeout if 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:

FeatureDefaultBehaviour
rustls-aws-lcβœ…rustls with the aws-lc-rs crypto provider + OS root store
rustls-ringrustls with the ring crypto provider + OS root store
native-tlsOS-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-tls

Applications 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 rustls crypto-provider installation.
utils
Utility functions and helpers Shared helpers for crate consumers.