Expand description
§Deribit HTTP Client (deribit_http)
Asynchronous HTTP client for the Deribit API, designed for server integrations,
batch jobs and tooling that prefer REST/HTTP over WebSocket. Built on top of
reqwest and tokio, it provides a typed set of methods for public and
private endpoints, OAuth2 authentication, category-based rate limiting and
Serde-powered data models.
This crate-level documentation is intended to be used by cargo readme to generate the README.
§Key features
- Pure async HTTP (reqwest + tokio).
- Simple Testnet/Mainnet setup:
DeribitHttpClient::new()ordefault. - Built-in OAuth2 (Client Credentials); utilities for
exchange_tokenandfork_token. - Category-based rate limiting (trading, market, account, auth, general) with a token-bucket approach.
- Strongly-typed data models (Serde) and JSON-RPC responses mapped to
ApiResponse/ApiError. - Re-exported types and structures for ergonomic usage.
- Explicit focus on Deribit REST public/private endpoints (no WebSocket/streaming in this crate).
§Quick start
use deribit_http::DeribitHttpClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// true = testnet, false = mainnet
let client = DeribitHttpClient::new();
// Public calls (no authentication required)
let currencies = client.get_currencies().await?;
println!("Supports {} currencies", currencies.len());
// Example: ticker
let ticker = client.get_ticker("BTC-PERPETUAL").await?;
println!("Mark price: {}", ticker.mark_price);
Ok(())
}§Authentication and private endpoints
- OAuth2 (Client Credentials):
DeribitHttpClient::authenticate_oauth2(client_id, client_secret)returns anAuthTokenand keeps it in theAuthManager. - Helpers:
is_authenticated(),get_auth_token(). - Session management:
exchange_token(refresh_token, subject_id, scope)andfork_token(refresh_token, session_name, scope). - API Key: the
authenticate_api_keymethod exists but is currently not implemented and will return an error.
§Configuration
- Environment shortcut:
DeribitHttpClient::new()for Testnet andnew(false)for Production. - Custom configuration:
DeribitHttpClient::with_config(HttpConfig)lets you setbase_url,timeout,user_agent,testnet, and optional credentials. - Validation: configuration is validated on client creation.
§Project structure (modules)
auth:AuthManager(OAuth2, token management) and related types (e.g.AuthRequest).client:DeribitHttpClient, public/private methods, auth helpers,exchange_tokenandfork_token.config:HttpConfigand environment helpers (testnet/production) and headers/base_url.connectionandsession: infrastructure support types (shared across the ecosystem).endpoints: HTTP implementation of public and private methods (see coverage below).error:HttpErrorvariants such asNetworkError,RequestFailed,InvalidResponse,AuthenticationFailed,ConfigError.messageandmodel: HTTP types (ApiResponse,ApiError,AuthToken, etc.).rate_limit:RateLimiterandcategorize_endpointwith per-category limits.constants: base URLs (production/testnet), endpoint routes, and common headers.
§Implemented public endpoints (selection)
The following methods exist on DeribitHttpClient within endpoints::public:
- Currencies and markets:
get_currencies(). - Indices and prices:
get_index(currency),get_index_price(index_name),get_index_price_names(). - Book summary:
get_book_summary_by_currency(currency, kind),get_book_summary_by_instrument(instrument_name). - Instruments:
get_instrument(instrument_name),get_instruments(currency, kind, expired),get_contract_size(instrument_name). - System and status:
get_server_time(),test_connection(),get_status(). - Market data:
get_ticker(instrument_name),get_order_book(instrument_name, depth),get_order_book_by_instrument_id(instrument_id, depth). - Trades:
get_last_trades(instrument_name, ...),get_last_trades_by_currency(...),get_last_trades_by_currency_and_time(...),get_last_trades_by_instrument_and_time(...). - Volatility and interest:
get_historical_volatility(currency),get_apr_history(currency, ...). - Funding:
get_funding_chart_data(instrument_name, length),get_funding_rate_history(instrument_name, start, end),get_funding_rate_value(instrument_name, start, end). - TradingView:
get_tradingview_chart_data(instrument_name, start, end, resolution). - Other:
get_delivery_prices(index_name, ...),get_expirations(currency, kind, currency_pair). - Note:
hello(client_name, client_version)is documented but WebSocket-only; in HTTP it will return a configuration error.
Included models (re-exported): Currency, IndexData, BookSummary, Instrument, Trade,
TickerData, OrderBook, FundingChartData, TradingViewChartData, DeliveryPricesResponse,
ExpirationsResponse, FundingRateData, SettlementsResponse, LastTradesResponse, etc.
§Implemented private endpoints (selection)
Require valid authentication (OAuth2). Examples include:
- Accounts and movements:
get_subaccounts(),get_transaction_log(...),get_deposits(...),get_withdrawals(...). - Basic trading:
buy_order(...),sell_order(...),cancel_order(order_id). - Account:
get_account_summary(currency, ...).
Useful re-exported models: Subaccount, TransactionLog, DepositsResponse, WithdrawalsResponse,
OrderResponse, OrderInfo, AccountSummary, Position, PortfolioInfo, etc.
§Limitations and important notes
- This crate does not implement WebSocket or streaming. Some Deribit endpoints exist only over WS
(for example,
/public/helloand/private/logout) and are not available in this HTTP client. - API Key authentication: the
authenticate_api_keystub exists but is not yet implemented in the HTTP client. - Deribit uses JSON-RPC over HTTP; this client exposes ergonomic methods that build URLs with query params
and parse
ApiResponse<T>in a strongly-typed manner.
§Error handling
The HttpError type centralizes common failures: network issues (NetworkError),
non-success HTTP responses (RequestFailed), parsing/structure errors (InvalidResponse),
authentication failures (AuthenticationFailed), and configuration conditions (ConfigError).
§Rate limiting
The RateLimiter categorizes each URL and applies a token-bucket scheme per category
(Trading, MarketData, Account, Auth, General). You can inspect it via rate_limiter().
§README generation
This crate-level header is consumed by cargo readme. To generate the README:
cargo readme -o README.mdEnsure you have cargo-readme installed (cargo install cargo-readme).
Re-exports§
pub use auth::AuthRequest;pub use auth::ApiKeyAuth;pub use auth::AuthManager;pub use config::ApiCredentials;pub use config::HttpConfig;pub use message::HttpMessageBuilder;pub use message::HttpRequestBuilder;pub use message::HttpResponseHandler;pub use client::*;pub use error::*;pub use connection::*;pub use session::*;
Modules§
- auth
- Authentication module for Deribit HTTP API
- client
- HTTP client implementation for Deribit REST API
- config
- Configuration module for HTTP client
- connection
- Connection module for HTTP client
- constants
- Application constants and configuration HTTP client constants
- endpoints
- HTTP API endpoints implementation for public and private Deribit API methods
- error
- Error handling module for HTTP client
- logger
- Logging utilities and configuration
- message
- Message handling module for HTTP client
- model
- Model definitions for HTTP client
- prelude
- Prelude module for deribit-http
- rate_
limit - Rate limiting implementation for Deribit HTTP client
- session
- Session management module for HTTP client
- utils
- Utility functions and helpers