orderbook-rs 0.6.2

A high-performance, lock-free price level implementation for limit order books in Rust. This library provides the building blocks for creating efficient trading systems with support for multiple order types and concurrent access patterns.
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
//! Pluggable event serialization for NATS publishers and consumers.
//!
//! This module provides the [`EventSerializer`] trait and two built-in
//! implementations:
//!
//! - [`JsonEventSerializer`] — human-readable JSON (always available)
//! - `BincodeEventSerializer` — compact binary format (requires the
//!   `bincode` feature)
//!
//! Publishers such as `NatsTradePublisher` (requires the `nats` feature)
//! accept any `Arc<dyn EventSerializer>` so the serialization format can be
//! chosen at construction time without changing downstream code.
//!
//! # Feature Gate
//!
//! The `BincodeEventSerializer` requires the `bincode` feature:
//!
//! ```toml
//! [dependencies]
//! orderbook-rs = { version = "0.6", features = ["bincode"] }
//! ```

use crate::orderbook::book_change_event::PriceLevelChangedEvent;
use crate::orderbook::trade::TradeResult;

/// Errors that can occur during event serialization or deserialization.
#[derive(Debug)]
pub struct SerializationError {
    /// Human-readable description of the failure.
    pub message: String,
}

impl std::fmt::Display for SerializationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "event serialization error: {}", self.message)
    }
}

impl std::error::Error for SerializationError {}

/// A pluggable serializer for order book events.
///
/// Implementations convert [`TradeResult`] and [`PriceLevelChangedEvent`]
/// to and from byte buffers. The format (JSON, Bincode, etc.) is an
/// implementation detail, allowing publishers and consumers to negotiate
/// the most efficient wire format.
///
/// # Thread Safety
///
/// Implementations must be `Send + Sync` so they can be shared across
/// async task boundaries via `Arc<dyn EventSerializer>`.
pub trait EventSerializer: Send + Sync + std::fmt::Debug {
    /// Serialize a [`TradeResult`] into a byte buffer.
    ///
    /// # Errors
    ///
    /// Returns [`SerializationError`] if the event cannot be serialized.
    fn serialize_trade(&self, trade: &TradeResult) -> Result<Vec<u8>, SerializationError>;

    /// Serialize a [`PriceLevelChangedEvent`] into a byte buffer.
    ///
    /// # Errors
    ///
    /// Returns [`SerializationError`] if the event cannot be serialized.
    fn serialize_book_change(
        &self,
        event: &PriceLevelChangedEvent,
    ) -> Result<Vec<u8>, SerializationError>;

    /// Deserialize a [`TradeResult`] from a byte buffer.
    ///
    /// # Errors
    ///
    /// Returns [`SerializationError`] if the bytes are malformed or
    /// incompatible with the expected format.
    fn deserialize_trade(&self, data: &[u8]) -> Result<TradeResult, SerializationError>;

    /// Deserialize a [`PriceLevelChangedEvent`] from a byte buffer.
    ///
    /// # Errors
    ///
    /// Returns [`SerializationError`] if the bytes are malformed or
    /// incompatible with the expected format.
    fn deserialize_book_change(
        &self,
        data: &[u8],
    ) -> Result<PriceLevelChangedEvent, SerializationError>;

    /// Returns the MIME-like content type identifier for this format.
    ///
    /// Consumers can use this value to select the correct deserializer.
    /// Examples: `"application/json"`, `"application/x-bincode"`.
    #[must_use]
    fn content_type(&self) -> &'static str;
}

// ─── JSON ───────────────────────────────────────────────────────────────────

/// JSON event serializer using `serde_json`.
///
/// This is the default serializer, producing human-readable JSON payloads.
/// It is always available (no feature gate) since `serde_json` is a
/// required dependency.
///
/// # Content Type
///
/// `"application/json"`
#[derive(Debug, Clone, Copy, Default)]
pub struct JsonEventSerializer;

impl JsonEventSerializer {
    /// Create a new JSON event serializer.
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self
    }
}

impl EventSerializer for JsonEventSerializer {
    fn serialize_trade(&self, trade: &TradeResult) -> Result<Vec<u8>, SerializationError> {
        serde_json::to_vec(trade).map_err(|e| SerializationError {
            message: e.to_string(),
        })
    }

    fn serialize_book_change(
        &self,
        event: &PriceLevelChangedEvent,
    ) -> Result<Vec<u8>, SerializationError> {
        serde_json::to_vec(event).map_err(|e| SerializationError {
            message: e.to_string(),
        })
    }

    fn deserialize_trade(&self, data: &[u8]) -> Result<TradeResult, SerializationError> {
        serde_json::from_slice(data).map_err(|e| SerializationError {
            message: e.to_string(),
        })
    }

    fn deserialize_book_change(
        &self,
        data: &[u8],
    ) -> Result<PriceLevelChangedEvent, SerializationError> {
        serde_json::from_slice(data).map_err(|e| SerializationError {
            message: e.to_string(),
        })
    }

    #[inline]
    fn content_type(&self) -> &'static str {
        "application/json"
    }
}

// ─── Bincode ────────────────────────────────────────────────────────────────

/// Bincode event serializer for compact binary payloads.
///
/// Produces significantly smaller payloads than JSON with much lower
/// serialization latency (typically < 500 ns per event). The trade-off
/// is that the output is not human-readable.
///
/// # Feature Gate
///
/// Requires the `bincode` feature:
///
/// ```toml
/// [dependencies]
/// orderbook-rs = { version = "0.6", features = ["bincode"] }
/// ```
///
/// # Content Type
///
/// `"application/x-bincode"`
#[cfg(feature = "bincode")]
#[derive(Debug, Clone, Copy, Default)]
pub struct BincodeEventSerializer;

#[cfg(feature = "bincode")]
impl BincodeEventSerializer {
    /// Create a new Bincode event serializer.
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self
    }
}

#[cfg(feature = "bincode")]
impl EventSerializer for BincodeEventSerializer {
    fn serialize_trade(&self, trade: &TradeResult) -> Result<Vec<u8>, SerializationError> {
        bincode::serde::encode_to_vec(trade, bincode::config::standard()).map_err(|e| {
            SerializationError {
                message: e.to_string(),
            }
        })
    }

    fn serialize_book_change(
        &self,
        event: &PriceLevelChangedEvent,
    ) -> Result<Vec<u8>, SerializationError> {
        bincode::serde::encode_to_vec(event, bincode::config::standard()).map_err(|e| {
            SerializationError {
                message: e.to_string(),
            }
        })
    }

    fn deserialize_trade(&self, data: &[u8]) -> Result<TradeResult, SerializationError> {
        let (value, bytes_read) =
            bincode::serde::decode_from_slice::<TradeResult, _>(data, bincode::config::standard())
                .map_err(|e| SerializationError {
                    message: e.to_string(),
                })?;
        if bytes_read != data.len() {
            return Err(SerializationError {
                message: format!(
                    "trailing bytes after trade payload: consumed {bytes_read} of {}",
                    data.len()
                ),
            });
        }
        Ok(value)
    }

    fn deserialize_book_change(
        &self,
        data: &[u8],
    ) -> Result<PriceLevelChangedEvent, SerializationError> {
        let (value, bytes_read) = bincode::serde::decode_from_slice::<PriceLevelChangedEvent, _>(
            data,
            bincode::config::standard(),
        )
        .map_err(|e| SerializationError {
            message: e.to_string(),
        })?;
        if bytes_read != data.len() {
            return Err(SerializationError {
                message: format!(
                    "trailing bytes after book-change payload: consumed {bytes_read} of {}",
                    data.len()
                ),
            });
        }
        Ok(value)
    }

    #[inline]
    fn content_type(&self) -> &'static str {
        "application/x-bincode"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pricelevel::{Id, MatchResult, Side};

    fn make_trade_result() -> TradeResult {
        let order_id = Id::new_uuid();
        let match_result = MatchResult::new(order_id, 100);
        TradeResult::new("BTC/USD".to_string(), match_result)
    }

    fn make_book_change() -> PriceLevelChangedEvent {
        PriceLevelChangedEvent {
            side: Side::Buy,
            price: 50_000_000,
            quantity: 1_000,
        }
    }

    // ─── JSON tests ─────────────────────────────────────────────────────

    #[test]
    fn test_json_serialize_trade() {
        let serializer = JsonEventSerializer::new();
        let trade = make_trade_result();
        let result = serializer.serialize_trade(&trade);
        assert!(result.is_ok());
        let bytes = result.unwrap_or_default();
        assert!(!bytes.is_empty());

        let json_str = String::from_utf8(bytes).unwrap_or_default();
        assert!(json_str.contains("BTC/USD"));
    }

    #[test]
    fn test_json_roundtrip_trade() {
        let serializer = JsonEventSerializer::new();
        let trade = make_trade_result();
        let bytes = serializer.serialize_trade(&trade);
        assert!(bytes.is_ok());
        let bytes = bytes.unwrap_or_default();

        let decoded = serializer.deserialize_trade(&bytes);
        assert!(decoded.is_ok());
        let decoded = decoded.unwrap_or_else(|_| make_trade_result());
        assert_eq!(decoded.symbol, trade.symbol);
        assert_eq!(decoded.total_maker_fees, trade.total_maker_fees);
        assert_eq!(decoded.total_taker_fees, trade.total_taker_fees);
    }

    #[test]
    fn test_json_serialize_book_change() {
        let serializer = JsonEventSerializer::new();
        let event = make_book_change();
        let result = serializer.serialize_book_change(&event);
        assert!(result.is_ok());
        let bytes = result.unwrap_or_default();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn test_json_roundtrip_book_change() {
        let serializer = JsonEventSerializer::new();
        let event = make_book_change();
        let bytes = serializer.serialize_book_change(&event);
        assert!(bytes.is_ok());
        let bytes = bytes.unwrap_or_default();

        let decoded = serializer.deserialize_book_change(&bytes);
        assert!(decoded.is_ok());
        let decoded = decoded.unwrap_or_else(|_| make_book_change());
        assert_eq!(decoded, event);
    }

    #[test]
    fn test_json_content_type() {
        let serializer = JsonEventSerializer::new();
        assert_eq!(serializer.content_type(), "application/json");
    }

    #[test]
    fn test_json_deserialize_trade_error() {
        let serializer = JsonEventSerializer::new();
        let result = serializer.deserialize_trade(b"not valid json");
        assert!(result.is_err());
    }

    #[test]
    fn test_json_deserialize_book_change_error() {
        let serializer = JsonEventSerializer::new();
        let result = serializer.deserialize_book_change(b"not valid json");
        assert!(result.is_err());
    }

    #[test]
    fn test_serialization_error_display() {
        let err = SerializationError {
            message: "test error".to_string(),
        };
        let display = format!("{err}");
        assert!(display.contains("event serialization error"));
        assert!(display.contains("test error"));
    }

    // ─── Bincode tests ──────────────────────────────────────────────────

    #[cfg(feature = "bincode")]
    mod bincode_tests {
        use super::*;

        #[test]
        fn test_bincode_serialize_trade() {
            let serializer = BincodeEventSerializer::new();
            let trade = make_trade_result();
            let result = serializer.serialize_trade(&trade);
            assert!(result.is_ok());
            let bytes = result.unwrap_or_default();
            assert!(!bytes.is_empty());

            // Bincode should be more compact than JSON
            let json_serializer = JsonEventSerializer::new();
            let json_bytes = json_serializer.serialize_trade(&trade).unwrap_or_default();
            assert!(
                bytes.len() < json_bytes.len(),
                "bincode ({}) should be smaller than json ({})",
                bytes.len(),
                json_bytes.len()
            );
        }

        #[test]
        fn test_bincode_roundtrip_trade() {
            let serializer = BincodeEventSerializer::new();
            let trade = make_trade_result();
            let bytes = serializer.serialize_trade(&trade);
            assert!(bytes.is_ok());
            let bytes = bytes.unwrap_or_default();

            let decoded = serializer.deserialize_trade(&bytes);
            assert!(decoded.is_ok());
            let decoded = decoded.unwrap_or_else(|_| make_trade_result());
            assert_eq!(decoded.symbol, trade.symbol);
            assert_eq!(decoded.total_maker_fees, trade.total_maker_fees);
            assert_eq!(decoded.total_taker_fees, trade.total_taker_fees);
        }

        #[test]
        fn test_bincode_serialize_book_change() {
            let serializer = BincodeEventSerializer::new();
            let event = make_book_change();
            let result = serializer.serialize_book_change(&event);
            assert!(result.is_ok());
            let bytes = result.unwrap_or_default();
            assert!(!bytes.is_empty());
        }

        #[test]
        fn test_bincode_roundtrip_book_change() {
            let serializer = BincodeEventSerializer::new();
            let event = make_book_change();
            let bytes = serializer.serialize_book_change(&event);
            assert!(bytes.is_ok());
            let bytes = bytes.unwrap_or_default();

            let decoded = serializer.deserialize_book_change(&bytes);
            assert!(decoded.is_ok());
            let decoded = decoded.unwrap_or_else(|_| make_book_change());
            assert_eq!(decoded, event);
        }

        #[test]
        fn test_bincode_content_type() {
            let serializer = BincodeEventSerializer::new();
            assert_eq!(serializer.content_type(), "application/x-bincode");
        }

        #[test]
        fn test_bincode_deserialize_trade_error() {
            let serializer = BincodeEventSerializer::new();
            let result = serializer.deserialize_trade(b"\x00\x01");
            assert!(result.is_err());
        }

        #[test]
        fn test_bincode_deserialize_book_change_error() {
            let serializer = BincodeEventSerializer::new();
            let result = serializer.deserialize_book_change(b"\x00\x01");
            assert!(result.is_err());
        }

        #[test]
        fn test_bincode_smaller_than_json_book_change() {
            let event = make_book_change();
            let bincode_ser = BincodeEventSerializer::new();
            let json_ser = JsonEventSerializer::new();

            let bin_bytes = bincode_ser
                .serialize_book_change(&event)
                .unwrap_or_default();
            let json_bytes = json_ser.serialize_book_change(&event).unwrap_or_default();

            assert!(
                bin_bytes.len() < json_bytes.len(),
                "bincode ({}) should be smaller than json ({})",
                bin_bytes.len(),
                json_bytes.len()
            );
        }
    }
}