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