nautilus_deribit/http/
models.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
105#[serde(rename_all = "snake_case")]
106pub enum DeribitInstrumentKind {
107    /// Future contract
108    Future,
109    /// Option contract
110    Option,
111    /// Spot market
112    Spot,
113    /// Future combo
114    #[serde(rename = "future_combo")]
115    FutureCombo,
116    /// Option combo
117    #[serde(rename = "option_combo")]
118    OptionCombo,
119}
120
121/// Deribit currency.
122#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
123#[serde(rename_all = "UPPERCASE")]
124pub enum DeribitCurrency {
125    /// Bitcoin
126    BTC,
127    /// Ethereum
128    ETH,
129    /// USD Coin
130    USDC,
131    /// Tether
132    USDT,
133    /// Euro stablecoin
134    EURR,
135}
136
137/// Deribit option type.
138#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
139#[serde(rename_all = "lowercase")]
140pub enum DeribitOptionType {
141    /// Call option
142    Call,
143    /// Put option
144    Put,
145}
146
147impl DeribitCurrency {
148    /// Returns the currency as a string.
149    #[must_use]
150    pub fn as_str(&self) -> &'static str {
151        match self {
152            Self::BTC => "BTC",
153            Self::ETH => "ETH",
154            Self::USDC => "USDC",
155            Self::USDT => "USDT",
156            Self::EURR => "EURR",
157        }
158    }
159}
160
161impl std::fmt::Display for DeribitCurrency {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        write!(f, "{}", self.as_str())
164    }
165}
166
167/// Wrapper for the account summaries response.
168///
169/// The API returns an object with a `summaries` field containing the array of account summaries,
170/// plus account-level metadata.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct DeribitAccountSummariesResponse {
173    /// Array of per-currency account summaries
174    pub summaries: Vec<DeribitAccountSummary>,
175    /// Account ID
176    #[serde(default)]
177    pub id: Option<i64>,
178    /// Account email
179    #[serde(default)]
180    pub email: Option<String>,
181    /// System name
182    #[serde(default)]
183    pub system_name: Option<String>,
184    /// Account username
185    #[serde(default)]
186    pub username: Option<String>,
187    /// Account type (e.g., "main", "subaccount")
188    #[serde(rename = "type", default)]
189    pub account_type: Option<String>,
190    /// Account creation timestamp (milliseconds since UNIX epoch)
191    #[serde(default)]
192    pub creation_timestamp: Option<i64>,
193    /// Referrer ID (affiliation program)
194    #[serde(default)]
195    pub referrer_id: Option<String>,
196    /// Whether login is enabled for this account
197    #[serde(default)]
198    pub login_enabled: Option<bool>,
199    /// Whether security keys are enabled
200    #[serde(default)]
201    pub security_keys_enabled: Option<bool>,
202    /// Whether MMP (Market Maker Protection) is enabled
203    #[serde(default)]
204    pub mmp_enabled: Option<bool>,
205    /// Whether inter-user transfers are enabled
206    #[serde(default)]
207    pub interuser_transfers_enabled: Option<bool>,
208    /// Self-trading reject mode
209    #[serde(default)]
210    pub self_trading_reject_mode: Option<String>,
211    /// Whether self-trading is extended to subaccounts
212    #[serde(default)]
213    pub self_trading_extended_to_subaccounts: Option<bool>,
214    /// Block RFQ self match prevention
215    #[serde(default)]
216    pub block_rfq_self_match_prevention: Option<bool>,
217}
218
219/// Account summary for a single currency.
220///
221/// Contains balance, equity, margin information, and profit/loss data.
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct DeribitAccountSummary {
224    /// Currency code (e.g., "BTC", "ETH")
225    pub currency: Ustr,
226    /// Account equity (balance + unrealized PnL)
227    pub equity: f64,
228    /// Account balance
229    pub balance: f64,
230    /// Available funds for trading
231    pub available_funds: f64,
232    /// Margin balance (for derivatives)
233    pub margin_balance: f64,
234    /// Initial margin (required for current positions)
235    #[serde(default)]
236    pub initial_margin: Option<f64>,
237    /// Maintenance margin
238    #[serde(default)]
239    pub maintenance_margin: Option<f64>,
240    /// Total profit/loss
241    #[serde(default)]
242    pub total_pl: Option<f64>,
243    /// Session unrealized profit/loss
244    #[serde(default)]
245    pub session_upl: Option<f64>,
246    /// Session realized profit/loss
247    #[serde(default)]
248    pub session_rpl: Option<f64>,
249    /// Portfolio margining enabled
250    #[serde(default)]
251    pub portfolio_margining_enabled: Option<bool>,
252}
253
254/// Extended account summary with additional account details.
255///
256/// Returned by `private/get_account_summary` with `extended=true`.
257/// Contains all fields from [`DeribitAccountSummary`] plus account metadata,
258/// position Greeks, detailed margins, and fee structures.
259#[derive(Debug, Clone, Serialize, Deserialize)]
260pub struct DeribitAccountSummaryExtended {
261    /// Currency code (e.g., "BTC", "ETH")
262    pub currency: Ustr,
263    /// Account equity (balance + unrealized PnL)
264    pub equity: f64,
265    /// Account balance
266    pub balance: f64,
267    /// Available funds for trading
268    pub available_funds: f64,
269    /// Margin balance (for derivatives)
270    pub margin_balance: f64,
271    /// Initial margin (required for current positions)
272    #[serde(default)]
273    pub initial_margin: Option<f64>,
274    /// Maintenance margin
275    #[serde(default)]
276    pub maintenance_margin: Option<f64>,
277    /// Total profit/loss
278    #[serde(default)]
279    pub total_pl: Option<f64>,
280    /// Session unrealized profit/loss
281    #[serde(default)]
282    pub session_upl: Option<f64>,
283    /// Session realized profit/loss
284    #[serde(default)]
285    pub session_rpl: Option<f64>,
286    /// Portfolio margining enabled
287    #[serde(default)]
288    pub portfolio_margining_enabled: Option<bool>,
289    // Extended fields below
290    /// Account ID
291    #[serde(default)]
292    pub id: Option<i64>,
293    /// Account email
294    #[serde(default)]
295    pub email: Option<String>,
296    /// Account username
297    #[serde(default)]
298    pub username: Option<String>,
299    /// System name
300    #[serde(default)]
301    pub system_name: Option<String>,
302    /// Account type (e.g., "main", "subaccount")
303    #[serde(rename = "type", default)]
304    pub account_type: Option<String>,
305    /// Futures session unrealized P&L
306    #[serde(default)]
307    pub futures_session_upl: Option<f64>,
308    /// Futures session realized P&L
309    #[serde(default)]
310    pub futures_session_rpl: Option<f64>,
311    /// Options session unrealized P&L
312    #[serde(default)]
313    pub options_session_upl: Option<f64>,
314    /// Options session realized P&L
315    #[serde(default)]
316    pub options_session_rpl: Option<f64>,
317    /// Futures profit/loss
318    #[serde(default)]
319    pub futures_pl: Option<f64>,
320    /// Options profit/loss
321    #[serde(default)]
322    pub options_pl: Option<f64>,
323    /// Options delta
324    #[serde(default)]
325    pub options_delta: Option<f64>,
326    /// Options gamma
327    #[serde(default)]
328    pub options_gamma: Option<f64>,
329    /// Options vega
330    #[serde(default)]
331    pub options_vega: Option<f64>,
332    /// Options theta
333    #[serde(default)]
334    pub options_theta: Option<f64>,
335    /// Options value
336    #[serde(default)]
337    pub options_value: Option<f64>,
338    /// Total delta across all positions
339    #[serde(default)]
340    pub delta_total: Option<f64>,
341    /// Projected delta total
342    #[serde(default)]
343    pub projected_delta_total: Option<f64>,
344    /// Projected initial margin
345    #[serde(default)]
346    pub projected_initial_margin: Option<f64>,
347    /// Projected maintenance margin
348    #[serde(default)]
349    pub projected_maintenance_margin: Option<f64>,
350    /// Estimated liquidation ratio
351    #[serde(default)]
352    pub estimated_liquidation_ratio: Option<f64>,
353    /// Available withdrawal funds
354    #[serde(default)]
355    pub available_withdrawal_funds: Option<f64>,
356    /// Spot reserve
357    #[serde(default)]
358    pub spot_reserve: Option<f64>,
359    /// Fee balance
360    #[serde(default)]
361    pub fee_balance: Option<f64>,
362    /// Margin model (e.g., "segregated_sm", "cross_pm")
363    #[serde(default)]
364    pub margin_model: Option<String>,
365    /// Cross collateral enabled
366    #[serde(default)]
367    pub cross_collateral_enabled: Option<bool>,
368    /// Account creation timestamp (milliseconds since UNIX epoch)
369    #[serde(default)]
370    pub creation_timestamp: Option<i64>,
371    /// Whether login is enabled for this account
372    #[serde(default)]
373    pub login_enabled: Option<bool>,
374    /// Whether security keys are enabled
375    #[serde(default)]
376    pub security_keys_enabled: Option<bool>,
377    /// Whether MMP (Market Maker Protection) is enabled
378    #[serde(default)]
379    pub mmp_enabled: Option<bool>,
380    /// Whether inter-user transfers are enabled
381    #[serde(default)]
382    pub interuser_transfers_enabled: Option<bool>,
383    /// Self-trading reject mode
384    #[serde(default)]
385    pub self_trading_reject_mode: Option<String>,
386    /// Whether self-trading is extended to subaccounts
387    #[serde(default)]
388    pub self_trading_extended_to_subaccounts: Option<bool>,
389    /// Referrer ID (affiliation program)
390    #[serde(default)]
391    pub referrer_id: Option<String>,
392    /// Block RFQ self match prevention
393    #[serde(default)]
394    pub block_rfq_self_match_prevention: Option<bool>,
395}