Skip to main content

deribit_http/model/response/
other.rs

1/******************************************************************************
2   Author: Joaquín Béjar García
3   Email: jb@taunais.com
4   Date: 15/9/25
5******************************************************************************/
6use crate::prelude::*;
7use pretty_simple_display::{DebugPretty, DisplaySimple};
8use serde::{Deserialize, Serialize};
9use serde_with::skip_serializing_none;
10
11/// Trading limit structure
12#[skip_serializing_none]
13#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
14pub struct TradingLimit {
15    /// Total rate limit for trading operations
16    pub total: RateLimit,
17}
18
19/// Account limits structure
20#[skip_serializing_none]
21#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
22pub struct AccountLimits {
23    /// Whether limits are applied per currency
24    pub limits_per_currency: bool,
25    /// Rate limits for non-matching engine operations
26    pub non_matching_engine: RateLimit,
27    /// Rate limits for matching engine operations
28    pub matching_engine: MatchingEngineLimit,
29}
30
31/// Rate limit structure
32#[skip_serializing_none]
33#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
34pub struct RateLimit {
35    /// Maximum burst capacity for rate limiting
36    pub burst: u32,
37    /// Rate limit per time unit
38    pub rate: u32,
39}
40
41/// Matching engine limits
42#[skip_serializing_none]
43#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
44pub struct MatchingEngineLimit {
45    /// Trading limits configuration
46    pub trading: TradingLimit,
47    /// Spot trading rate limits
48    pub spot: RateLimit,
49    /// Quote request rate limits
50    pub quotes: RateLimit,
51    /// Maximum quotes rate limits
52    pub max_quotes: RateLimit,
53    /// Guaranteed quotes rate limits
54    pub guaranteed_quotes: RateLimit,
55    /// Cancel all orders rate limits
56    pub cancel_all: RateLimit,
57}
58
59/// Response type for user trades, containing a vector of user trade data
60pub type UserTradeResponse = Vec<UserTrade>;
61
62/// Response type for user trades with pagination info (used by instrument-specific endpoints)
63#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
64pub struct UserTradeWithPaginationResponse {
65    /// List of user trades
66    pub trades: Vec<UserTrade>,
67    /// Whether there are more trades available
68    pub has_more: bool,
69}
70
71/// Contract size response
72#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
73pub struct ContractSizeResponse {
74    /// Contract size value
75    pub contract_size: f64,
76}
77
78/// Test response for connectivity checks
79#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
80pub struct TestResponse {
81    /// Version information
82    pub version: String,
83}
84
85/// Status response
86#[skip_serializing_none]
87#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
88pub struct StatusResponse {
89    /// Whether the system is locked (optional)
90    pub locked: Option<bool>,
91    /// Status message (optional)
92    pub message: Option<String>,
93    /// List of locked indices (optional)
94    pub locked_indices: Option<Vec<String>>,
95    /// Additional fields that might be present in the API response
96    #[serde(flatten)]
97    pub additional_fields: std::collections::HashMap<String, serde_json::Value>,
98}
99
100/// APR history response
101#[skip_serializing_none]
102#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
103pub struct AprHistoryResponse {
104    /// List of APR data points
105    pub data: Vec<AprDataPoint>,
106    /// Continuation token for pagination
107    pub continuation: Option<String>,
108}
109
110/// Hello response
111#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
112pub struct HelloResponse {
113    /// Version string
114    pub version: String,
115}
116
117/// Delivery prices response
118#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
119pub struct DeliveryPricesResponse {
120    /// List of delivery price data
121    pub data: Vec<DeliveryPriceData>,
122    /// Total number of records
123    pub records_total: u32,
124}
125
126/// APR data point
127#[skip_serializing_none]
128#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
129pub struct AprDataPoint {
130    /// Annual percentage rate
131    pub apr: f64,
132    /// Timestamp of the data point (optional)
133    pub timestamp: Option<u64>,
134    /// Day of the data point
135    pub day: i32,
136}
137
138/// Expirations response
139#[skip_serializing_none]
140#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
141pub struct ExpirationsResponse {
142    /// Direct future expirations (when currency="any")
143    pub future: Option<Vec<String>>,
144    /// Direct option expirations (when currency="any")
145    pub option: Option<Vec<String>>,
146    /// Map of currency to their expirations (when specific currency)
147    #[serde(flatten)]
148    pub currencies: std::collections::HashMap<String, CurrencyExpirations>,
149}
150
151/// Last trades response
152#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
153pub struct LastTradesResponse {
154    /// Whether there are more trades available
155    pub has_more: bool,
156    /// List of recent trades
157    pub trades: Vec<LastTrade>,
158}
159
160/// Settlements response structure
161#[skip_serializing_none]
162#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
163pub struct SettlementsResponse {
164    /// Continuation token for pagination
165    pub continuation: Option<String>,
166    /// List of settlement events
167    pub settlements: Vec<Settlement>,
168}
169
170impl SettlementsResponse {
171    /// Create a new settlements response
172    pub fn new(settlements: Vec<Settlement>) -> Self {
173        Self {
174            continuation: None,
175            settlements,
176        }
177    }
178
179    /// Create settlements response with continuation token
180    pub fn with_continuation(
181        settlements: Vec<crate::model::settlement::Settlement>,
182        continuation: String,
183    ) -> Self {
184        Self {
185            continuation: Some(continuation),
186            settlements,
187        }
188    }
189
190    /// Check if there are more results
191    pub fn has_more(&self) -> bool {
192        self.continuation.is_some()
193    }
194}
195
196/// Paginated transaction log response
197#[skip_serializing_none]
198#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize, Default)]
199pub struct TransactionLogResponse {
200    /// Continuation token for pagination. NULL when no continuation.
201    pub continuation: Option<u64>,
202    /// List of transaction log entries
203    pub logs: Vec<TransactionLogEntry>,
204}
205
206/// Transfer result for order-related transfers (e.g., fee rebates)
207#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
208pub struct TransferResultResponse {
209    /// Transfer identifier
210    pub id: String,
211    /// Transfer status
212    pub status: String,
213}
214
215/// Account summary response containing user account information
216#[skip_serializing_none]
217#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
218pub struct AccountSummaryResponse {
219    /// Account id
220    pub id: u64,
221    /// User email
222    pub email: String,
223    /// System generated user nickname
224    pub system_name: String,
225    /// Account name (given by user)
226    pub username: String,
227    /// When Block RFQ Self Match Prevention is enabled
228    pub block_rfq_self_match_prevention: bool,
229    /// Time at which the account was created (milliseconds since the Unix epoch)
230    pub creation_timestamp: u64,
231    /// Account type
232    #[serde(rename = "type")]
233    pub account_type: String,
234    /// Optional identifier of the referrer
235    pub referrer_id: Option<String>,
236    /// Whether account is loginable using email and password
237    pub login_enabled: bool,
238    /// Whether Security Key authentication is enabled
239    pub security_keys_enabled: bool,
240    /// Whether MMP is enabled
241    pub mmp_enabled: bool,
242    /// true when the inter-user transfers are enabled for user
243    pub interuser_transfers_enabled: bool,
244    /// Self trading rejection behavior - reject_taker or cancel_maker
245    pub self_trading_reject_mode: String,
246    /// true if self trading rejection behavior is applied to trades between subaccounts
247    pub self_trading_extended_to_subaccounts: bool,
248    /// Aggregated list of per-currency account summaries
249    pub summaries: Vec<AccountResult>,
250}
251
252/// Mark price history data point
253///
254/// Represents a single data point in mark price history.
255/// The API returns data as `[timestamp_ms, mark_price]` arrays.
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257#[serde(from = "(u64, f64)", into = "(u64, f64)")]
258pub struct MarkPriceHistoryPoint {
259    /// Timestamp in milliseconds since Unix epoch
260    pub timestamp: u64,
261    /// Mark price value
262    pub mark_price: f64,
263}
264
265impl From<(u64, f64)> for MarkPriceHistoryPoint {
266    fn from((timestamp, mark_price): (u64, f64)) -> Self {
267        Self {
268            timestamp,
269            mark_price,
270        }
271    }
272}
273
274impl From<MarkPriceHistoryPoint> for (u64, f64) {
275    fn from(point: MarkPriceHistoryPoint) -> Self {
276        (point.timestamp, point.mark_price)
277    }
278}
279
280/// Index name information with extended details
281///
282/// Represents an index with optional combo trading availability flags.
283/// Returned by `get_supported_index_names` when `extended=true`.
284#[skip_serializing_none]
285#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
286pub struct IndexNameInfo {
287    /// Index name identifier (e.g., "btc_eth", "btc_usdc")
288    pub name: String,
289    /// Whether future combo creation is enabled for this index
290    pub future_combo_enabled: Option<bool>,
291    /// Whether option combo creation is enabled for this index
292    pub option_combo_enabled: Option<bool>,
293}
294
295/// Aggregated trade volume by currency
296///
297/// Contains 24-hour trade volumes for different instrument types.
298/// When `extended=true`, also includes 7-day and 30-day volumes.
299#[skip_serializing_none]
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301pub struct TradeVolume {
302    /// Currency (e.g., "BTC", "ETH", "USDC")
303    pub currency: String,
304    /// Total 24h trade volume for call options
305    pub calls_volume: f64,
306    /// Total 24h trade volume for put options
307    pub puts_volume: f64,
308    /// Total 24h trade volume for futures
309    pub futures_volume: f64,
310    /// Total 24h trade volume for spot
311    pub spot_volume: f64,
312    /// Total 7d trade volume for call options (extended only)
313    pub calls_volume_7d: Option<f64>,
314    /// Total 7d trade volume for put options (extended only)
315    pub puts_volume_7d: Option<f64>,
316    /// Total 7d trade volume for futures (extended only)
317    pub futures_volume_7d: Option<f64>,
318    /// Total 7d trade volume for spot (extended only)
319    pub spot_volume_7d: Option<f64>,
320    /// Total 30d trade volume for call options (extended only)
321    pub calls_volume_30d: Option<f64>,
322    /// Total 30d trade volume for put options (extended only)
323    pub puts_volume_30d: Option<f64>,
324    /// Total 30d trade volume for futures (extended only)
325    pub futures_volume_30d: Option<f64>,
326    /// Total 30d trade volume for spot (extended only)
327    pub spot_volume_30d: Option<f64>,
328}
329
330/// A single volatility index candle
331///
332/// Represents OHLC data for a volatility index at a specific timestamp.
333#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
334pub struct VolatilityIndexCandle {
335    /// Timestamp in milliseconds since UNIX epoch
336    pub timestamp: u64,
337    /// Open value
338    pub open: f64,
339    /// High value
340    pub high: f64,
341    /// Low value
342    pub low: f64,
343    /// Close value
344    pub close: f64,
345}
346
347/// Response from get_volatility_index_data
348///
349/// Contains volatility index candles and optional continuation token.
350#[skip_serializing_none]
351#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
352pub struct VolatilityIndexData {
353    /// Candles as OHLC data
354    #[serde(deserialize_with = "deserialize_candles")]
355    pub data: Vec<VolatilityIndexCandle>,
356    /// Continuation token for pagination (use as end_timestamp for next request)
357    pub continuation: Option<u64>,
358}
359
360/// Deserialize candles from array of arrays format
361fn deserialize_candles<'de, D>(deserializer: D) -> Result<Vec<VolatilityIndexCandle>, D::Error>
362where
363    D: serde::Deserializer<'de>,
364{
365    use serde::de::Error;
366    let raw: Vec<Vec<serde_json::Value>> = Vec::deserialize(deserializer)?;
367    let mut candles = Vec::with_capacity(raw.len());
368
369    for arr in raw {
370        if arr.len() != 5 {
371            return Err(D::Error::custom(format!(
372                "expected 5 elements in candle array, got {}",
373                arr.len()
374            )));
375        }
376        let timestamp = arr[0]
377            .as_u64()
378            .ok_or_else(|| D::Error::custom("invalid timestamp"))?;
379        let open = arr[1]
380            .as_f64()
381            .ok_or_else(|| D::Error::custom("invalid open"))?;
382        let high = arr[2]
383            .as_f64()
384            .ok_or_else(|| D::Error::custom("invalid high"))?;
385        let low = arr[3]
386            .as_f64()
387            .ok_or_else(|| D::Error::custom("invalid low"))?;
388        let close = arr[4]
389            .as_f64()
390            .ok_or_else(|| D::Error::custom("invalid close"))?;
391
392        candles.push(VolatilityIndexCandle {
393            timestamp,
394            open,
395            high,
396            low,
397            close,
398        });
399    }
400
401    Ok(candles)
402}
403
404/// Account summary information
405#[skip_serializing_none]
406#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
407pub struct AccountResult {
408    /// Currency of the summary
409    pub currency: String,
410    /// The account's balance
411    pub balance: f64,
412    /// The account's current equity
413    pub equity: f64,
414    /// The account's available funds
415    pub available_funds: f64,
416    /// The account's margin balance
417    pub margin_balance: f64,
418    /// Profit and loss
419    pub total_pl: Option<f64>,
420    /// Session realized profit and loss
421    pub session_rpl: Option<f64>,
422    /// Session unrealized profit and loss
423    pub session_upl: Option<f64>,
424    /// The maintenance margin
425    pub maintenance_margin: f64,
426    /// The account's initial margin
427    pub initial_margin: f64,
428    /// The account's available to withdrawal funds
429    pub available_withdrawal_funds: Option<f64>,
430    /// When true cross collateral is enabled for user
431    pub cross_collateral_enabled: Option<bool>,
432    /// The sum of position deltas
433    pub delta_total: Option<f64>,
434    /// Futures profit and Loss
435    pub futures_pl: Option<f64>,
436    /// Futures session realized profit and Loss
437    pub futures_session_rpl: Option<f64>,
438    /// Futures session unrealized profit and Loss
439    pub futures_session_upl: Option<f64>,
440    /// Options summary delta
441    pub options_delta: Option<f64>,
442    /// Options summary gamma
443    pub options_gamma: Option<f64>,
444    /// Options profit and Loss
445    pub options_pl: Option<f64>,
446    /// Options session realized profit and Loss
447    pub options_session_rpl: Option<f64>,
448    /// Options session unrealized profit and Loss
449    pub options_session_upl: Option<f64>,
450    /// Options summary theta
451    pub options_theta: Option<f64>,
452    /// Options summary vega
453    pub options_vega: Option<f64>,
454    /// true when portfolio margining is enabled for user
455    pub portfolio_margining_enabled: Option<bool>,
456    /// The sum of position deltas without positions that will expire during closest expiration
457    pub projected_delta_total: Option<f64>,
458    /// Projected initial margin
459    pub projected_initial_margin: Option<f64>,
460    /// Projected maintenance margin
461    pub projected_maintenance_margin: Option<f64>,
462    /// Delta total map (currency -> delta)
463    pub delta_total_map: Option<std::collections::HashMap<String, f64>>,
464    /// The deposit address for the account (if available)
465    pub deposit_address: Option<String>,
466    /// List of fee objects for all currency pairs and instrument types
467    pub fees: Option<Vec<FeeStructure>>,
468    /// Account limits structure
469    pub limits: Option<AccountLimits>,
470    /// Name of user's currently enabled margin model
471    pub margin_model: Option<String>,
472    /// Map of options' gammas per index
473    pub options_gamma_map: Option<std::collections::HashMap<String, f64>>,
474    /// Map of options' thetas per index
475    pub options_theta_map: Option<std::collections::HashMap<String, f64>>,
476    /// Map of options' vegas per index
477    pub options_vega_map: Option<std::collections::HashMap<String, f64>>,
478    /// Options value
479    pub options_value: Option<f64>,
480    /// The account's balance reserved in active spot orders
481    pub spot_reserve: Option<f64>,
482    /// Estimated Liquidation Ratio
483    pub estimated_liquidation_ratio: Option<f64>,
484    /// Estimated liquidation ratio map
485    pub estimated_liquidation_ratio_map: Option<std::collections::HashMap<String, f64>>,
486    /// The account's fee balance (it can be used to pay for fees)
487    pub fee_balance: Option<f64>,
488    /// The account's balance reserved in other orders
489    pub additional_reserve: Option<f64>,
490
491    // Additional fields for cross-collateral users
492    /// Optional field returned with value true when user has non block chain equity
493    pub has_non_block_chain_equity: Option<bool>,
494    /// The account's total margin balance in all cross collateral currencies, expressed in USD
495    pub total_margin_balance_usd: Option<f64>,
496    /// The account's total delta total in all cross collateral currencies, expressed in USD
497    pub total_delta_total_usd: Option<f64>,
498    /// The account's total initial margin in all cross collateral currencies, expressed in USD
499    pub total_initial_margin_usd: Option<f64>,
500    /// The account's total maintenance margin in all cross collateral currencies, expressed in USD
501    pub total_maintenance_margin_usd: Option<f64>,
502    /// The account's total equity in all cross collateral currencies, expressed in USD
503    pub total_equity_usd: Option<f64>,
504    /// System name for the account
505    pub system_name: Option<String>,
506    /// Account type
507    pub account_type: Option<String>,
508}