deribit-http 0.7.0

HTTP REST API client for Deribit trading platform
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
//! Block trade models for the Deribit API.
//!
//! This module contains request and response types for block trade endpoints,
//! including executing, verifying, and managing block trades.

use serde::{Deserialize, Serialize};

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

impl std::fmt::Display for BlockTradeRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Maker => write!(f, "maker"),
            Self::Taker => write!(f, "taker"),
        }
    }
}

/// Direction of a trade (buy or sell).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TradeDirection {
    /// Buy direction
    Buy,
    /// Sell direction
    Sell,
}

impl std::fmt::Display for TradeDirection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Buy => write!(f, "buy"),
            Self::Sell => write!(f, "sell"),
        }
    }
}

/// Individual trade item within a block trade.
///
/// Represents a single leg of a block trade with instrument, price, amount, and direction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockTradeItem {
    /// Instrument name (e.g., "BTC-PERPETUAL", "BTC-28MAR25-100000-C")
    pub instrument_name: String,
    /// Price for the trade in base currency
    pub price: f64,
    /// Trade size. For perpetual and inverse futures, amount is in USD units.
    /// For options and linear futures, it is in the underlying base currency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<f64>,
    /// Direction of trade from the maker perspective
    pub direction: TradeDirection,
}

impl BlockTradeItem {
    /// Creates a new block trade item.
    ///
    /// # Arguments
    ///
    /// * `instrument_name` - The instrument name
    /// * `price` - The trade price
    /// * `amount` - The trade amount (optional)
    /// * `direction` - The trade direction
    #[must_use]
    pub fn new(
        instrument_name: impl Into<String>,
        price: f64,
        amount: Option<f64>,
        direction: TradeDirection,
    ) -> Self {
        Self {
            instrument_name: instrument_name.into(),
            price,
            amount,
            direction,
        }
    }
}

/// Request parameters for executing a block trade.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecuteBlockTradeRequest {
    /// Timestamp shared with other party, in milliseconds since UNIX epoch
    pub timestamp: u64,
    /// Nonce shared with other party
    pub nonce: String,
    /// Role in the trade (maker or taker)
    pub role: BlockTradeRole,
    /// List of trades for the block trade
    pub trades: Vec<BlockTradeItem>,
    /// Signature from the counterparty generated by verify_block_trade
    pub counterparty_signature: String,
}

/// Request parameters for verifying a block trade.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VerifyBlockTradeRequest {
    /// Timestamp shared with other party, in milliseconds since UNIX epoch
    pub timestamp: u64,
    /// Nonce shared with other party
    pub nonce: String,
    /// Role in the trade (maker or taker)
    pub role: BlockTradeRole,
    /// List of trades for the block trade
    pub trades: Vec<BlockTradeItem>,
}

/// Request parameters for simulating a block trade.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SimulateBlockTradeRequest {
    /// Role in the trade (maker or taker), optional
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<BlockTradeRole>,
    /// List of trades for the block trade
    pub trades: Vec<BlockTradeItem>,
}

/// Request parameters for getting block trades with filters.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct GetBlockTradesRequest {
    /// Currency to filter by (e.g., "BTC", "ETH")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    /// Number of requested items (default: 20)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<u32>,
    /// Continuation token for pagination
    #[serde(skip_serializing_if = "Option::is_none")]
    pub continuation: Option<String>,
    /// Filter trades from this timestamp (milliseconds since UNIX epoch)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_timestamp: Option<u64>,
    /// Filter trades up to this timestamp (milliseconds since UNIX epoch)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_timestamp: Option<u64>,
}

/// Request parameters for getting block trade requests.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct GetBlockTradeRequestsParams {
    /// Broker code to filter by (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broker_code: Option<String>,
}

/// Detailed trade information within a block trade result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockTradeTradeInfo {
    /// Unique trade identifier
    pub trade_id: String,
    /// Trade sequence number
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trade_seq: Option<u64>,
    /// Timestamp in milliseconds since UNIX epoch
    pub timestamp: u64,
    /// Direction of the tick (0=Plus, 1=Zero-Plus, 2=Minus, 3=Zero-Minus)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tick_direction: Option<i32>,
    /// Order state
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    /// Whether this was a reduce-only trade
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reduce_only: Option<bool>,
    /// Trade price
    pub price: f64,
    /// Whether this was a post-only order
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_only: Option<bool>,
    /// Order type (limit, market, liquidation)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_type: Option<String>,
    /// Order ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<String>,
    /// Matching ID (always null for block trades)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub matching_id: Option<String>,
    /// Mark price at time of trade
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mark_price: Option<f64>,
    /// Liquidity indicator (M=maker, T=taker)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub liquidity: Option<String>,
    /// Implied volatility (options only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iv: Option<f64>,
    /// Instrument name
    pub instrument_name: String,
    /// Index price at time of trade
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index_price: Option<f64>,
    /// Fee currency
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fee_currency: Option<String>,
    /// Fee amount
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fee: Option<f64>,
    /// Trade direction
    pub direction: TradeDirection,
    /// Block trade ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub block_trade_id: Option<String>,
    /// Trade amount
    pub amount: f64,
    /// Underlying price (options only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub underlying_price: Option<f64>,
    /// Whether trade was created via API
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api: Option<bool>,
    /// Advanced order type (usd or implv, options only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub advanced: Option<String>,
    /// User-defined label
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Whether MMP was active
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mmp: Option<bool>,
    /// Quote ID (for mass_quote orders)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quote_id: Option<String>,
    /// Combo ID (for combo trades)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub combo_id: Option<String>,
    /// Profit and loss in base currency
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profit_loss: Option<f64>,
    /// Trade size in contract units
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contracts: Option<f64>,
    /// Block RFQ quote ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub block_rfq_quote_id: Option<u64>,
}

/// Block trade information returned from get_block_trade and get_block_trades.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockTrade {
    /// Block trade ID
    pub id: String,
    /// Timestamp in milliseconds since UNIX epoch
    pub timestamp: u64,
    /// List of trades in this block trade
    pub trades: Vec<BlockTradeTradeInfo>,
    /// Name of the application that executed the block trade (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app_name: Option<String>,
    /// Broker code associated with the trade
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broker_code: Option<String>,
    /// Broker name associated with the trade
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broker_name: Option<String>,
}

/// Result from executing a block trade.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockTradeResult {
    /// Block trade ID
    pub id: String,
    /// Timestamp in milliseconds since UNIX epoch
    pub timestamp: u64,
    /// List of executed trades
    pub trades: Vec<BlockTradeTradeInfo>,
}

/// Signature returned from verify_block_trade.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BlockTradeSignature {
    /// Block trade signature, valid for 5 minutes around the given timestamp
    pub signature: String,
}

/// Pending block trade request information.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockTradeRequest {
    /// Timestamp in milliseconds since UNIX epoch
    pub timestamp: u64,
    /// Nonce shared with other party
    pub nonce: String,
    /// Role expected for this request
    pub role: BlockTradeRole,
    /// List of trades in the request
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trades: Option<Vec<BlockTradeItem>>,
    /// Broker code (for broker requests)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub broker_code: Option<String>,
    /// Counterparty user ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub counterparty_user_id: Option<u64>,
    /// State of the request
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
}

/// Response for get_block_trades containing a list of block trades.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GetBlockTradesResponse {
    /// List of block trades
    pub block_trades: Vec<BlockTrade>,
    /// Continuation token for pagination
    #[serde(skip_serializing_if = "Option::is_none")]
    pub continuation: Option<String>,
}

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

    #[test]
    fn test_block_trade_role_serialization() {
        assert_eq!(
            serde_json::to_string(&BlockTradeRole::Maker).unwrap(),
            r#""maker""#
        );
        assert_eq!(
            serde_json::to_string(&BlockTradeRole::Taker).unwrap(),
            r#""taker""#
        );
    }

    #[test]
    fn test_block_trade_role_deserialization() {
        assert_eq!(
            serde_json::from_str::<BlockTradeRole>(r#""maker""#).unwrap(),
            BlockTradeRole::Maker
        );
        assert_eq!(
            serde_json::from_str::<BlockTradeRole>(r#""taker""#).unwrap(),
            BlockTradeRole::Taker
        );
    }

    #[test]
    fn test_trade_direction_serialization() {
        assert_eq!(
            serde_json::to_string(&TradeDirection::Buy).unwrap(),
            r#""buy""#
        );
        assert_eq!(
            serde_json::to_string(&TradeDirection::Sell).unwrap(),
            r#""sell""#
        );
    }

    #[test]
    fn test_block_trade_item_serialization() {
        let item = BlockTradeItem::new("BTC-PERPETUAL", 50000.0, Some(100.0), TradeDirection::Buy);
        let json = serde_json::to_string(&item).unwrap();
        assert!(json.contains("BTC-PERPETUAL"));
        assert!(json.contains("50000"));
        assert!(json.contains("buy"));
    }

    #[test]
    fn test_execute_block_trade_request_serialization() {
        let request = ExecuteBlockTradeRequest {
            timestamp: 1565172650935,
            nonce: "test_nonce".to_string(),
            role: BlockTradeRole::Maker,
            trades: vec![BlockTradeItem::new(
                "BTC-PERPETUAL",
                50000.0,
                Some(100.0),
                TradeDirection::Buy,
            )],
            counterparty_signature: "sig123".to_string(),
        };
        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("1565172650935"));
        assert!(json.contains("test_nonce"));
        assert!(json.contains("maker"));
        assert!(json.contains("sig123"));
    }

    #[test]
    fn test_verify_block_trade_request_serialization() {
        let request = VerifyBlockTradeRequest {
            timestamp: 1565172650935,
            nonce: "test_nonce".to_string(),
            role: BlockTradeRole::Taker,
            trades: vec![BlockTradeItem::new(
                "ETH-PERPETUAL",
                3000.0,
                Some(50.0),
                TradeDirection::Sell,
            )],
        };
        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("taker"));
        assert!(json.contains("ETH-PERPETUAL"));
    }

    #[test]
    fn test_block_trade_signature_deserialization() {
        let json = r#"{"signature":"1565172710935.1ESE83qh.abc123"}"#;
        let sig: BlockTradeSignature = serde_json::from_str(json).unwrap();
        assert_eq!(sig.signature, "1565172710935.1ESE83qh.abc123");
    }

    #[test]
    fn test_block_trade_deserialization() {
        let json = r#"{
            "id": "61",
            "timestamp": 1565089523720,
            "trades": [
                {
                    "trade_id": "92437",
                    "timestamp": 1565089523719,
                    "price": 0.0001,
                    "instrument_name": "BTC-9AUG19-10250-C",
                    "direction": "sell",
                    "amount": 10
                }
            ],
            "broker_code": "ABC123"
        }"#;
        let trade: BlockTrade = serde_json::from_str(json).unwrap();
        assert_eq!(trade.id, "61");
        assert_eq!(trade.trades.len(), 1);
        assert_eq!(trade.broker_code, Some("ABC123".to_string()));
    }

    #[test]
    fn test_get_block_trades_request_default() {
        let request = GetBlockTradesRequest::default();
        assert!(request.currency.is_none());
        assert!(request.count.is_none());
        assert!(request.continuation.is_none());
    }

    #[test]
    fn test_simulate_block_trade_request_serialization() {
        let request = SimulateBlockTradeRequest {
            role: Some(BlockTradeRole::Maker),
            trades: vec![BlockTradeItem::new(
                "BTC-PERPETUAL",
                50000.0,
                Some(40.0),
                TradeDirection::Buy,
            )],
        };
        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("maker"));
        assert!(json.contains("BTC-PERPETUAL"));
    }
}