#finance-trading #real-time #deribit #finance

deribit-websocket

WebSocket client for Deribit trading platform real-time data

2 releases

Uses new Rust 2024

0.1.1 Aug 19, 2025
0.1.0 Jul 21, 2025

#172 in WebSocket

MIT license

385KB
2K SLoC

deribit-websocket

Dual License Crates.io Downloads Stars Issues PRs Build Status Coverage Dependencies Documentation Wiki

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 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

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 handling
  • callback_example.rs - Advanced callback system with error handling
  • advanced_subscriptions.rs - Chart data and position change subscriptions
  • mass_quote_basic.rs - Basic mass quoting with MMP group setup
  • mass_quote_advanced.rs - Advanced mass quoting with multiple MMP groups and monitoring
  • mass_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:

  1. Fork the repository.
  2. Create a new branch for your feature or bug fix.
  3. Make your changes and ensure that the project still builds and all tests pass.
  4. Commit your changes and push your branch to your forked repository.
  5. 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

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