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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 6/3/26
******************************************************************************/

//! Block trade data structures and types
//!
//! This module contains types for Deribit block trade operations,
//! supporting bilateral/OTC trading between counterparties.
//!
//! Block trades allow large trades to be executed off the order book
//! between two parties who have agreed on the terms.

use crate::model::order::OrderSide;
use pretty_simple_display::{DebugPretty, DisplaySimple};
use serde::{Deserialize, Serialize};

/// Role in a block trade
///
/// Indicates whether the party is the maker or taker in the block trade.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum BlockTradeRole {
    /// Maker role - the party initiating the trade
    #[default]
    Maker,
    /// Taker role - the party accepting the trade
    Taker,
}

impl BlockTradeRole {
    /// Get the string representation for API requests
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Maker => "maker",
            Self::Taker => "taker",
        }
    }
}

impl std::fmt::Display for BlockTradeRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Single trade leg for block trade request
///
/// Represents one instrument in a block trade, specifying the
/// instrument, price, amount, and direction.
#[derive(DebugPretty, DisplaySimple, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockTradeLeg {
    /// Instrument name (e.g., "BTC-PERPETUAL")
    pub instrument_name: String,
    /// Price for this leg
    pub price: f64,
    /// Trade amount (USD for perpetuals/inverse futures, base currency for options/linear)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<f64>,
    /// Direction from the maker's perspective
    pub direction: OrderSide,
}

impl BlockTradeLeg {
    /// Create a new block trade leg
    #[must_use]
    pub fn new(instrument_name: String, price: f64, amount: f64, direction: OrderSide) -> Self {
        Self {
            instrument_name,
            price,
            amount: Some(amount),
            direction,
        }
    }
}

/// Block trade verification request
///
/// Used to verify and generate a signature for a block trade
/// via `/private/verify_block_trade`.
#[derive(DebugPretty, DisplaySimple, Clone, PartialEq, Serialize, Deserialize)]
pub struct VerifyBlockTradeRequest {
    /// Timestamp shared with counterparty (milliseconds since Unix epoch)
    pub timestamp: i64,
    /// Nonce shared with counterparty
    pub nonce: String,
    /// Role in the block trade (maker/taker)
    pub role: BlockTradeRole,
    /// List of trade legs
    pub trades: Vec<BlockTradeLeg>,
}

impl VerifyBlockTradeRequest {
    /// Create a new verification request
    #[must_use]
    pub fn new(
        timestamp: i64,
        nonce: String,
        role: BlockTradeRole,
        trades: Vec<BlockTradeLeg>,
    ) -> Self {
        Self {
            timestamp,
            nonce,
            role,
            trades,
        }
    }
}

/// Block trade signature response
///
/// Contains the signature generated by `/private/verify_block_trade`.
/// The signature is valid for 5 minutes around the given timestamp.
#[derive(DebugPretty, DisplaySimple, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlockTradeSignature {
    /// Signature string for the block trade
    pub signature: String,
}

impl BlockTradeSignature {
    /// Create a new signature response
    #[must_use]
    pub fn new(signature: String) -> Self {
        Self { signature }
    }
}

/// Block trade execution request
///
/// Used to execute a block trade via `/private/execute_block_trade`.
/// The request must match exactly what was used in `verify_block_trade`,
/// with the counterparty's signature.
#[derive(DebugPretty, DisplaySimple, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecuteBlockTradeRequest {
    /// Timestamp shared with counterparty (milliseconds since Unix epoch)
    pub timestamp: i64,
    /// Nonce shared with counterparty
    pub nonce: String,
    /// Role in the block trade (maker/taker)
    pub role: BlockTradeRole,
    /// List of trade legs
    pub trades: Vec<BlockTradeLeg>,
    /// Signature from counterparty's verify_block_trade call
    pub counterparty_signature: String,
}

impl ExecuteBlockTradeRequest {
    /// Create a new execution request
    #[must_use]
    pub fn new(
        timestamp: i64,
        nonce: String,
        role: BlockTradeRole,
        trades: Vec<BlockTradeLeg>,
        counterparty_signature: String,
    ) -> Self {
        Self {
            timestamp,
            nonce,
            role,
            trades,
            counterparty_signature,
        }
    }

    /// Create from a verification request and counterparty signature
    #[must_use]
    pub fn from_verify_request(
        verify_request: VerifyBlockTradeRequest,
        counterparty_signature: String,
    ) -> Self {
        Self {
            timestamp: verify_request.timestamp,
            nonce: verify_request.nonce,
            role: verify_request.role,
            trades: verify_request.trades,
            counterparty_signature,
        }
    }
}

/// Individual trade execution within a block trade
///
/// Contains details of a single executed trade leg within a block trade.
#[derive(DebugPretty, DisplaySimple, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockTradeExecution {
    /// Unique trade identifier
    pub trade_id: String,
    /// Trade sequence number
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trade_seq: Option<i64>,
    /// Instrument name
    pub instrument_name: String,
    /// Trade direction (buy/sell)
    pub direction: String,
    /// Trade amount
    pub amount: f64,
    /// Execution price
    pub price: f64,
    /// Fee amount
    pub fee: f64,
    /// Fee currency (e.g., "BTC", "ETH")
    pub fee_currency: String,
    /// Order ID
    pub order_id: String,
    /// Order type (e.g., "limit")
    pub order_type: String,
    /// Liquidity indicator ("M" for maker, "T" for taker)
    pub liquidity: String,
    /// Index price at execution
    pub index_price: f64,
    /// Mark price at execution
    pub mark_price: f64,
    /// Block trade ID this execution belongs to
    pub block_trade_id: String,
    /// Execution timestamp in milliseconds
    pub timestamp: i64,
    /// Trade state (e.g., "filled")
    pub state: String,
    /// Tick direction (0=Plus, 1=Zero-Plus, 2=Minus, 3=Zero-Minus)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tick_direction: Option<i32>,
    /// Whether this was an API order
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api: Option<bool>,
    /// Post-only flag
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_only: Option<bool>,
    /// Reduce-only flag
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reduce_only: Option<bool>,
    /// Implied volatility (options only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iv: Option<f64>,
    /// Underlying price (options only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub underlying_price: Option<f64>,
    /// Trade label
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

/// Executed block trade
///
/// Contains the full details of an executed block trade,
/// returned by `/private/execute_block_trade` or `/private/get_block_trade`.
#[derive(DebugPretty, DisplaySimple, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockTrade {
    /// Block trade ID
    pub id: String,
    /// Execution timestamp in milliseconds
    pub timestamp: i64,
    /// List of executed trades in this block
    pub trades: Vec<BlockTradeExecution>,
    /// Application name that executed the block trade (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app_name: Option<String>,
    /// Broker code (for broker trades)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broker_code: Option<String>,
    /// Broker name (for broker trades)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broker_name: Option<String>,
}

impl BlockTrade {
    /// Get the total number of trades in this block
    #[must_use]
    pub fn trade_count(&self) -> usize {
        self.trades.len()
    }

    /// Check if this is a broker-facilitated block trade
    #[must_use]
    pub fn is_broker_trade(&self) -> bool {
        self.broker_code.is_some()
    }

    /// Get all unique instruments in this block trade
    #[must_use]
    pub fn instruments(&self) -> Vec<&str> {
        let mut instruments: Vec<&str> = self
            .trades
            .iter()
            .map(|t| t.instrument_name.as_str())
            .collect();
        instruments.sort();
        instruments.dedup();
        instruments
    }

    /// Calculate total fees across all trades
    #[must_use]
    pub fn total_fees(&self) -> f64 {
        self.trades.iter().map(|t| t.fee).sum()
    }
}

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

    #[test]
    fn test_block_trade_role_default() {
        let role = BlockTradeRole::default();
        assert_eq!(role, BlockTradeRole::Maker);
    }

    #[test]
    fn test_block_trade_role_as_str() {
        assert_eq!(BlockTradeRole::Maker.as_str(), "maker");
        assert_eq!(BlockTradeRole::Taker.as_str(), "taker");
    }

    #[test]
    fn test_block_trade_role_display() {
        assert_eq!(format!("{}", BlockTradeRole::Maker), "maker");
        assert_eq!(format!("{}", BlockTradeRole::Taker), "taker");
    }

    #[test]
    fn test_block_trade_role_serialization() {
        let maker = BlockTradeRole::Maker;
        let json = serde_json::to_string(&maker).unwrap();
        assert_eq!(json, "\"maker\"");

        let deserialized: BlockTradeRole = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, BlockTradeRole::Maker);
    }

    #[test]
    fn test_block_trade_leg_new() {
        let leg = BlockTradeLeg::new(
            "BTC-PERPETUAL".to_string(),
            50000.0,
            10000.0,
            OrderSide::Buy,
        );
        assert_eq!(leg.instrument_name, "BTC-PERPETUAL");
        assert!((leg.price - 50000.0).abs() < f64::EPSILON);
        assert_eq!(leg.amount, Some(10000.0));
        assert_eq!(leg.direction, OrderSide::Buy);
    }

    #[test]
    fn test_block_trade_leg_serialization() {
        let leg = BlockTradeLeg::new(
            "BTC-PERPETUAL".to_string(),
            50000.0,
            10000.0,
            OrderSide::Buy,
        );
        let json = serde_json::to_string(&leg).unwrap();
        let deserialized: BlockTradeLeg = serde_json::from_str(&json).unwrap();
        assert_eq!(leg, deserialized);
    }

    #[test]
    fn test_verify_block_trade_request_new() {
        let trades = vec![BlockTradeLeg::new(
            "BTC-PERPETUAL".to_string(),
            50000.0,
            10000.0,
            OrderSide::Buy,
        )];
        let request = VerifyBlockTradeRequest::new(
            1640995200000,
            "test_nonce".to_string(),
            BlockTradeRole::Maker,
            trades,
        );
        assert_eq!(request.timestamp, 1640995200000);
        assert_eq!(request.nonce, "test_nonce");
        assert_eq!(request.role, BlockTradeRole::Maker);
        assert_eq!(request.trades.len(), 1);
    }

    #[test]
    fn test_block_trade_signature_new() {
        let sig = BlockTradeSignature::new("test_signature_123".to_string());
        assert_eq!(sig.signature, "test_signature_123");
    }

    #[test]
    fn test_block_trade_signature_serialization() {
        let sig = BlockTradeSignature::new("test_signature_123".to_string());
        let json = serde_json::to_string(&sig).unwrap();
        let deserialized: BlockTradeSignature = serde_json::from_str(&json).unwrap();
        assert_eq!(sig, deserialized);
    }

    #[test]
    fn test_execute_block_trade_request_new() {
        let trades = vec![BlockTradeLeg::new(
            "BTC-PERPETUAL".to_string(),
            50000.0,
            10000.0,
            OrderSide::Buy,
        )];
        let request = ExecuteBlockTradeRequest::new(
            1640995200000,
            "test_nonce".to_string(),
            BlockTradeRole::Maker,
            trades,
            "counterparty_sig".to_string(),
        );
        assert_eq!(request.timestamp, 1640995200000);
        assert_eq!(request.counterparty_signature, "counterparty_sig");
    }

    #[test]
    fn test_execute_block_trade_request_from_verify() {
        let trades = vec![BlockTradeLeg::new(
            "BTC-PERPETUAL".to_string(),
            50000.0,
            10000.0,
            OrderSide::Buy,
        )];
        let verify_request = VerifyBlockTradeRequest::new(
            1640995200000,
            "test_nonce".to_string(),
            BlockTradeRole::Maker,
            trades,
        );
        let exec_request = ExecuteBlockTradeRequest::from_verify_request(
            verify_request.clone(),
            "counterparty_sig".to_string(),
        );
        assert_eq!(exec_request.timestamp, verify_request.timestamp);
        assert_eq!(exec_request.nonce, verify_request.nonce);
        assert_eq!(exec_request.role, verify_request.role);
        assert_eq!(exec_request.counterparty_signature, "counterparty_sig");
    }

    fn create_test_block_trade_execution() -> BlockTradeExecution {
        BlockTradeExecution {
            trade_id: "48079573".to_string(),
            trade_seq: Some(30289730),
            instrument_name: "BTC-PERPETUAL".to_string(),
            direction: "sell".to_string(),
            amount: 200000.0,
            price: 8900.0,
            fee: -0.00561798,
            fee_currency: "BTC".to_string(),
            order_id: "4009043192".to_string(),
            order_type: "limit".to_string(),
            liquidity: "M".to_string(),
            index_price: 8900.45,
            mark_price: 8895.19,
            block_trade_id: "6165".to_string(),
            timestamp: 1590485535978,
            state: "filled".to_string(),
            tick_direction: Some(0),
            api: None,
            post_only: Some(false),
            reduce_only: Some(false),
            iv: None,
            underlying_price: None,
            label: None,
        }
    }

    #[test]
    fn test_block_trade_execution_serialization() {
        let exec = create_test_block_trade_execution();
        let json = serde_json::to_string(&exec).unwrap();
        let deserialized: BlockTradeExecution = serde_json::from_str(&json).unwrap();
        assert_eq!(exec.trade_id, deserialized.trade_id);
        assert_eq!(exec.instrument_name, deserialized.instrument_name);
    }

    #[test]
    fn test_block_trade_trade_count() {
        let block_trade = BlockTrade {
            id: "6165".to_string(),
            timestamp: 1590485535980,
            trades: vec![
                create_test_block_trade_execution(),
                create_test_block_trade_execution(),
            ],
            app_name: None,
            broker_code: None,
            broker_name: None,
        };
        assert_eq!(block_trade.trade_count(), 2);
    }

    #[test]
    fn test_block_trade_is_broker_trade() {
        let regular_trade = BlockTrade {
            id: "6165".to_string(),
            timestamp: 1590485535980,
            trades: vec![],
            app_name: None,
            broker_code: None,
            broker_name: None,
        };
        assert!(!regular_trade.is_broker_trade());

        let broker_trade = BlockTrade {
            id: "6165".to_string(),
            timestamp: 1590485535980,
            trades: vec![],
            app_name: None,
            broker_code: Some("BROKER123".to_string()),
            broker_name: Some("Test Broker".to_string()),
        };
        assert!(broker_trade.is_broker_trade());
    }

    #[test]
    fn test_block_trade_instruments() {
        let mut exec1 = create_test_block_trade_execution();
        exec1.instrument_name = "BTC-PERPETUAL".to_string();

        let mut exec2 = create_test_block_trade_execution();
        exec2.instrument_name = "BTC-28MAY20-9000-C".to_string();

        let block_trade = BlockTrade {
            id: "6165".to_string(),
            timestamp: 1590485535980,
            trades: vec![exec1, exec2],
            app_name: None,
            broker_code: None,
            broker_name: None,
        };

        let instruments = block_trade.instruments();
        assert_eq!(instruments.len(), 2);
        assert!(instruments.contains(&"BTC-PERPETUAL"));
        assert!(instruments.contains(&"BTC-28MAY20-9000-C"));
    }

    #[test]
    fn test_block_trade_total_fees() {
        let mut exec1 = create_test_block_trade_execution();
        exec1.fee = 0.001;

        let mut exec2 = create_test_block_trade_execution();
        exec2.fee = 0.002;

        let block_trade = BlockTrade {
            id: "6165".to_string(),
            timestamp: 1590485535980,
            trades: vec![exec1, exec2],
            app_name: None,
            broker_code: None,
            broker_name: None,
        };

        assert!((block_trade.total_fees() - 0.003).abs() < f64::EPSILON);
    }

    #[test]
    fn test_block_trade_serialization() {
        let block_trade = BlockTrade {
            id: "6165".to_string(),
            timestamp: 1590485535980,
            trades: vec![create_test_block_trade_execution()],
            app_name: Some("TestApp".to_string()),
            broker_code: None,
            broker_name: None,
        };
        let json = serde_json::to_string(&block_trade).unwrap();
        let deserialized: BlockTrade = serde_json::from_str(&json).unwrap();
        assert_eq!(block_trade.id, deserialized.id);
        assert_eq!(block_trade.app_name, deserialized.app_name);
    }
}