Skip to main content

deribit_http/
lib.rs

1//! # Deribit HTTP Client (deribit_http)
2//!
3//! **Production-ready** asynchronous HTTP client for the Deribit API v2.
4//! Version **0.6.0** provides **~95% coverage** of all HTTP-compatible Deribit endpoints.
5//!
6//! Designed for server integrations, batch jobs, and tooling that prefer REST/HTTP over WebSocket.
7//! Built on `reqwest` and `tokio`, with full WASM/Cloudflare Workers support.
8//!
9//! ## Key features
10//! - **100+ endpoints** implemented across public and private APIs
11//! - **Pure async HTTP** with reqwest + tokio (native) or fetch (WASM)
12//! - **Cross-platform**: Native, WASM browsers, and Cloudflare Workers
13//! - **OAuth2 authentication** with automatic token renewal
14//! - **Token-bucket rate limiting** per endpoint category
15//! - **40+ strongly-typed models** with Serde serialization
16//! - **126 unit tests** ensuring reliability
17//!
18//! ## Installation
19//! Add to your `Cargo.toml`:
20//! ```toml
21//! [dependencies]
22//! deribit-http = "0.6"
23//! tokio = { version = "1", features = ["full"] }
24//! ```
25//!
26//! ## Quick start
27//! ```rust
28//! use deribit_http::DeribitHttpClient;
29//!
30//! #[tokio::main]
31//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
32//!     // true = testnet, false = mainnet
33//!     let client = DeribitHttpClient::new();
34//!
35//!     // Public calls (no authentication required)
36//!     let currencies = client.get_currencies().await?;
37//!     println!("Supports {} currencies", currencies.len());
38//!
39//!     // Example: ticker
40//!     let ticker = client.get_ticker("BTC-PERPETUAL").await?;
41//!     println!("Mark price: {}", ticker.mark_price);
42//!
43//!     Ok(())
44//! }
45//! ```
46//!
47//! ## Authentication and private endpoints
48//! - OAuth2 (Client Credentials): `DeribitHttpClient::authenticate_oauth2(client_id, client_secret)` returns an `AuthToken` and keeps it in the `AuthManager`.
49//! - Helpers: `is_authenticated()`, `get_auth_token()`.
50//! - Session management: `exchange_token(refresh_token, subject_id, scope)` and `fork_token(refresh_token, session_name, scope)`.
51//! - API Key: the `authenticate_api_key` method exists but is currently not implemented and will return an error.
52//!
53//! ## Configuration
54//! - Environment shortcut: `DeribitHttpClient::new()` for Testnet and `new(false)` for Production.
55//! - Custom configuration: `DeribitHttpClient::with_config(HttpConfig)` lets you set `base_url`, `timeout`, `user_agent`, `testnet`, and optional credentials.
56//! - Validation: configuration is validated on client creation.
57//!
58//! ## Project structure (modules)
59//! - `auth`: `AuthManager` (OAuth2, token management) and related types (e.g. `AuthRequest`).
60//! - `client`: `DeribitHttpClient`, public/private methods, auth helpers, `exchange_token` and `fork_token`.
61//! - `config`: `HttpConfig` and environment helpers (testnet/production) and headers/base_url.
62//! - `connection` and `session`: infrastructure support types (shared across the ecosystem).
63//! - `endpoints`: HTTP implementation of public and private methods (see coverage below).
64//! - `error`: `HttpError` variants such as `NetworkError`, `RequestFailed`, `InvalidResponse`, `AuthenticationFailed`, `ConfigError`.
65//! - `message` and `model`: HTTP types (`ApiResponse`, `ApiError`, `AuthToken`, etc.).
66//! - `rate_limit`: `RateLimiter` and `categorize_endpoint` with per-category limits.
67//! - `constants`: base URLs (production/testnet), endpoint routes, and common headers.
68//!
69//! ## Public endpoints (30+)
70//!
71//! | Category | Endpoints |
72//! |----------|-----------|
73//! | **System** | `get_server_time()`, `test_connection()`, `get_status()` |
74//! | **Currencies** | `get_currencies()`, `get_apr_history()` |
75//! | **Indices** | `get_index()`, `get_index_price()`, `get_index_price_names()`, `get_index_chart_data()` |
76//! | **Instruments** | `get_instrument()`, `get_instruments()`, `get_contract_size()` |
77//! | **Book Summary** | `get_book_summary_by_currency()`, `get_book_summary_by_instrument()` |
78//! | **Market Data** | `get_ticker()`, `get_order_book()`, `get_order_book_by_instrument_id()` |
79//! | **Trades** | `get_last_trades()`, `get_last_trades_by_currency()`, `get_last_trades_by_*_and_time()` |
80//! | **Funding** | `get_funding_chart_data()`, `get_funding_rate_history()`, `get_funding_rate_value()` |
81//! | **Volatility** | `get_historical_volatility()`, `get_volatility_index_data()` |
82//! | **Settlements** | `get_last_settlements_by_currency()`, `get_last_settlements_by_instrument()` |
83//! | **TradingView** | `get_tradingview_chart_data()` |
84//! | **Combo Books** | `get_combo_details()`, `get_combo_ids()`, `get_combos()` |
85//! | **Block RFQ** | `get_block_rfq_trades()` |
86//!
87//! ## Private endpoints (70+)
88//!
89//! Require valid authentication (OAuth2):
90//!
91//! | Category | Endpoints |
92//! |----------|-----------|
93//! | **Trading** | `buy_order()`, `sell_order()`, `edit_order()`, `cancel_order()`, `cancel_all()`, `cancel_all_by_*()` |
94//! | **Orders** | `get_open_orders()`, `get_order_state()`, `get_order_history_by_currency()`, `get_order_history_by_instrument()` |
95//! | **Positions** | `get_position()`, `get_positions()`, `close_position()`, `move_positions()` |
96//! | **User Trades** | `get_user_trades_by_instrument()`, `get_user_trades_by_currency()`, `get_user_trades_by_order()` |
97//! | **Account** | `get_account_summary()`, `get_account_summaries()`, `get_subaccounts()`, `get_subaccounts_details()` |
98//! | **Subaccounts** | `create_subaccount()`, `change_subaccount_name()`, `toggle_subaccount_login()`, `remove_subaccount()` |
99//! | **API Keys** | `create_api_key()`, `edit_api_key()`, `remove_api_key()`, `list_api_keys()`, `enable_api_key()`, `disable_api_key()` |
100//! | **Wallet** | `get_deposits()`, `get_withdrawals()`, `withdraw()`, `cancel_withdrawal()`, `create_deposit_address()` |
101//! | **Transfers** | `get_transfers()`, `submit_transfer_to_subaccount()`, `submit_transfer_between_subaccounts()`, `cancel_transfer_by_id()` |
102//! | **Block Trade** | `execute_block_trade()`, `verify_block_trade()`, `get_block_trade()`, `get_block_trades()`, `simulate_block_trade()` |
103//! | **Block RFQ** | `create_block_rfq()`, `accept_block_rfq()`, `add_block_rfq_quote()`, `cancel_block_rfq()`, `get_block_rfqs()` |
104//! | **Combo Books** | `create_combo()`, `get_leg_prices()` |
105//! | **MMP** | `get_mmp_config()`, `set_mmp_config()`, `reset_mmp()`, `get_mmp_status()` |
106//! | **Mass Quote** | `mass_quote()`, `cancel_quotes()` |
107//! | **Margins** | `get_margins()`, `get_order_margin_by_ids()` |
108//! | **Settlement** | `get_settlement_history_by_currency()`, `get_settlement_history_by_instrument()` |
109//!
110//! ## Limitations and important notes
111//! - This crate does not implement WebSocket or streaming. Some Deribit endpoints exist only over WS
112//!   (for example, `/public/hello` and `/private/logout`) and are not available in this HTTP client.
113//! - API Key authentication: the `authenticate_api_key` stub exists but is not yet implemented in the HTTP client.
114//! - Deribit uses JSON-RPC over HTTP; this client exposes ergonomic methods that build URLs with query params
115//!   and parse `ApiResponse<T>` in a strongly-typed manner.
116//!
117//! ## Error handling
118//! The `HttpError` type centralizes common failures: network issues (`NetworkError`),
119//! non-success HTTP responses (`RequestFailed`), parsing/structure errors (`InvalidResponse`),
120//! authentication failures (`AuthenticationFailed`), and configuration conditions (`ConfigError`).
121//!
122//! ## Rate limiting
123//! The `RateLimiter` categorizes each URL and applies a token-bucket scheme per category
124//! (Trading, MarketData, Account, Auth, General). You can inspect it via `rate_limiter()`.
125//!
126//! ## Examples
127//!
128//! See the `examples/` directory for comprehensive examples:
129//! - **Public examples** (16 binaries): Market data, instruments, trades, funding, settlements
130//! - **Private examples** (7 binaries): Trading, orders, positions, account management, mass quotes
131//!
132//! ```bash
133//! # Run a public example
134//! cargo run --bin check_currencies
135//!
136//! # Run a private example (requires .env with credentials)
137//! cargo run --bin trading_endpoints
138//! ```
139//!
140//! ## Platform support
141//!
142//! | Target | Status |
143//! |--------|--------|
144//! | Native (tokio) | ✅ Full support |
145//! | WASM (browser) | ✅ Full support |
146//! | Cloudflare Workers | ✅ Full support |
147
148pub mod auth;
149pub mod client;
150pub mod config;
151pub mod connection;
152/// HTTP API endpoints implementation for public and private Deribit API methods
153pub mod endpoints;
154pub mod error;
155pub mod message;
156pub mod model;
157pub mod prelude;
158pub mod rate_limit;
159pub mod session;
160/// Cross-platform async sleep for native and WASM targets
161pub mod sleep_compat;
162/// Cross-platform Mutex re-export for native and WASM targets
163pub mod sync_compat;
164/// Cross-platform time utilities for native and WASM targets
165pub mod time_compat;
166
167// Constants
168/// Application constants and configuration
169pub mod constants;
170/// Logging utilities and configuration
171pub mod logger;
172/// Utility functions and helpers
173pub mod utils;
174
175// Re-export main client and error types
176pub use client::*;
177pub use error::*;
178
179// Re-export specific types to avoid conflicts
180pub use auth::AuthRequest;
181pub use auth::{ApiKeyAuth, AuthManager};
182pub use config::ApiCredentials;
183pub use config::HttpConfig;
184pub use connection::*;
185pub use message::{HttpMessageBuilder, HttpRequestBuilder, HttpResponseHandler};
186pub use session::*;