deribit-base 0.3.1

Base library with common structs, traits, and logic for Deribit API clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 21/7/25
******************************************************************************/
use pretty_simple_display::{DebugPretty, DisplaySimple};
use serde::{Deserialize, Serialize};

/// Account summary information
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
pub struct AccountSummary {
    /// Account currency (kept as Currencies enum for compatibility)
    pub currency: String,
    /// Total balance
    pub balance: f64,
    /// Account equity
    pub equity: f64,
    /// Available funds for trading
    pub available_funds: f64,
    /// Margin balance
    pub margin_balance: f64,
    /// Unrealized profit and loss
    pub unrealized_pnl: f64,
    /// Realized profit and loss
    pub realized_pnl: f64,
    /// Total profit and loss
    pub total_pl: f64,
    /// Session funding
    pub session_funding: f64,
    /// Session realized P&L
    pub session_rpl: f64,
    /// Session unrealized P&L
    pub session_upl: f64,
    /// Maintenance margin requirement
    pub maintenance_margin: f64,
    /// Initial margin requirement
    pub initial_margin: f64,
    /// Available withdrawal funds
    pub available_withdrawal_funds: Option<f64>,
    /// Cross collateral enabled
    pub cross_collateral_enabled: Option<bool>,
    /// Delta total
    pub delta_total: Option<f64>,
    /// Futures profit and loss
    pub futures_pl: Option<f64>,
    /// Futures session realized profit and loss
    pub futures_session_rpl: Option<f64>,
    /// Futures session unrealized profit and loss
    pub futures_session_upl: Option<f64>,
    /// Options delta
    pub options_delta: Option<f64>,
    /// Options gamma
    pub options_gamma: Option<f64>,
    /// Options profit and loss
    pub options_pl: Option<f64>,
    /// Options session realized profit and loss
    pub options_session_rpl: Option<f64>,
    /// Options session unrealized profit and loss
    pub options_session_upl: Option<f64>,
    /// Options theta
    pub options_theta: Option<f64>,
    /// Options vega
    pub options_vega: Option<f64>,
    /// Portfolio margin enabled
    pub portfolio_margining_enabled: Option<bool>,
    /// Projected delta total
    pub projected_delta_total: Option<f64>,
    /// Projected initial margin
    pub projected_initial_margin: Option<f64>,
    /// Projected maintenance margin
    pub projected_maintenance_margin: Option<f64>,
    /// System name
    pub system_name: Option<String>,
    /// Type of account
    #[serde(rename = "type")]
    pub account_type: String,
    // Additional fields from deribit-http types.rs
    /// Delta total map (currency -> delta)
    pub delta_total_map: std::collections::HashMap<String, f64>,
    /// Deposit address
    pub deposit_address: String,
    /// Fees structure
    pub fees: Vec<std::collections::HashMap<String, f64>>,
    /// Account limits
    pub limits: std::collections::HashMap<String, f64>,
}

impl AccountSummary {
    /// Calculate margin utilization as percentage
    pub fn margin_utilization(&self) -> f64 {
        if self.equity != 0.0 {
            (self.initial_margin / self.equity) * 100.0
        } else {
            0.0
        }
    }

    /// Calculate available margin
    pub fn available_margin(&self) -> f64 {
        self.equity - self.initial_margin
    }

    /// Check if account is at risk (high margin utilization)
    pub fn is_at_risk(&self, threshold: f64) -> bool {
        self.margin_utilization() > threshold
    }

    /// Calculate return on equity
    pub fn return_on_equity(&self) -> f64 {
        if self.equity != 0.0 {
            (self.total_pl / self.equity) * 100.0
        } else {
            0.0
        }
    }
}

/// Subaccount information
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
pub struct Subaccount {
    /// Subaccount email
    pub email: String,
    /// Subaccount ID
    pub id: u64,
    /// Whether login is enabled
    pub login_enabled: bool,
    /// Portfolio information (optional)
    pub portfolio: Option<PortfolioInfo>,
    /// Whether to receive notifications
    pub receive_notifications: bool,
    /// System name
    pub system_name: String,
    /// Time in force (optional)
    pub tif: Option<String>,
    /// Subaccount type
    #[serde(rename = "type")]
    pub subaccount_type: String,
    /// Username
    pub username: String,
}

/// Portfolio information
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
pub struct PortfolioInfo {
    /// Available funds
    pub available_funds: f64,
    /// Available withdrawal funds
    pub available_withdrawal_funds: f64,
    /// Balance
    pub balance: f64,
    /// Currency
    pub currency: String,
    /// Delta total
    pub delta_total: f64,
    /// Equity
    pub equity: f64,
    /// Initial margin
    pub initial_margin: f64,
    /// Maintenance margin
    pub maintenance_margin: f64,
    /// Margin balance
    pub margin_balance: f64,
    /// Session realized P&L
    pub session_rpl: f64,
    /// Session unrealized P&L
    pub session_upl: f64,
    /// Total P&L
    pub total_pl: f64,
}

/// Portfolio information
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
pub struct Portfolio {
    /// Currency of the portfolio
    pub currency: String,
    /// Account summaries for different currencies
    pub accounts: Vec<AccountSummary>,
    /// Total portfolio value in USD
    pub total_usd_value: Option<f64>,
    /// Cross-currency margin enabled
    pub cross_margin_enabled: bool,
}

impl Portfolio {
    /// Create a new empty portfolio
    pub fn new(currency: String) -> Self {
        Self {
            currency,
            accounts: Vec::new(),
            total_usd_value: None,
            cross_margin_enabled: false,
        }
    }

    /// Add an account summary to the portfolio
    pub fn add_account(&mut self, account: AccountSummary) {
        self.accounts.push(account);
    }

    /// Get account summary for a specific currency
    pub fn get_account(&self, currency: &String) -> Option<&AccountSummary> {
        self.accounts.iter().find(|acc| &acc.currency == currency)
    }

    /// Calculate total equity across all accounts
    pub fn total_equity(&self) -> f64 {
        self.accounts.iter().map(|acc| acc.equity).sum()
    }

    /// Calculate total unrealized PnL across all accounts
    pub fn total_unrealized_pnl(&self) -> f64 {
        self.accounts.iter().map(|acc| acc.unrealized_pnl).sum()
    }

    /// Calculate total realized PnL across all accounts
    pub fn total_realized_pnl(&self) -> f64 {
        self.accounts.iter().map(|acc| acc.realized_pnl).sum()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    fn create_test_account_summary() -> AccountSummary {
        AccountSummary {
            currency: "BTC".to_string(),
            balance: 1.5,
            equity: 1.4,
            available_funds: 1.2,
            margin_balance: 0.3,
            unrealized_pnl: -0.1,
            realized_pnl: 0.05,
            total_pl: -0.05,
            session_funding: 0.001,
            session_rpl: 0.02,
            session_upl: -0.08,
            maintenance_margin: 0.1,
            initial_margin: 0.2,
            available_withdrawal_funds: Some(1.0),
            cross_collateral_enabled: Some(true),
            delta_total: Some(0.5),
            futures_pl: Some(0.03),
            futures_session_rpl: Some(0.01),
            futures_session_upl: Some(-0.02),
            options_delta: Some(0.3),
            options_gamma: Some(0.05),
            options_pl: Some(-0.08),
            options_session_rpl: Some(0.01),
            options_session_upl: Some(-0.06),
            options_theta: Some(-0.02),
            options_vega: Some(0.1),
            portfolio_margining_enabled: Some(false),
            projected_delta_total: Some(0.6),
            projected_initial_margin: Some(0.25),
            projected_maintenance_margin: Some(0.12),
            system_name: Some("deribit".to_string()),
            account_type: "main".to_string(),
            delta_total_map: HashMap::new(),
            deposit_address: "bc1qtest123".to_string(),
            fees: vec![HashMap::new()],
            limits: HashMap::new(),
        }
    }

    #[test]
    fn test_account_summary_margin_utilization() {
        let account = create_test_account_summary();
        let utilization = account.margin_utilization();
        assert!((utilization - 14.285714285714286).abs() < 0.0001); // 0.2 / 1.4 * 100
    }

    #[test]
    fn test_account_summary_margin_utilization_zero_equity() {
        let mut account = create_test_account_summary();
        account.equity = 0.0;
        assert_eq!(account.margin_utilization(), 0.0);
    }

    #[test]
    fn test_account_summary_available_margin() {
        let account = create_test_account_summary();
        assert_eq!(account.available_margin(), 1.2); // 1.4 - 0.2
    }

    #[test]
    fn test_account_summary_is_at_risk() {
        let account = create_test_account_summary();
        assert!(!account.is_at_risk(20.0)); // 14.28% < 20%
        assert!(account.is_at_risk(10.0)); // 14.28% > 10%
    }

    #[test]
    fn test_account_summary_return_on_equity() {
        let account = create_test_account_summary();
        let roe = account.return_on_equity();
        assert!((roe - (-3.571428571428571)).abs() < 0.0001); // -0.05 / 1.4 * 100
    }

    #[test]
    fn test_account_summary_return_on_equity_zero_equity() {
        let mut account = create_test_account_summary();
        account.equity = 0.0;
        assert_eq!(account.return_on_equity(), 0.0);
    }

    #[test]
    fn test_portfolio_new() {
        let portfolio = Portfolio::new("USD".to_string());
        assert_eq!(portfolio.currency, "USD");
        assert!(portfolio.accounts.is_empty());
        assert_eq!(portfolio.total_usd_value, None);
        assert!(!portfolio.cross_margin_enabled);
    }

    #[test]
    fn test_portfolio_add_account() {
        let mut portfolio = Portfolio::new("USD".to_string());
        let account = create_test_account_summary();
        portfolio.add_account(account);
        assert_eq!(portfolio.accounts.len(), 1);
    }

    #[test]
    fn test_portfolio_get_account() {
        let mut portfolio = Portfolio::new("USD".to_string());
        let account = create_test_account_summary();
        portfolio.add_account(account);

        let found = portfolio.get_account(&"BTC".to_string());
        assert!(found.is_some());
        assert_eq!(found.unwrap().currency, "BTC");

        let not_found = portfolio.get_account(&"ETH".to_string());
        assert!(not_found.is_none());
    }

    #[test]
    fn test_portfolio_total_equity() {
        let mut portfolio = Portfolio::new("USD".to_string());
        let mut account1 = create_test_account_summary();
        account1.equity = 1.0;
        let mut account2 = create_test_account_summary();
        account2.equity = 2.0;

        portfolio.add_account(account1);
        portfolio.add_account(account2);

        assert_eq!(portfolio.total_equity(), 3.0);
    }

    #[test]
    fn test_portfolio_total_unrealized_pnl() {
        let mut portfolio = Portfolio::new("USD".to_string());
        let mut account1 = create_test_account_summary();
        account1.unrealized_pnl = 0.1;
        let mut account2 = create_test_account_summary();
        account2.unrealized_pnl = -0.2;

        portfolio.add_account(account1);
        portfolio.add_account(account2);

        assert_eq!(portfolio.total_unrealized_pnl(), -0.1);
    }

    #[test]
    fn test_portfolio_total_realized_pnl() {
        let mut portfolio = Portfolio::new("USD".to_string());
        let mut account1 = create_test_account_summary();
        account1.realized_pnl = 0.05;
        let mut account2 = create_test_account_summary();
        account2.realized_pnl = 0.03;

        portfolio.add_account(account1);
        portfolio.add_account(account2);

        assert_eq!(portfolio.total_realized_pnl(), 0.08);
    }

    #[test]
    fn test_account_summary_serialization() {
        let account = create_test_account_summary();
        let json = serde_json::to_string(&account).unwrap();
        let deserialized: AccountSummary = serde_json::from_str(&json).unwrap();
        assert_eq!(account.currency, deserialized.currency);
        assert_eq!(account.balance, deserialized.balance);
    }

    #[test]
    fn test_portfolio_serialization() {
        let portfolio = Portfolio::new("USD".to_string());
        let json = serde_json::to_string(&portfolio).unwrap();
        let deserialized: Portfolio = serde_json::from_str(&json).unwrap();
        assert_eq!(portfolio.currency, deserialized.currency);
    }

    #[test]
    fn test_subaccount_creation() {
        let subaccount = Subaccount {
            email: "test@example.com".to_string(),
            id: 12345,
            login_enabled: true,
            portfolio: None,
            receive_notifications: false,
            system_name: "deribit".to_string(),
            tif: Some("GTC".to_string()),
            subaccount_type: "subaccount".to_string(),
            username: "testuser".to_string(),
        };

        assert_eq!(subaccount.email, "test@example.com");
        assert_eq!(subaccount.id, 12345);
        assert!(subaccount.login_enabled);
    }

    #[test]
    fn test_portfolio_info_creation() {
        let portfolio_info = PortfolioInfo {
            available_funds: 1000.0,
            available_withdrawal_funds: 900.0,
            balance: 1100.0,
            currency: "BTC".to_string(),
            delta_total: 0.5,
            equity: 1050.0,
            initial_margin: 100.0,
            maintenance_margin: 50.0,
            margin_balance: 150.0,
            session_rpl: 10.0,
            session_upl: -5.0,
            total_pl: 5.0,
        };

        assert_eq!(portfolio_info.currency, "BTC");
        assert_eq!(portfolio_info.balance, 1100.0);
    }

    #[test]
    fn test_debug_and_display_implementations() {
        let account = create_test_account_summary();
        let debug_str = format!("{:?}", account);
        let display_str = format!("{}", account);

        assert!(debug_str.contains("BTC"));
        assert!(display_str.contains("BTC"));
    }
}