Skip to main content

deribit_websocket/
lib.rs

1//! # Deribit WebSocket Client
2//!
3//! A high-performance, production-ready WebSocket client for the Deribit cryptocurrency derivatives exchange.
4//! This crate provides comprehensive real-time market data streaming, trading operations, and account management
5//! through Deribit's WebSocket API v2.
6//!
7//! ## Features
8//!
9//! - ๐Ÿ”Œ **WebSocket Connection Management** - Robust connection handling with automatic reconnection and heartbeat
10//! - ๐Ÿ“ก **JSON-RPC Protocol** - Complete JSON-RPC 2.0 implementation for Deribit API
11//! - ๐Ÿ“Š **Real-time Market Data** - Live ticker, order book, trades, and chart data streaming
12//! - ๐Ÿ“ˆ **Advanced Subscriptions** - Chart data aggregation and user position change notifications
13//! - ๐Ÿ’ฐ **Mass Quote System** - High-performance mass quoting with MMP (Market Maker Protection) groups
14//! - ๐Ÿ” **Authentication** - Secure API key and signature-based authentication with typed responses
15//! - ๐Ÿ“ **Trading Operations** - Full order lifecycle: buy, sell, cancel, edit orders
16//! - ๐Ÿ’ผ **Account Management** - Position queries, account summaries, order history
17//! - ๐Ÿ”„ **Session Management** - Heartbeat control, client identification, cancel-on-disconnect
18//! - ๐Ÿ›ก๏ธ **Error Handling** - Comprehensive error types with detailed recovery mechanisms
19//! - โšก **Async/Await** - Full async support with tokio runtime for high concurrency
20//! - ๐Ÿ”„ **Callback System** - Flexible message processing with primary and error callbacks
21//! - ๐Ÿ“‹ **Subscription Management** - Intelligent subscription tracking and channel management
22//! - ๐Ÿงช **Testing Support** - Complete test coverage with working examples
23//!
24//! ## Supported Subscription Channels
25//!
26//! ### Market Data Channels
27//! - `ticker.{instrument}` - Real-time ticker updates
28//! - `book.{instrument}.{group}` - Order book snapshots and updates
29//! - `trades.{instrument}` - Live trade executions
30//! - `chart.trades.{instrument}.{resolution}` - Aggregated chart data for technical analysis
31//!
32//! ### User Data Channels (Requires Authentication)
33//! - `user.orders` - Order status updates and fills
34//! - `user.trades` - User trade executions
35//! - `user.changes.{instrument}.{interval}` - Position and portfolio changes
36//!
37//! ## Protocol Support
38//!
39//! | Feature | Status | Description |
40//! |---------|--------|-------------|
41//! | JSON-RPC over WebSocket | โœ… Full Support | Complete JSON-RPC 2.0 implementation |
42//! | Market Data Subscriptions | โœ… Full Support | All public channels supported |
43//! | User Data Subscriptions | โœ… Full Support | Private channels with authentication |
44//! | Chart Data Streaming | โœ… Full Support | Real-time OHLCV data aggregation |
45//! | Authentication | โœ… API Key + Signature | Secure credential-based auth |
46//! | Connection Management | โœ… Auto-reconnect | Robust connection handling |
47//! | Error Recovery | โœ… Comprehensive | Detailed error types and handling |
48//!
49//! ## Quick Start
50//!
51//! ```rust,no_run
52//! use deribit_websocket::prelude::*;
53//!
54//! #[tokio::main]
55//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
56//!     // Initialize crypto provider for TLS connections
57//!     rustls::crypto::aws_lc_rs::default_provider()
58//!         .install_default()
59//!         .map_err(|_| "Failed to install crypto provider")?;
60//!
61//!     // Create client for testnet
62//!     let config = WebSocketConfig::default();
63//!     let mut client = DeribitWebSocketClient::new(&config)?;
64//!
65//!     // Set up message processing
66//!     client.set_message_handler(
67//!         |message| {
68//!             tracing::info!("Received: {}", message);
69//!             Ok(())
70//!         },
71//!         |message, error| {
72//!             tracing::error!("Error processing {}: {}", message, error);
73//!         }
74//!     );
75//!
76//!     // Connect and subscribe
77//!     client.connect().await?;
78//!     client.subscribe(vec!["ticker.BTC-PERPETUAL".to_string()]).await?;
79//!
80//!     // Start processing messages
81//!     client.start_message_processing_loop().await?;
82//!     Ok(())
83//! }
84//! ```
85//!
86//! ## Advanced Usage
87//!
88//! The client supports advanced subscription patterns for professional trading applications:
89//!
90//! ### Chart Data Streaming
91//! ```rust,no_run
92//! # use deribit_websocket::prelude::*;
93//! # #[tokio::main]
94//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
95//! # let config = WebSocketConfig::default();
96//! # let client = DeribitWebSocketClient::new(&config)?;
97//! // Subscribe to 1-minute chart data for BTC perpetual
98//! client.subscribe(vec!["chart.trades.BTC-PERPETUAL.1".to_string()]).await?;
99//! # Ok(())
100//! # }
101//! ```
102//!
103//! ### Position Change Monitoring
104//! ```rust,no_run
105//! # use deribit_websocket::prelude::*;
106//! # #[tokio::main]
107//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
108//! # let config = WebSocketConfig::default();
109//! # let client = DeribitWebSocketClient::new(&config)?;
110//! // Monitor real-time position changes (requires authentication)
111//! client.authenticate("client_id", "client_secret").await?;
112//! client.subscribe(vec!["user.changes.BTC-PERPETUAL.raw".to_string()]).await?;
113//! # Ok(())
114//! # }
115//! ```
116//!
117//! ### Mass Quote System
118//! ```rust,no_run
119//! # use deribit_websocket::prelude::*;
120//! # #[tokio::main]
121//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
122//! # let config = WebSocketConfig::default();
123//! # let mut client = DeribitWebSocketClient::new(&config)?;
124//! # client.connect().await?;
125//! # client.authenticate("client_id", "client_secret").await?;
126//! // Set up MMP group for mass quoting
127//! let mmp_config = MmpGroupConfig::new(
128//!     "btc_market_making".to_string(),
129//!     10.0,  // quantity_limit
130//!     5.0,   // delta_limit  
131//!     1000,  // interval (ms)
132//!     5000,  // frozen_time (ms)
133//! )?;
134//! client.set_mmp_config(mmp_config).await?;
135//!
136//! // Create and place mass quotes
137//! let quotes = vec![
138//!     Quote::buy("BTC-PERPETUAL".to_string(), 0.1, 45000.0),
139//!     Quote::sell("BTC-PERPETUAL".to_string(), 0.1, 55000.0),
140//! ];
141//! let request = MassQuoteRequest::new("btc_market_making".to_string(), quotes);
142//! let response = client.mass_quote(request).await?;
143//! # Ok(())
144//! # }
145//! ```
146//!
147//! ## Examples
148//!
149//! The crate includes comprehensive examples demonstrating:
150//!
151//! ### Core Examples
152//! - **`basic_client.rs`** - Basic connection, subscription, and message handling
153//! - **`callback_example.rs`** - Advanced callback system with error handling
154//! - **`advanced_subscriptions.rs`** - Chart data and position change subscriptions
155//!
156//! ### Trading & Account Management (v0.2.0)
157//! - **`trading_operations.rs`** - Buy, sell, cancel, edit orders
158//! - **`account_operations.rs`** - Get positions, account summary, order history
159//! - **`position_management.rs`** - Close positions, move positions between subaccounts
160//!
161//! ### Session Management (v0.2.0)
162//! - **`session_management.rs`** - Hello, heartbeat, typed responses (AuthResponse, HelloResponse, TestResponse)
163//! - **`cancel_on_disconnect.rs`** - Enable/disable/get cancel-on-disconnect status
164//! - **`unsubscribe_all.rs`** - Public and private unsubscribe_all operations
165//!
166//! ### Market Data Subscriptions
167//! - **`new_channels_subscription.rs`** - Grouped order book, incremental ticker, trades by kind
168//! - **`perpetual_subscription.rs`** - Perpetual funding rate subscriptions
169//! - **`quote_subscription.rs`** - Quote data subscriptions
170//! - **`price_index_subscription.rs`** - Price index subscriptions
171//!
172//! ### Mass Quoting
173//! - **`mass_quote_basic.rs`** - Basic mass quoting with MMP group setup
174//! - **`mass_quote_advanced.rs`** - Advanced mass quoting with multiple MMP groups
175//! - **`mass_quote_options.rs`** - Options-specific mass quoting with delta management
176//!
177//! ## Architecture
178//!
179//! The client is built with a modular architecture:
180//! - **Connection Layer** - Low-level WebSocket connection management
181//! - **Session Layer** - Protocol-aware session handling with authentication
182//! - **Message Layer** - JSON-RPC request/response and notification handling
183//! - **Subscription Layer** - Channel management and subscription tracking
184//! - **Callback Layer** - Flexible message processing with error recovery
185
186#![warn(missing_docs)]
187#![deny(unsafe_code)]
188
189pub mod callback;
190pub mod client;
191pub mod config;
192pub mod connection;
193pub mod constants;
194pub mod error;
195pub mod message;
196pub mod model;
197/// Prelude module with commonly used types
198pub mod prelude;
199pub mod session;
200pub mod subscriptions;
201/// Utility functions and helpers
202pub mod utils;