pricelevel 0.7.0

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
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
#[cfg(test)]
mod tests {
    use crate::price_level::entry::OrderBookEntry;
    use crate::price_level::level::PriceLevel;
    use crate::utils::{Price, Quantity, TimestampMs};
    use crate::{Hash32, Id, OrderType, Side, TimeInForce};
    use std::str::FromStr;
    use std::sync::Arc;
    use tracing::info;

    #[test]
    fn test_display() {
        let level = Arc::new(PriceLevel::new(1000));
        let entry = OrderBookEntry::new(level.clone(), 5);

        let display_str = entry.to_string();
        info!("Display string: {}", display_str);

        assert!(display_str.starts_with("OrderBookEntry:"));
        assert!(display_str.contains("price=1000"));
        assert!(display_str.contains("index=5"));
    }

    #[test]
    fn test_from_str() {
        let input = "OrderBookEntry:price=1000;index=5";
        let entry = OrderBookEntry::from_str(input).unwrap();

        assert_eq!(entry.price(), 1000);
        assert_eq!(entry.index, 5);
    }

    #[test]
    fn test_roundtrip_display_parse() {
        let level = Arc::new(PriceLevel::new(1000));
        let original = OrderBookEntry::new(level.clone(), 5);

        let string_rep = original.to_string();
        let parsed = OrderBookEntry::from_str(&string_rep).unwrap();

        assert_eq!(original.price(), parsed.price());
        assert_eq!(original.index, parsed.index);
    }

    #[test]
    fn test_serialization() {
        use serde_json;

        let level = Arc::new(PriceLevel::new(1000));
        let entry = OrderBookEntry::new(level.clone(), 5);

        let serialized = serde_json::to_string(&entry).unwrap();
        info!("Serialized: {}", serialized);

        // Verify basic structure of JSON
        assert!(serialized.contains("\"price\":1000"));
        assert!(serialized.contains("\"index\":5"));
    }

    #[test]
    fn test_deserialization() {
        use serde_json;

        let json = r#"{"price":1000,"index":5}"#;
        let entry: OrderBookEntry = serde_json::from_str(json).unwrap();

        assert_eq!(entry.price(), 1000);
        assert_eq!(entry.index, 5);
    }

    #[test]
    fn test_order_book_entry_json_serialization() {
        let level = Arc::new(PriceLevel::new(10000));
        let entry = OrderBookEntry::new(level, 5);

        // Serialize to JSON
        let json = serde_json::to_string(&entry).unwrap();

        // Check JSON structure
        assert!(json.contains("\"price\":10000"));
        assert!(json.contains("\"index\":5"));
        assert!(json.contains("\"visible_quantity\":0"));
        assert!(json.contains("\"total_quantity\":0"));
    }

    #[test]
    fn test_order_book_entry_wrapper_struct() {
        // Directly test the wrapper struct used for deserialization
        #[derive(serde::Deserialize)]
        struct Wrapper {
            price: u64,
            index: usize,
        }

        let json = r#"{"price":10000,"index":5}"#;
        let wrapper: Wrapper = serde_json::from_str(json).unwrap();

        assert_eq!(wrapper.price, 10000);
        assert_eq!(wrapper.index, 5);
    }

    #[test]
    fn test_order_book_entry_equality_hash() {
        // Test line 76 - Testing Eq trait implementation
        let level1 = Arc::new(PriceLevel::new(1000));
        let level2 = Arc::new(PriceLevel::new(1000));

        let entry1 = OrderBookEntry::new(level1.clone(), 1);
        let entry2 = OrderBookEntry::new(level2.clone(), 2);

        // Test Eq trait implementation
        assert_eq!(entry1, entry2); // They should be equal as they have the same price

        // Create a hash set to test the Eq trait's blanket implementation
        let mut set = std::collections::HashSet::new();
        set.insert(entry1.price());
        assert!(set.contains(&entry2.price()));
    }

    #[test]
    fn test_order_book_entry_serialization() {
        // Test lines 100, 102-104 - Serialize implementation
        let level = Arc::new(PriceLevel::new(1000));
        let entry = OrderBookEntry::new(level.clone(), 5);

        // Add an order to make the test more meaningful
        let order = OrderType::Standard {
            id: Id::from_u64(1),
            price: Price::new(1000),
            quantity: Quantity::new(10),
            side: Side::Buy,
            user_id: Hash32::zero(),
            timestamp: TimestampMs::new(1616823000000),
            time_in_force: TimeInForce::Gtc,
            extra_fields: (),
        };
        level.add_order(order);

        // Serialize the entry
        let json = serde_json::to_string(&entry).unwrap();

        // Verify the serialized output contains expected fields
        assert!(json.contains("\"price\":1000"));
        assert!(json.contains("\"visible_quantity\":10"));
        assert!(json.contains("\"total_quantity\":10"));
        assert!(json.contains("\"index\":5"));
    }

    #[test]
    fn test_order_book_entry_deserialization() {
        // Test lines 130, 144, 152-153, 161-162 - Deserialize implementation
        let json = r#"{"price":1500,"index":10,"visible_quantity":50,"total_quantity":150}"#;

        // Deserialize into OrderBookEntry
        let entry: OrderBookEntry = serde_json::from_str(json).unwrap();

        // Verify deserialized values
        assert_eq!(entry.price(), 1500);
        assert_eq!(entry.index, 10);

        // The visible quantity and total quantity cannot be verified directly
        // as they come from the PriceLevel which is freshly created in deserialization
        // and not populated with orders
    }

    #[test]
    fn test_order_book_entry_from_str_with_invalid_input() {
        // Create a string with invalid format
        let invalid_input = "NotAnOrderBookEntry:price=1000;index=5";

        // Attempt to parse the invalid input
        let result = OrderBookEntry::from_str(invalid_input);

        // Verify parsing fails as expected
        assert!(result.is_err());

        // Test missing fields
        let missing_index = "OrderBookEntry:price=1000";
        let result = OrderBookEntry::from_str(missing_index);
        assert!(result.is_err());

        // Test invalid field values
        let invalid_price = "OrderBookEntry:price=invalid;index=5";
        let result = OrderBookEntry::from_str(invalid_price);
        assert!(result.is_err());

        let invalid_index = "OrderBookEntry:price=1000;index=invalid";
        let result = OrderBookEntry::from_str(invalid_index);
        assert!(result.is_err());
    }
}

#[cfg(test)]
mod tests_order_book_entry {
    use crate::orders::Hash32;
    use crate::price_level::entry::OrderBookEntry;
    use crate::price_level::level::PriceLevel;
    use crate::utils::{Price, Quantity, TimestampMs};
    use std::cmp::Ordering;
    use std::sync::Arc;

    /// Create a test OrderBookEntry with specified price and index
    fn create_test_entry(price: u128, index: usize) -> OrderBookEntry {
        let level = Arc::new(PriceLevel::new(price));
        OrderBookEntry::new(level, index)
    }

    #[test]
    /// Test the order_count method returns the correct count
    fn test_order_count() {
        // Create two price levels with different characteristics
        let level1 = Arc::new(PriceLevel::new(1000));
        let entry1 = OrderBookEntry::new(level1.clone(), 5);

        // Initially should have zero orders
        assert_eq!(entry1.order_count(), 0);

        // Add some orders and check again
        let order_type = crate::orders::OrderType::Standard {
            id: crate::orders::Id::from_u64(1),
            price: Price::new(1000),
            quantity: Quantity::new(10),
            side: crate::orders::Side::Buy,
            user_id: Hash32::zero(),
            timestamp: TimestampMs::new(1616823000000),
            time_in_force: crate::orders::TimeInForce::Gtc,
            extra_fields: (),
        };

        level1.add_order(order_type);
        assert_eq!(entry1.order_count(), 1);

        // Add another order
        let order_type2 = crate::orders::OrderType::Standard {
            id: crate::orders::Id::from_u64(2),
            price: Price::new(1000),
            quantity: Quantity::new(20),
            side: crate::orders::Side::Buy,
            user_id: Hash32::zero(),
            timestamp: TimestampMs::new(1616823000001),
            time_in_force: crate::orders::TimeInForce::Gtc,
            extra_fields: (),
        };

        level1.add_order(order_type2);
        assert_eq!(entry1.order_count(), 2);
    }

    #[test]
    /// Test the equality comparison between entries
    fn test_partial_eq() {
        // Create entries with same price but different indices
        let entry1 = create_test_entry(1000, 5);
        let entry2 = create_test_entry(1000, 10);

        // Entries should be equal because they have the same price
        assert_eq!(entry1, entry2);

        // Create an entry with different price
        let entry3 = create_test_entry(2000, 5);

        // Entries should not be equal because they have different prices
        assert_ne!(entry1, entry3);
    }

    #[test]
    /// Test that Eq trait is implemented correctly
    fn test_eq() {
        // This test is mostly to verify the Eq trait's blanket implementation
        let entry1 = create_test_entry(1000, 5);
        let entry2 = create_test_entry(1000, 10);

        // Use in a context requiring Eq
        let mut entries = std::collections::HashSet::new();
        entries.insert(entry1.price());
        entries.insert(entry2.price());

        // Should only have one entry because prices are the same
        assert_eq!(entries.len(), 1);
    }

    #[test]
    /// Test partial ordering comparison
    fn test_partial_ord() {
        let entry1 = create_test_entry(1000, 5);
        let entry2 = create_test_entry(2000, 10);

        // entry1 should be less than entry2
        assert!(entry1.partial_cmp(&entry2) == Some(Ordering::Less));
        // entry2 should be greater than entry1
        assert!(entry2.partial_cmp(&entry1) == Some(Ordering::Greater));
        // entry1 should be equal to itself
        assert!(entry1.partial_cmp(&entry1) == Some(Ordering::Equal));
    }

    #[test]
    /// Test total ordering comparison
    fn test_ord() {
        let entry1 = create_test_entry(1000, 5);
        let entry2 = create_test_entry(2000, 10);
        let entry3 = create_test_entry(500, 15);

        // Direct comparisons
        assert!(entry1 < entry2);
        assert!(entry2 > entry1);
        assert!(entry3 < entry1);

        // Test sorting behavior
        let mut entries = [entry2, entry1, entry3];
        entries.sort();

        // After sorting, should be in order of increasing price
        assert_eq!(entries[0].price(), 500);
        assert_eq!(entries[1].price(), 1000);
        assert_eq!(entries[2].price(), 2000);
    }

    #[test]
    /// Test ordering works correctly with binary search
    fn test_binary_search() {
        // Create sorted entries
        let entries = [
            create_test_entry(500, 1),
            create_test_entry(1000, 2),
            create_test_entry(1500, 3),
            create_test_entry(2000, 4),
            create_test_entry(2500, 5),
        ];

        // Search for existing entry
        let search_entry = create_test_entry(1500, 100); // Different index, same price
        let result = entries.binary_search(&search_entry);
        assert_eq!(result, Ok(2)); // Should find at index 2

        // Search for entry that doesn't exist but would be inserted at index 3
        let search_entry = create_test_entry(1800, 100);
        let result = entries.binary_search(&search_entry);
        assert_eq!(result, Err(3)); // Should suggest insertion at index 3
    }

    #[test]
    /// Test price accessor method returns correct value
    fn test_price() {
        let entry = create_test_entry(1234, 5);
        assert_eq!(entry.price(), 1234);
    }

    #[test]
    /// Test that index is stored and accessible
    fn test_index() {
        let entry = create_test_entry(1000, 42);
        assert_eq!(entry.index, 42);
    }

    #[test]
    /// Test that visible_quantity and total_quantity are correctly delegated to PriceLevel
    fn test_quantity_methods() {
        let level = Arc::new(PriceLevel::new(1000));
        let entry = OrderBookEntry::new(level.clone(), 5);

        // Initially quantities should be zero
        assert_eq!(entry.visible_quantity(), 0);
        assert!(matches!(entry.total_quantity(), Ok(0)));

        // Add an order with visible quantity
        let standard_order = crate::orders::OrderType::Standard {
            id: crate::orders::Id::from_u64(1),
            price: Price::new(1000),
            quantity: Quantity::new(10),
            side: crate::orders::Side::Buy,
            user_id: Hash32::zero(),
            timestamp: TimestampMs::new(1616823000000),
            time_in_force: crate::orders::TimeInForce::Gtc,
            extra_fields: (),
        };
        level.add_order(standard_order);

        // Check quantities after adding order
        assert_eq!(entry.visible_quantity(), 10);
        assert!(matches!(entry.total_quantity(), Ok(10)));

        // Add an iceberg order with hidden quantity
        let iceberg_order = crate::orders::OrderType::IcebergOrder {
            id: crate::orders::Id::from_u64(2),
            price: Price::new(1000),
            visible_quantity: Quantity::new(5),
            hidden_quantity: Quantity::new(15),
            side: crate::orders::Side::Buy,
            user_id: Hash32::zero(),
            timestamp: TimestampMs::new(1616823000001),
            time_in_force: crate::orders::TimeInForce::Gtc,
            extra_fields: (),
        };
        level.add_order(iceberg_order);

        // Check quantities after adding iceberg order
        assert_eq!(entry.visible_quantity(), 15); // 10 + 5
        assert!(matches!(entry.total_quantity(), Ok(30))); // 10 + 5 + 15
    }
}

#[cfg(test)]
mod tests_order_book_entry_deserialize {
    use crate::price_level::entry::OrderBookEntry;
    use crate::price_level::level::PriceLevel;
    use std::sync::Arc;

    #[test]
    /// Test deserialization from JSON with minimum fields
    fn test_deserialize_from_json_basic() {
        // Create a simple JSON representation
        let json = r#"{"price":1000,"index":5}"#;

        // Deserialize into OrderBookEntry
        let entry: OrderBookEntry = serde_json::from_str(json).unwrap();

        // Assert the deserialized values match expected values
        assert_eq!(entry.price(), 1000);
        assert_eq!(entry.index, 5);
        assert_eq!(entry.order_count(), 0); // New PriceLevel should have 0 orders
    }

    #[test]
    /// Test deserialization handles additional fields gracefully
    fn test_deserialize_with_extra_fields() {
        // JSON with additional fields that should be ignored
        let json = r#"{
            "price": 1500,
            "index": 10,
            "visible_quantity": 100,
            "total_quantity": 200,
            "unknown_field": "value"
        }"#;

        // Deserialize should work despite extra fields
        let entry: OrderBookEntry = serde_json::from_str(json).unwrap();

        // Check the values were properly deserialized
        assert_eq!(entry.price(), 1500);
        assert_eq!(entry.index, 10);
    }

    #[test]
    /// Test deserialization fails when required fields are missing
    fn test_deserialize_missing_fields() {
        // Missing price field
        let json_missing_price = r#"{"index": 5}"#;
        let result = serde_json::from_str::<OrderBookEntry>(json_missing_price);
        assert!(result.is_err());

        // Missing index field
        let json_missing_index = r#"{"price": 1000}"#;
        let result = serde_json::from_str::<OrderBookEntry>(json_missing_index);
        assert!(result.is_err());
    }

    #[test]
    /// Test deserialization fails with invalid field types
    fn test_deserialize_invalid_types() {
        // Invalid type for price (string instead of number)
        let json_invalid_price = r#"{"price":"invalid","index":5}"#;
        let result = serde_json::from_str::<OrderBookEntry>(json_invalid_price);
        assert!(result.is_err());

        // Invalid type for index (string instead of number)
        let json_invalid_index = r#"{"price":1000,"index":"invalid"}"#;
        let result = serde_json::from_str::<OrderBookEntry>(json_invalid_index);
        assert!(result.is_err());
    }

    #[test]
    /// Test deserialization from different JSON formats
    fn test_deserialize_different_formats() {
        // Test with integer index
        let json_int = r#"{"price":1000,"index":5}"#;
        let entry: OrderBookEntry = serde_json::from_str(json_int).unwrap();
        assert_eq!(entry.index, 5);

        // Test with larger integers
        let json_large_values = r#"{"price":18446744073709551615,"index":4294967295}"#; // max u64, max u32
        let entry: OrderBookEntry = serde_json::from_str(json_large_values).unwrap();
        assert_eq!(entry.price(), 18446744073709551615);
        assert_eq!(entry.index, 4294967295);
    }

    #[test]
    /// Test Wrapper struct directly used in deserialization implementation
    fn test_deserialize_wrapper_struct() {
        // Access the internal Wrapper struct - requires knowledge of implementation details
        // This is based on the Deserialize implementation shown earlier
        #[derive(serde::Deserialize)]
        struct Wrapper {
            price: u128,
            index: usize,
        }

        let json = r#"{"price":1000,"index":5}"#;
        let wrapper: Wrapper = serde_json::from_str(json).unwrap();

        assert_eq!(wrapper.price, 1000);
        assert_eq!(wrapper.index, 5);

        // Create an OrderBookEntry from the wrapper manually
        let level = Arc::new(PriceLevel::new(wrapper.price));
        let entry = OrderBookEntry::new(level, wrapper.index);

        assert_eq!(entry.price(), 1000);
        assert_eq!(entry.index, 5);
    }

    #[test]
    /// Test deserialization from a complete JSON data structure
    fn test_deserialize_from_complete_json() {
        // More complete JSON with nested structure similar to what might be used in practice
        let json = r#"{
            "price": 1000, 
            "index": 5,
            "level_data": {
                "visible_quantity": 10,
                "hidden_quantity": 20,
                "order_count": 2
            }
        }"#;

        // Despite extra nested fields, deserialization should still work
        let entry: OrderBookEntry = serde_json::from_str(json).unwrap();

        assert_eq!(entry.price(), 1000);
        assert_eq!(entry.index, 5);
    }

    #[test]
    /// Test round-trip serialization and deserialization
    fn test_serde_round_trip() {
        // Create an original entry
        let original_level = Arc::new(PriceLevel::new(1500));
        let original_entry = OrderBookEntry::new(original_level, 25);

        // Serialize to JSON
        let serialized = serde_json::to_string(&original_entry).unwrap();

        // Deserialize back
        let deserialized: OrderBookEntry = serde_json::from_str(&serialized).unwrap();

        // Compare values
        assert_eq!(deserialized.price(), original_entry.price());
        assert_eq!(deserialized.index, original_entry.index);
    }
}