nautilus_deribit/http/
models.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Deribit HTTP API models and types.
17
18use std::fmt::Display;
19
20use serde::{Deserialize, Serialize};
21use ustr::Ustr;
22
23pub use crate::common::rpc::{DeribitJsonRpcError, DeribitJsonRpcRequest, DeribitJsonRpcResponse};
24
25/// JSON-RPC 2.0 response payload (either success or error).
26#[derive(Debug, Serialize, Deserialize)]
27#[serde(untagged)]
28pub enum DeribitResponsePayload<T> {
29    /// Successful response with result data
30    Success { result: T },
31    /// Error response with error details
32    Error { error: DeribitJsonRpcError },
33}
34
35/// Deribit instrument definition.
36#[derive(Clone, Debug, Serialize, Deserialize)]
37pub struct DeribitInstrument {
38    /// The underlying currency being traded
39    pub base_currency: Ustr,
40    /// Block trade commission for instrument
41    #[serde(default)]
42    pub block_trade_commission: Option<f64>,
43    /// Minimum amount for block trading
44    pub block_trade_min_trade_amount: Option<f64>,
45    /// Specifies minimal price change for block trading
46    #[serde(default)]
47    pub block_trade_tick_size: Option<f64>,
48    /// Contract size for instrument
49    pub contract_size: f64,
50    /// Counter currency for the instrument
51    pub counter_currency: Option<Ustr>,
52    /// The time when the instrument was first created (milliseconds since UNIX epoch)
53    pub creation_timestamp: i64,
54    /// The time when the instrument will expire (milliseconds since UNIX epoch)
55    pub expiration_timestamp: Option<i64>,
56    /// Future type (deprecated, use instrument_type instead)
57    pub future_type: Option<String>,
58    /// Instrument ID
59    pub instrument_id: i64,
60    /// Unique instrument identifier (e.g., "BTC-PERPETUAL")
61    pub instrument_name: Ustr,
62    /// Type of the instrument: "linear" or "reversed"
63    pub instrument_type: Option<String>,
64    /// Indicates if the instrument can currently be traded
65    pub is_active: bool,
66    /// Instrument kind: "future", "option", "spot", "future_combo", "option_combo"
67    pub kind: DeribitInstrumentKind,
68    /// Maker commission for instrument
69    pub maker_commission: f64,
70    /// Maximal leverage for instrument (only for futures)
71    pub max_leverage: Option<i64>,
72    /// Maximal liquidation trade commission for instrument (only for futures)
73    pub max_liquidation_commission: Option<f64>,
74    /// Minimum amount for trading
75    pub min_trade_amount: f64,
76    /// The option type (only for options)
77    pub option_type: Option<DeribitOptionType>,
78    /// Name of price index that is used for this instrument
79    pub price_index: Option<String>,
80    /// The currency in which the instrument prices are quoted
81    pub quote_currency: Ustr,
82    /// Settlement currency for the instrument (not present for spot)
83    pub settlement_currency: Option<Ustr>,
84    /// The settlement period (not present for spot)
85    pub settlement_period: Option<String>,
86    /// The strike value (only for options)
87    pub strike: Option<f64>,
88    /// Taker commission for instrument
89    pub taker_commission: f64,
90    /// Specifies minimal price change and number of decimal places for instrument prices
91    pub tick_size: f64,
92    /// Tick size steps for different price ranges
93    pub tick_size_steps: Option<Vec<DeribitTickSizeStep>>,
94}
95
96/// Tick size step definition for price-dependent tick sizes.
97#[derive(Clone, Debug, Serialize, Deserialize)]
98pub struct DeribitTickSizeStep {
99    /// The price from which the increased tick size applies
100    pub above_price: f64,
101    /// Tick size to be used above the price
102    pub tick_size: f64,
103}
104
105/// Deribit instrument kind.
106#[derive(
107    Clone,
108    Copy,
109    Debug,
110    PartialEq,
111    Eq,
112    Hash,
113    strum::AsRefStr,
114    strum::Display,
115    strum::EnumIter,
116    strum::EnumString,
117    Serialize,
118    Deserialize,
119)]
120#[serde(rename_all = "snake_case")]
121#[strum(serialize_all = "snake_case")]
122#[cfg_attr(
123    feature = "python",
124    pyo3::pyclass(eq, eq_int, module = "nautilus_trader.core.nautilus_pyo3.deribit")
125)]
126pub enum DeribitInstrumentKind {
127    /// Future contract
128    Future,
129    /// Option contract
130    Option,
131    /// Spot market
132    Spot,
133    /// Future combo
134    #[serde(rename = "future_combo")]
135    FutureCombo,
136    /// Option combo
137    #[serde(rename = "option_combo")]
138    OptionCombo,
139}
140
141/// Deribit currency.
142#[derive(
143    Clone,
144    Copy,
145    Debug,
146    PartialEq,
147    Eq,
148    Hash,
149    strum::AsRefStr,
150    strum::EnumIter,
151    strum::EnumString,
152    Serialize,
153    Deserialize,
154)]
155#[serde(rename_all = "UPPERCASE")]
156#[strum(serialize_all = "UPPERCASE")]
157#[cfg_attr(
158    feature = "python",
159    pyo3::pyclass(eq, eq_int, module = "nautilus_trader.core.nautilus_pyo3.deribit")
160)]
161pub enum DeribitCurrency {
162    /// Bitcoin
163    BTC,
164    /// Ethereum
165    ETH,
166    /// USD Coin
167    USDC,
168    /// Tether
169    USDT,
170    /// Euro stablecoin
171    EURR,
172    /// All currencies
173    #[serde(rename = "any")]
174    ANY,
175}
176
177/// Deribit option type.
178#[derive(
179    Clone,
180    Copy,
181    Debug,
182    PartialEq,
183    Eq,
184    Hash,
185    strum::AsRefStr,
186    strum::Display,
187    strum::EnumIter,
188    strum::EnumString,
189    Serialize,
190    Deserialize,
191)]
192#[serde(rename_all = "lowercase")]
193#[strum(serialize_all = "lowercase")]
194#[cfg_attr(
195    feature = "python",
196    pyo3::pyclass(eq, eq_int, module = "nautilus_trader.core.nautilus_pyo3.deribit")
197)]
198pub enum DeribitOptionType {
199    /// Call option
200    Call,
201    /// Put option
202    Put,
203}
204
205impl DeribitCurrency {
206    /// Returns the currency as a string.
207    #[must_use]
208    pub fn as_str(&self) -> &'static str {
209        match self {
210            Self::BTC => "BTC",
211            Self::ETH => "ETH",
212            Self::USDC => "USDC",
213            Self::USDT => "USDT",
214            Self::EURR => "EURR",
215            Self::ANY => "any",
216        }
217    }
218}
219
220impl Display for DeribitCurrency {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        write!(f, "{}", self.as_str())
223    }
224}
225
226/// Wrapper for the account summaries response.
227///
228/// The API returns an object with a `summaries` field containing the array of account summaries,
229/// plus account-level metadata.
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct DeribitAccountSummariesResponse {
232    /// Array of per-currency account summaries
233    pub summaries: Vec<DeribitAccountSummary>,
234    /// Account ID
235    #[serde(default)]
236    pub id: Option<i64>,
237    /// Account email
238    #[serde(default)]
239    pub email: Option<String>,
240    /// System name
241    #[serde(default)]
242    pub system_name: Option<String>,
243    /// Account username
244    #[serde(default)]
245    pub username: Option<String>,
246    /// Account type (e.g., "main", "subaccount")
247    #[serde(rename = "type", default)]
248    pub account_type: Option<String>,
249    /// Account creation timestamp (milliseconds since UNIX epoch)
250    #[serde(default)]
251    pub creation_timestamp: Option<i64>,
252    /// Referrer ID (affiliation program)
253    #[serde(default)]
254    pub referrer_id: Option<String>,
255    /// Whether login is enabled for this account
256    #[serde(default)]
257    pub login_enabled: Option<bool>,
258    /// Whether security keys are enabled
259    #[serde(default)]
260    pub security_keys_enabled: Option<bool>,
261    /// Whether MMP (Market Maker Protection) is enabled
262    #[serde(default)]
263    pub mmp_enabled: Option<bool>,
264    /// Whether inter-user transfers are enabled
265    #[serde(default)]
266    pub interuser_transfers_enabled: Option<bool>,
267    /// Self-trading reject mode
268    #[serde(default)]
269    pub self_trading_reject_mode: Option<String>,
270    /// Whether self-trading is extended to subaccounts
271    #[serde(default)]
272    pub self_trading_extended_to_subaccounts: Option<bool>,
273    /// Block RFQ self match prevention
274    #[serde(default)]
275    pub block_rfq_self_match_prevention: Option<bool>,
276}
277
278/// Account summary for a single currency.
279///
280/// Contains balance, equity, margin information, and profit/loss data.
281#[derive(Debug, Clone, Serialize, Deserialize)]
282pub struct DeribitAccountSummary {
283    /// Currency code (e.g., "BTC", "ETH")
284    pub currency: Ustr,
285    /// Account equity (balance + unrealized PnL)
286    pub equity: f64,
287    /// Account balance
288    pub balance: f64,
289    /// Available funds for trading
290    pub available_funds: f64,
291    /// Margin balance (for derivatives)
292    pub margin_balance: f64,
293    /// Initial margin (required for current positions)
294    #[serde(default)]
295    pub initial_margin: Option<f64>,
296    /// Maintenance margin
297    #[serde(default)]
298    pub maintenance_margin: Option<f64>,
299    /// Total profit/loss
300    #[serde(default)]
301    pub total_pl: Option<f64>,
302    /// Session unrealized profit/loss
303    #[serde(default)]
304    pub session_upl: Option<f64>,
305    /// Session realized profit/loss
306    #[serde(default)]
307    pub session_rpl: Option<f64>,
308    /// Portfolio margining enabled
309    #[serde(default)]
310    pub portfolio_margining_enabled: Option<bool>,
311}
312
313/// Extended account summary with additional account details.
314///
315/// Returned by `private/get_account_summary` with `extended=true`.
316/// Contains all fields from [`DeribitAccountSummary`] plus account metadata,
317/// position Greeks, detailed margins, and fee structures.
318#[derive(Debug, Clone, Serialize, Deserialize)]
319pub struct DeribitAccountSummaryExtended {
320    /// Currency code (e.g., "BTC", "ETH")
321    pub currency: Ustr,
322    /// Account equity (balance + unrealized PnL)
323    pub equity: f64,
324    /// Account balance
325    pub balance: f64,
326    /// Available funds for trading
327    pub available_funds: f64,
328    /// Margin balance (for derivatives)
329    pub margin_balance: f64,
330    /// Initial margin (required for current positions)
331    #[serde(default)]
332    pub initial_margin: Option<f64>,
333    /// Maintenance margin
334    #[serde(default)]
335    pub maintenance_margin: Option<f64>,
336    /// Total profit/loss
337    #[serde(default)]
338    pub total_pl: Option<f64>,
339    /// Session unrealized profit/loss
340    #[serde(default)]
341    pub session_upl: Option<f64>,
342    /// Session realized profit/loss
343    #[serde(default)]
344    pub session_rpl: Option<f64>,
345    /// Portfolio margining enabled
346    #[serde(default)]
347    pub portfolio_margining_enabled: Option<bool>,
348    // Extended fields below
349    /// Account ID
350    #[serde(default)]
351    pub id: Option<i64>,
352    /// Account email
353    #[serde(default)]
354    pub email: Option<String>,
355    /// Account username
356    #[serde(default)]
357    pub username: Option<String>,
358    /// System name
359    #[serde(default)]
360    pub system_name: Option<String>,
361    /// Account type (e.g., "main", "subaccount")
362    #[serde(rename = "type", default)]
363    pub account_type: Option<String>,
364    /// Futures session unrealized P&L
365    #[serde(default)]
366    pub futures_session_upl: Option<f64>,
367    /// Futures session realized P&L
368    #[serde(default)]
369    pub futures_session_rpl: Option<f64>,
370    /// Options session unrealized P&L
371    #[serde(default)]
372    pub options_session_upl: Option<f64>,
373    /// Options session realized P&L
374    #[serde(default)]
375    pub options_session_rpl: Option<f64>,
376    /// Futures profit/loss
377    #[serde(default)]
378    pub futures_pl: Option<f64>,
379    /// Options profit/loss
380    #[serde(default)]
381    pub options_pl: Option<f64>,
382    /// Options delta
383    #[serde(default)]
384    pub options_delta: Option<f64>,
385    /// Options gamma
386    #[serde(default)]
387    pub options_gamma: Option<f64>,
388    /// Options vega
389    #[serde(default)]
390    pub options_vega: Option<f64>,
391    /// Options theta
392    #[serde(default)]
393    pub options_theta: Option<f64>,
394    /// Options value
395    #[serde(default)]
396    pub options_value: Option<f64>,
397    /// Total delta across all positions
398    #[serde(default)]
399    pub delta_total: Option<f64>,
400    /// Projected delta total
401    #[serde(default)]
402    pub projected_delta_total: Option<f64>,
403    /// Projected initial margin
404    #[serde(default)]
405    pub projected_initial_margin: Option<f64>,
406    /// Projected maintenance margin
407    #[serde(default)]
408    pub projected_maintenance_margin: Option<f64>,
409    /// Estimated liquidation ratio
410    #[serde(default)]
411    pub estimated_liquidation_ratio: Option<f64>,
412    /// Available withdrawal funds
413    #[serde(default)]
414    pub available_withdrawal_funds: Option<f64>,
415    /// Spot reserve
416    #[serde(default)]
417    pub spot_reserve: Option<f64>,
418    /// Fee balance
419    #[serde(default)]
420    pub fee_balance: Option<f64>,
421    /// Margin model (e.g., "segregated_sm", "cross_pm")
422    #[serde(default)]
423    pub margin_model: Option<String>,
424    /// Cross collateral enabled
425    #[serde(default)]
426    pub cross_collateral_enabled: Option<bool>,
427    /// Account creation timestamp (milliseconds since UNIX epoch)
428    #[serde(default)]
429    pub creation_timestamp: Option<i64>,
430    /// Whether login is enabled for this account
431    #[serde(default)]
432    pub login_enabled: Option<bool>,
433    /// Whether security keys are enabled
434    #[serde(default)]
435    pub security_keys_enabled: Option<bool>,
436    /// Whether MMP (Market Maker Protection) is enabled
437    #[serde(default)]
438    pub mmp_enabled: Option<bool>,
439    /// Whether inter-user transfers are enabled
440    #[serde(default)]
441    pub interuser_transfers_enabled: Option<bool>,
442    /// Self-trading reject mode
443    #[serde(default)]
444    pub self_trading_reject_mode: Option<String>,
445    /// Whether self-trading is extended to subaccounts
446    #[serde(default)]
447    pub self_trading_extended_to_subaccounts: Option<bool>,
448    /// Referrer ID (affiliation program)
449    #[serde(default)]
450    pub referrer_id: Option<String>,
451    /// Block RFQ self match prevention
452    #[serde(default)]
453    pub block_rfq_self_match_prevention: Option<bool>,
454}
455
456/// Deribit public trade data from the market data API.
457///
458/// Represents a single trade returned by `/public/get_last_trades_by_instrument_and_time`
459/// and other trade-related endpoints.
460#[derive(Clone, Debug, Serialize, Deserialize)]
461pub struct DeribitPublicTrade {
462    /// Trade amount. For perpetual and inverse futures the amount is in USD units.
463    /// For options and linear futures it is the underlying base currency coin.
464    pub amount: f64,
465    /// Trade size in contract units (optional, may be absent in historical trades).
466    #[serde(default)]
467    pub contracts: Option<f64>,
468    /// Direction of the trade: "buy" or "sell"
469    pub direction: String,
470    /// Index Price at the moment of trade.
471    pub index_price: f64,
472    /// Unique instrument identifier.
473    pub instrument_name: String,
474    /// Option implied volatility for the price (Option only).
475    #[serde(default)]
476    pub iv: Option<f64>,
477    /// Optional field (only for trades caused by liquidation).
478    #[serde(default)]
479    pub liquidation: Option<String>,
480    /// Mark Price at the moment of trade.
481    pub mark_price: f64,
482    /// Price in base currency.
483    pub price: f64,
484    /// Direction of the "tick" (0 = Plus Tick, 1 = Zero-Plus Tick, 2 = Minus Tick, 3 = Zero-Minus Tick).
485    pub tick_direction: i32,
486    /// The timestamp of the trade (milliseconds since the UNIX epoch).
487    pub timestamp: i64,
488    /// Unique (per currency) trade identifier.
489    pub trade_id: String,
490    /// The sequence number of the trade within instrument.
491    pub trade_seq: i64,
492    /// Block trade id - when trade was part of a block trade.
493    #[serde(default)]
494    pub block_trade_id: Option<String>,
495    /// Block trade leg count - when trade was part of a block trade.
496    #[serde(default)]
497    pub block_trade_leg_count: Option<i32>,
498    /// ID of the Block RFQ - when trade was part of the Block RFQ.
499    #[serde(default)]
500    pub block_rfq_id: Option<i64>,
501    /// Optional field containing combo instrument name if the trade is a combo trade.
502    #[serde(default)]
503    pub combo_id: Option<String>,
504    /// Optional field containing combo trade identifier if the trade is a combo trade.
505    #[serde(default)]
506    pub combo_trade_id: Option<f64>,
507}
508
509/// Response wrapper for trades endpoints.
510///
511/// Contains the trades array and pagination information.
512#[derive(Clone, Debug, Serialize, Deserialize)]
513pub struct DeribitTradesResponse {
514    /// Whether there are more trades available.
515    pub has_more: bool,
516    /// Array of trade objects.
517    pub trades: Vec<DeribitPublicTrade>,
518}
519
520/// Response from `public/get_tradingview_chart_data` endpoint.
521///
522/// Contains OHLCV data in array format where each array element corresponds
523/// to a single candle at the index in the `ticks` array.
524#[derive(Clone, Debug, Serialize, Deserialize)]
525pub struct DeribitTradingViewChartData {
526    /// List of prices at close (one per candle)
527    pub close: Vec<f64>,
528    /// List of cost bars (volume in quote currency, one per candle)
529    #[serde(default)]
530    pub cost: Vec<f64>,
531    /// List of highest price levels (one per candle)
532    pub high: Vec<f64>,
533    /// List of lowest price levels (one per candle)
534    pub low: Vec<f64>,
535    /// List of prices at open (one per candle)
536    pub open: Vec<f64>,
537    /// Status of the query: "ok" or "no_data"
538    pub status: String,
539    /// Values of the time axis given in milliseconds since UNIX epoch
540    pub ticks: Vec<i64>,
541    /// List of volume bars (in base currency, one per candle)
542    pub volume: Vec<f64>,
543}
544
545/// Response from `public/get_order_book` endpoint.
546///
547/// Contains the current order book state with bids, asks, and market data.
548#[derive(Clone, Debug, Serialize, Deserialize)]
549pub struct DeribitOrderBook {
550    /// The timestamp of the order book (milliseconds since UNIX epoch)
551    pub timestamp: i64,
552    /// Unique instrument identifier
553    pub instrument_name: String,
554    /// List of bids as [price, amount] pairs
555    pub bids: Vec<[f64; 2]>,
556    /// List of asks as [price, amount] pairs
557    pub asks: Vec<[f64; 2]>,
558    /// The state of the order book: "open" or "closed"
559    pub state: String,
560    /// The current best bid price (null if there aren't any bids)
561    #[serde(default)]
562    pub best_bid_price: Option<f64>,
563    /// The current best ask price (null if there aren't any asks)
564    #[serde(default)]
565    pub best_ask_price: Option<f64>,
566    /// The order size of all best bids
567    #[serde(default)]
568    pub best_bid_amount: Option<f64>,
569    /// The order size of all best asks
570    #[serde(default)]
571    pub best_ask_amount: Option<f64>,
572    /// The mark price for the instrument
573    #[serde(default)]
574    pub mark_price: Option<f64>,
575    /// The price for the last trade
576    #[serde(default)]
577    pub last_price: Option<f64>,
578    /// Current index price
579    #[serde(default)]
580    pub index_price: Option<f64>,
581    /// The total amount of outstanding contracts
582    #[serde(default)]
583    pub open_interest: Option<f64>,
584    /// The maximum price for the future
585    #[serde(default)]
586    pub max_price: Option<f64>,
587    /// The minimum price for the future
588    #[serde(default)]
589    pub min_price: Option<f64>,
590    /// Current funding (perpetual only)
591    #[serde(default)]
592    pub current_funding: Option<f64>,
593    /// Funding 8h (perpetual only)
594    #[serde(default)]
595    pub funding_8h: Option<f64>,
596    /// The settlement price for the instrument (when state = open)
597    #[serde(default)]
598    pub settlement_price: Option<f64>,
599    /// The settlement/delivery price for the instrument (when state = closed)
600    #[serde(default)]
601    pub delivery_price: Option<f64>,
602    /// (Only for option) implied volatility for best bid
603    #[serde(default)]
604    pub bid_iv: Option<f64>,
605    /// (Only for option) implied volatility for best ask
606    #[serde(default)]
607    pub ask_iv: Option<f64>,
608    /// (Only for option) implied volatility for mark price
609    #[serde(default)]
610    pub mark_iv: Option<f64>,
611    /// Underlying price for implied volatility calculations (options only)
612    #[serde(default)]
613    pub underlying_price: Option<f64>,
614    /// Name of the underlying future, or index_price (options only)
615    #[serde(default)]
616    pub underlying_index: Option<serde_json::Value>,
617    /// Interest rate used in implied volatility calculations (options only)
618    #[serde(default)]
619    pub interest_rate: Option<f64>,
620}