roshar-types 0.1.23

Type definitions for cryptocurrency exchange websocket messages
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
use chrono::DateTime;
use serde::{Deserialize, Serialize};

use crate::{DepthUpdate, LocalOrderBook, LocalOrderBookError, OrderBookState, Trade, Venue};

// Kraken Derivatives Book Structures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KrakenBookLevel {
    pub price: f64,
    pub qty: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KrakenBookSnapshotMessage {
    pub feed: String,
    pub product_id: String,
    pub timestamp: i64,
    pub seq: i64,
    #[serde(rename = "tickSize")]
    pub tick_size: Option<String>,
    pub bids: Vec<KrakenBookLevel>,
    pub asks: Vec<KrakenBookLevel>,
}

impl KrakenBookSnapshotMessage {
    pub fn is_snapshot(&self) -> bool {
        true
    }

    pub fn to_order_book_state(&self) -> OrderBookState {
        let mut book = OrderBookState::new(50);

        for level in &self.bids {
            if let Err(e) = book.set_bid(level.price, &level.qty.to_string()) {
                log::error!(
                    "Kraken: failed to set bid for {} at price {}: {}",
                    self.product_id,
                    level.price,
                    e
                );
            }
        }

        for level in &self.asks {
            if let Err(e) = book.set_ask(level.price, &level.qty.to_string()) {
                log::error!(
                    "Kraken: failed to set ask for {} at price {}: {}",
                    self.product_id,
                    level.price,
                    e
                );
            }
        }

        // Trim after all updates are processed
        book.trim();

        book
    }

    pub fn to_depth_snapshot_data(&self) -> crate::DepthSnapshotData {
        let bid_prices: Vec<String> = self.bids.iter().map(|b| b.price.to_string()).collect();
        let bid_sizes: Vec<String> = self.bids.iter().map(|b| b.qty.to_string()).collect();
        let ask_prices: Vec<String> = self.asks.iter().map(|a| a.price.to_string()).collect();
        let ask_sizes: Vec<String> = self.asks.iter().map(|a| a.qty.to_string()).collect();

        crate::DepthSnapshotData {
            bid_prices,
            bid_sizes,
            ask_prices,
            ask_sizes,
            time: self.timestamp as u64,
            time_ts: DateTime::from_timestamp_millis(self.timestamp).unwrap_or_default(),
            ticker: self.product_id.clone(),
            venue: Venue::Kraken,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KrakenBookDeltaMessage {
    pub feed: String,
    pub product_id: String,
    pub timestamp: i64,
    pub seq: i64,
    pub side: String, // "buy" or "sell"
    pub price: f64,
    pub qty: f64,
}

impl KrakenBookDeltaMessage {
    pub fn to_depth_update(&self) -> DepthUpdate {
        let side = match self.side.as_str() {
            "sell" => true, // ask side
            "buy" => false, // bid side
            _ => false,     // default to bid side if unknown
        };

        DepthUpdate {
            time: self.timestamp,
            exchange: Venue::Kraken.as_str().to_string(),
            side,
            coin: self.product_id.clone(),
            px: self.price,
            sz: self.qty,
        }
    }

    pub fn to_depth_updates(&self) -> Vec<DepthUpdate> {
        vec![self.to_depth_update()]
    }

    pub fn to_depth_update_data(&self) -> Vec<crate::DepthUpdateData> {
        vec![crate::DepthUpdateData {
            px: self.price.to_string(),
            qty: self.qty.to_string(),
            time: self.timestamp as u64,
            time_ts: DateTime::from_timestamp_millis(self.timestamp).unwrap_or_default(),
            ticker: self.product_id.clone(),
            meta: format!("{{\"seq\": {}, \"feed\": \"{}\"}}", self.seq, self.feed),
            side: self.side == "sell", // true for sell, false for buy
            venue: Venue::Kraken,
        }]
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct KrakenSubscribeMessage {
    pub event: String,
    pub feed: String,
    pub product_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KrakenSingleTrade {
    pub feed: String,
    pub product_id: String,
    pub uid: String,
    pub side: String, // "buy" or "sell"
    #[serde(rename = "type")]
    pub type_field: String, // "fill", "liquidation", "termination", or "block"
    pub seq: i64,
    pub time: i64,
    pub qty: f64,
    pub price: f64,
}

impl KrakenSingleTrade {
    pub fn to_trade(&self) -> Trade {
        Trade {
            time: self.time,
            exchange: Venue::Kraken.to_string(),
            side: self.side == "sell", // true for sell, false for buy
            coin: self.product_id.clone(),
            px: self.price,
            sz: self.qty,
        }
    }

    pub fn to_trade_data(&self) -> crate::TradeData {
        crate::TradeData {
            px: self.price.to_string(),
            qty: self.qty.to_string(),
            time: self.time as u64,
            time_ts: DateTime::from_timestamp_millis(self.time).unwrap_or_default(),
            ticker: self.product_id.clone(),
            meta: format!(
                "{{\"uid\": \"{}\", \"seq\": {}, \"type\": \"{}\"}}",
                self.uid, self.seq, self.type_field
            ),
            side: self.side == "sell", // true for sell, false for buy
            venue: Venue::Kraken,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KrakenTradeSnapshotMessage {
    pub feed: String,
    pub product_id: String,
    pub trades: Vec<KrakenSingleTrade>,
}

impl KrakenTradeSnapshotMessage {
    pub fn to_trades(&self) -> Vec<Trade> {
        self.trades.iter().map(|t| t.to_trade()).collect()
    }

    pub fn to_trade_data(&self) -> Vec<crate::TradeData> {
        self.trades.iter().map(|t| t.to_trade_data()).collect()
    }
}

// Use SingleTrade as TradeDeltaMessage to avoid duplication
pub type KrakenTradeDeltaMessage = KrakenSingleTrade;

// WebSocket Message Type
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct KrakenWssMessage {
    pub event: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_ids: Option<Vec<String>>,
}

impl KrakenWssMessage {
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).expect("failed to serialize KrakenWssMessage")
    }

    pub fn ping() -> Self {
        Self {
            event: "ping".to_string(),
            feed: None,
            product_ids: None,
        }
    }

    pub fn depth(product_id: &str) -> Self {
        Self {
            event: "subscribe".to_string(),
            feed: Some("book".to_string()),
            product_ids: Some(vec![product_id.to_string()]),
        }
    }

    pub fn depth_unsub(product_id: &str) -> Self {
        Self {
            event: "unsubscribe".to_string(),
            feed: Some("book".to_string()),
            product_ids: Some(vec![product_id.to_string()]),
        }
    }

    pub fn trades(product_id: &str) -> Self {
        Self {
            event: "subscribe".to_string(),
            feed: Some("trade".to_string()),
            product_ids: Some(vec![product_id.to_string()]),
        }
    }

    pub fn trades_unsub(product_id: &str) -> Self {
        Self {
            event: "unsubscribe".to_string(),
            feed: Some("trade".to_string()),
            product_ids: Some(vec![product_id.to_string()]),
        }
    }
}

// Order book management
pub struct KrakenOrderBook {
    pub symbol: String,
    pub book: Option<OrderBookState>,
    pub counter: i64,
}

impl KrakenOrderBook {
    pub fn new(symbol: String) -> Self {
        Self {
            symbol,
            book: None,
            counter: 0,
        }
    }

    /// Get a read-only view of the order book for calculations
    pub fn as_view(&self) -> Option<LocalOrderBook<'_>> {
        self.book.as_ref().map(|b| b.as_view())
    }

    pub fn new_update(&mut self, msg: &KrakenBookDeltaMessage) -> Result<(), LocalOrderBookError> {
        let coin = &msg.product_id;

        // Validate symbol
        if coin != &self.symbol {
            return Err(LocalOrderBookError::WrongSymbol(
                self.symbol.clone(),
                coin.clone(),
            ));
        }

        if self.book.is_some() {
            let msg_seq = msg.seq;
            let expected_seq = self.counter + 1;
            if msg_seq == expected_seq {
                if let Some(ref mut book) = self.book {
                    // Apply update directly
                    let size_str = msg.qty.to_string();
                    if msg.side == "sell" {
                        if let Err(e) = book.set_ask(msg.price, &size_str) {
                            log::error!(
                                "Kraken: failed to set ask update for {} at price {}: {}",
                                coin,
                                msg.price,
                                e
                            );
                        }
                    } else if let Err(e) = book.set_bid(msg.price, &size_str) {
                        log::error!(
                            "Kraken: failed to set bid update for {} at price {}: {}",
                            coin,
                            msg.price,
                            e
                        );
                    }
                    // Trim after update
                    book.trim();
                    self.counter = msg_seq;
                }
            } else {
                return Err(LocalOrderBookError::OutOfOrderUpdate(
                    Venue::Kraken.to_string(),
                    coin.clone(),
                    expected_seq,
                    msg_seq,
                ));
            }
        } else {
            return Err(LocalOrderBookError::BookUpdateBeforeSnapshot(
                Venue::Kraken.to_string(),
                coin.clone(),
            ));
        }
        Ok(())
    }

    pub fn new_snapshot(&mut self, msg: &KrakenBookSnapshotMessage) {
        let coin = &msg.product_id;

        // Validate symbol
        if coin != &self.symbol {
            // Silently ignore snapshots for wrong symbols
            return;
        }

        self.counter = msg.seq;
        self.book = Some(msg.to_order_book_state());
    }
}

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

    fn create_test_snapshot_message(seq: i64, product_id: &str) -> KrakenBookSnapshotMessage {
        KrakenBookSnapshotMessage {
            feed: "book_snapshot".to_string(),
            product_id: product_id.to_string(),
            timestamp: 1234567890,
            seq,
            tick_size: Some("0.1".to_string()),
            bids: vec![
                KrakenBookLevel {
                    price: 50000.0,
                    qty: 1.0,
                },
                KrakenBookLevel {
                    price: 49999.0,
                    qty: 2.0,
                },
            ],
            asks: vec![
                KrakenBookLevel {
                    price: 50001.0,
                    qty: 1.5,
                },
                KrakenBookLevel {
                    price: 50002.0,
                    qty: 2.5,
                },
            ],
        }
    }

    fn create_test_delta_message(
        seq: i64,
        product_id: &str,
        side: &str,
        price: f64,
        qty: f64,
    ) -> KrakenBookDeltaMessage {
        KrakenBookDeltaMessage {
            feed: "book".to_string(),
            product_id: product_id.to_string(),
            timestamp: 1234567890 + seq,
            seq,
            side: side.to_string(),
            price,
            qty,
        }
    }

    #[test]
    fn test_kraken_order_book_snapshot_initialization() {
        let mut order_book = KrakenOrderBook::new("PI_XBTUSD".to_string());
        let snapshot = create_test_snapshot_message(1000, "PI_XBTUSD");

        order_book.new_snapshot(&snapshot);

        assert!(order_book.book.is_some());
        assert_eq!(order_book.counter, 1000);

        let view = order_book.as_view().unwrap();
        assert_eq!(view.bid_prices().len(), 2);
        assert_eq!(view.ask_prices().len(), 2);
        assert_eq!(view.bid_prices()[0], "50000");
        assert_eq!(view.ask_prices()[0], "50001");
    }

    #[test]
    fn test_kraken_order_book_in_sequence_updates() {
        let mut order_book = KrakenOrderBook::new("PI_XBTUSD".to_string());
        let snapshot = create_test_snapshot_message(1000, "PI_XBTUSD");
        order_book.new_snapshot(&snapshot);

        let delta1 = create_test_delta_message(1001, "PI_XBTUSD", "buy", 50003.0, 3.0);
        let delta2 = create_test_delta_message(1002, "PI_XBTUSD", "sell", 50004.0, 4.0);

        assert!(order_book.new_update(&delta1).is_ok());
        assert_eq!(order_book.counter, 1001);

        assert!(order_book.new_update(&delta2).is_ok());
        assert_eq!(order_book.counter, 1002);
    }

    #[test]
    fn test_kraken_order_book_update_before_snapshot_error() {
        let mut order_book = KrakenOrderBook::new("PI_XBTUSD".to_string());
        let delta = create_test_delta_message(1001, "PI_XBTUSD", "buy", 50003.0, 3.0);

        let result = order_book.new_update(&delta);
        assert!(result.is_err());
        if let Err(LocalOrderBookError::BookUpdateBeforeSnapshot(exchange, coin)) = result {
            assert_eq!(exchange, "kraken");
            assert_eq!(coin, "PI_XBTUSD");
        } else {
            panic!("Expected BookUpdateBeforeSnapshot error");
        }
    }

    #[test]
    fn test_kraken_order_book_wrong_symbol() {
        let mut order_book = KrakenOrderBook::new("PI_XBTUSD".to_string());
        let delta_eth = create_test_delta_message(1001, "PI_ETHUSD", "buy", 3000.0, 10.0);

        let result = order_book.new_update(&delta_eth);
        assert!(result.is_err());
        if let Err(LocalOrderBookError::WrongSymbol(expected, received)) = result {
            assert_eq!(expected, "PI_XBTUSD");
            assert_eq!(received, "PI_ETHUSD");
        } else {
            panic!("Expected WrongSymbol error");
        }
    }

    #[test]
    fn test_wss_message_ping() {
        let msg = KrakenWssMessage::ping();
        let json = msg.to_json();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["event"], "ping");
    }

    #[test]
    fn test_wss_message_depth() {
        let msg = KrakenWssMessage::depth("PI_XBTUSD");
        let json = msg.to_json();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["event"], "subscribe");
        assert_eq!(parsed["feed"], "book");
        assert_eq!(parsed["product_ids"][0], "PI_XBTUSD");
    }

    #[test]
    fn test_wss_message_trades() {
        let msg = KrakenWssMessage::trades("PI_XBTUSD");
        let json = msg.to_json();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["event"], "subscribe");
        assert_eq!(parsed["feed"], "trade");
        assert_eq!(parsed["product_ids"][0], "PI_XBTUSD");
    }
}