deribit_http/
lib.rs

1//! # Deribit HTTP Client (deribit_http)
2//!
3//! Asynchronous HTTP client for the Deribit API, designed for server integrations,
4//! batch jobs and tooling that prefer REST/HTTP over WebSocket. Built on top of
5//! `reqwest` and `tokio`, it provides a typed set of methods for public and
6//! private endpoints, OAuth2 authentication, category-based rate limiting and
7//! Serde-powered data models.
8//!
9//! This crate-level documentation is intended to be used by `cargo readme` to generate the README.
10//!
11//! ## Key features
12//! - Pure async HTTP (reqwest + tokio).
13//! - Simple Testnet/Mainnet setup: `DeribitHttpClient::new()` or `default`.
14//! - Built-in OAuth2 (Client Credentials); utilities for `exchange_token` and `fork_token`.
15//! - Category-based rate limiting (trading, market, account, auth, general) with a token-bucket approach.
16//! - Strongly-typed data models (Serde) and JSON-RPC responses mapped to `ApiResponse`/`ApiError`.
17//! - Re-exported types and structures for ergonomic usage.
18//! - Explicit focus on Deribit REST public/private endpoints (no WebSocket/streaming in this crate).
19//!
20//! ## Quick start
21//! ```rust
22//! use deribit_http::DeribitHttpClient;
23//!
24//! #[tokio::main]
25//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
26//!     // true = testnet, false = mainnet
27//!     let client = DeribitHttpClient::new();
28//!
29//!     // Public calls (no authentication required)
30//!     let currencies = client.get_currencies().await?;
31//!     println!("Supports {} currencies", currencies.len());
32//!
33//!     // Example: ticker
34//!     let ticker = client.get_ticker("BTC-PERPETUAL").await?;
35//!     println!("Mark price: {}", ticker.mark_price);
36//!
37//!     Ok(())
38//! }
39//! ```
40//!
41//! ## Authentication and private endpoints
42//! - OAuth2 (Client Credentials): `DeribitHttpClient::authenticate_oauth2(client_id, client_secret)` returns an `AuthToken` and keeps it in the `AuthManager`.
43//! - Helpers: `is_authenticated()`, `get_auth_token()`.
44//! - Session management: `exchange_token(refresh_token, subject_id, scope)` and `fork_token(refresh_token, session_name, scope)`.
45//! - API Key: the `authenticate_api_key` method exists but is currently not implemented and will return an error.
46//!
47//! ## Configuration
48//! - Environment shortcut: `DeribitHttpClient::new()` for Testnet and `new(false)` for Production.
49//! - Custom configuration: `DeribitHttpClient::with_config(HttpConfig)` lets you set `base_url`, `timeout`, `user_agent`, `testnet`, and optional credentials.
50//! - Validation: configuration is validated on client creation.
51//!
52//! ## Project structure (modules)
53//! - `auth`: `AuthManager` (OAuth2, token management) and related types (e.g. `AuthRequest`).
54//! - `client`: `DeribitHttpClient`, public/private methods, auth helpers, `exchange_token` and `fork_token`.
55//! - `config`: `HttpConfig` and environment helpers (testnet/production) and headers/base_url.
56//! - `connection` and `session`: infrastructure support types (shared across the ecosystem).
57//! - `endpoints`: HTTP implementation of public and private methods (see coverage below).
58//! - `error`: `HttpError` variants such as `NetworkError`, `RequestFailed`, `InvalidResponse`, `AuthenticationFailed`, `ConfigError`.
59//! - `message` and `model`: HTTP types (`ApiResponse`, `ApiError`, `AuthToken`, etc.).
60//! - `rate_limit`: `RateLimiter` and `categorize_endpoint` with per-category limits.
61//! - `constants`: base URLs (production/testnet), endpoint routes, and common headers.
62//!
63//! ## Implemented public endpoints (selection)
64//! The following methods exist on `DeribitHttpClient` within `endpoints::public`:
65//! - Currencies and markets: `get_currencies()`.
66//! - Indices and prices: `get_index(currency)`, `get_index_price(index_name)`, `get_index_price_names()`.
67//! - Book summary: `get_book_summary_by_currency(currency, kind)`, `get_book_summary_by_instrument(instrument_name)`.
68//! - Instruments: `get_instrument(instrument_name)`, `get_instruments(currency, kind, expired)`, `get_contract_size(instrument_name)`.
69//! - System and status: `get_server_time()`, `test_connection()`, `get_status()`.
70//! - Market data: `get_ticker(instrument_name)`, `get_order_book(instrument_name, depth)`, `get_order_book_by_instrument_id(instrument_id, depth)`.
71//! - Trades: `get_last_trades(instrument_name, ...)`, `get_last_trades_by_currency(...)`,
72//!   `get_last_trades_by_currency_and_time(...)`, `get_last_trades_by_instrument_and_time(...)`.
73//! - Volatility and interest: `get_historical_volatility(currency)`, `get_apr_history(currency, ...)`.
74//! - Funding: `get_funding_chart_data(instrument_name, length)`, `get_funding_rate_history(instrument_name, start, end)`, `get_funding_rate_value(instrument_name, start, end)`.
75//! - TradingView: `get_tradingview_chart_data(instrument_name, start, end, resolution)`.
76//! - Other: `get_delivery_prices(index_name, ...)`, `get_expirations(currency, kind, currency_pair)`.
77//! - Note: `hello(client_name, client_version)` is documented but WebSocket-only; in HTTP it will return a configuration error.
78//!
79//! Included models (re-exported): `Currency`, `IndexData`, `BookSummary`, `Instrument`, `Trade`,
80//! `TickerData`, `OrderBook`, `FundingChartData`, `TradingViewChartData`, `DeliveryPricesResponse`,
81//! `ExpirationsResponse`, `FundingRateData`, `SettlementsResponse`, `LastTradesResponse`, etc.
82//!
83//! ## Implemented private endpoints (selection)
84//! Require valid authentication (OAuth2). Examples include:
85//! - Accounts and movements: `get_subaccounts()`, `get_transaction_log(...)`, `get_deposits(...)`, `get_withdrawals(...)`.
86//! - Basic trading: `buy_order(...)`, `sell_order(...)`, `cancel_order(order_id)`.
87//! - Account: `get_account_summary(currency, ...)`.
88//!
89//! Useful re-exported models: `Subaccount`, `TransactionLog`, `DepositsResponse`, `WithdrawalsResponse`,
90//! `OrderResponse`, `OrderInfo`, `AccountSummary`, `Position`, `PortfolioInfo`, etc.
91//!
92//! ## Limitations and important notes
93//! - This crate does not implement WebSocket or streaming. Some Deribit endpoints exist only over WS
94//!   (for example, `/public/hello` and `/private/logout`) and are not available in this HTTP client.
95//! - API Key authentication: the `authenticate_api_key` stub exists but is not yet implemented in the HTTP client.
96//! - Deribit uses JSON-RPC over HTTP; this client exposes ergonomic methods that build URLs with query params
97//!   and parse `ApiResponse<T>` in a strongly-typed manner.
98//!
99//! ## Error handling
100//! The `HttpError` type centralizes common failures: network issues (`NetworkError`),
101//! non-success HTTP responses (`RequestFailed`), parsing/structure errors (`InvalidResponse`),
102//! authentication failures (`AuthenticationFailed`), and configuration conditions (`ConfigError`).
103//!
104//! ## Rate limiting
105//! The `RateLimiter` categorizes each URL and applies a token-bucket scheme per category
106//! (Trading, MarketData, Account, Auth, General). You can inspect it via `rate_limiter()`.
107//!
108//! ## README generation
109//! This crate-level header is consumed by `cargo readme`. To generate the README:
110//! ```bash
111//! cargo readme -o README.md
112//! ```
113//! Ensure you have `cargo-readme` installed (`cargo install cargo-readme`).
114
115pub mod auth;
116pub mod client;
117pub mod config;
118pub mod connection;
119/// HTTP API endpoints implementation for public and private Deribit API methods
120pub mod endpoints;
121pub mod error;
122pub mod message;
123pub mod model;
124pub mod prelude;
125pub mod rate_limit;
126pub mod session;
127
128// Constants
129/// Application constants and configuration
130pub mod constants;
131/// Logging utilities and configuration
132pub mod logger;
133/// Utility functions and helpers
134pub mod utils;
135
136// Re-export main client and error types
137pub use client::*;
138pub use error::*;
139
140// Re-export specific types to avoid conflicts
141pub use auth::AuthRequest;
142pub use auth::{ApiKeyAuth, AuthManager};
143pub use config::ApiCredentials;
144pub use config::HttpConfig;
145pub use connection::*;
146pub use message::{HttpMessageBuilder, HttpRequestBuilder, HttpResponseHandler};
147pub use session::*;