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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
#[cfg(test)]
mod tests {
    use crate::errors::PriceLevelError;
    use crate::orders::{Hash32, Id, OrderType, Side, TimeInForce};
    use crate::price_level::snapshot::SNAPSHOT_FORMAT_VERSION;
    use crate::price_level::{PriceLevelSnapshot, PriceLevelSnapshotPackage};
    use crate::utils::{Price, Quantity, TimestampMs};
    use serde_json::Value;
    use std::str::FromStr;
    use std::sync::Arc;

    fn create_sample_orders() -> Vec<Arc<OrderType<()>>> {
        vec![
            Arc::new(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: (),
            }),
            Arc::new(OrderType::IcebergOrder {
                id: Id::from_u64(2),
                price: Price::new(1000),
                visible_quantity: Quantity::new(5),
                hidden_quantity: Quantity::new(15),
                side: Side::Buy,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000001),
                time_in_force: TimeInForce::Gtc,
                extra_fields: (),
            }),
        ]
    }

    #[test]
    fn test_snapshot_package_roundtrip() {
        let snapshot = PriceLevelSnapshot::with_orders(42, create_sample_orders())
            .expect("Failed to create snapshot with orders");

        let package =
            PriceLevelSnapshotPackage::new(snapshot.clone()).expect("Failed to create package");

        assert_eq!(package.version(), SNAPSHOT_FORMAT_VERSION);
        package.validate().expect("Package validation failed");

        let json = package.to_json().expect("Failed to serialize package");
        let restored_package =
            PriceLevelSnapshotPackage::from_json(&json).expect("Failed to deserialize package");

        restored_package
            .validate()
            .expect("Checksum validation should succeed");

        let restored_snapshot = restored_package
            .into_snapshot()
            .expect("Snapshot extraction failed");

        assert_eq!(restored_snapshot.price(), snapshot.price());
        assert_eq!(restored_snapshot.order_count(), snapshot.order_count());
        assert_eq!(
            restored_snapshot.visible_quantity(),
            snapshot.visible_quantity()
        );
        assert_eq!(
            restored_snapshot.hidden_quantity(),
            snapshot.hidden_quantity()
        );
        assert_eq!(restored_snapshot.orders().len(), snapshot.orders().len());
    }

    #[test]
    fn test_snapshot_package_checksum_mismatch() {
        let snapshot = PriceLevelSnapshot::with_orders(99, create_sample_orders())
            .expect("Failed to create snapshot with orders");

        let package = PriceLevelSnapshotPackage::new(snapshot).expect("Failed to create package");
        let json = package.to_json().expect("Failed to serialize package");

        let mut value: Value = serde_json::from_str(&json).expect("JSON parsing failed");
        if let Some(obj) = value.as_object_mut() {
            obj.insert(
                "checksum".to_string(),
                Value::String("deadbeef".to_string()),
            );
        }

        let tampered_json = serde_json::to_string(&value).expect("JSON serialization failed");

        let tampered_package = PriceLevelSnapshotPackage::from_json(&tampered_json)
            .expect("Deserialization should still succeed");

        let err = tampered_package
            .validate()
            .expect_err("Checksum mismatch expected");
        assert!(matches!(err, PriceLevelError::ChecksumMismatch { .. }));
    }

    #[test]
    fn test_new() {
        let snapshot = PriceLevelSnapshot::new(1000);
        assert_eq!(snapshot.price(), 1000);
        assert_eq!(snapshot.visible_quantity(), 0);
        assert_eq!(snapshot.hidden_quantity(), 0);
        assert_eq!(snapshot.order_count(), 0);
        assert!(snapshot.orders().is_empty());
    }

    #[test]
    fn test_default() {
        let snapshot = PriceLevelSnapshot::default();
        assert_eq!(snapshot.price(), 0);
        assert_eq!(snapshot.visible_quantity(), 0);
        assert_eq!(snapshot.hidden_quantity(), 0);
        assert_eq!(snapshot.order_count(), 0);
        assert!(snapshot.orders().is_empty());
    }

    #[test]
    fn test_total_quantity() {
        let snapshot = PriceLevelSnapshot::from_raw_parts(1000, 50, 150, 0, Vec::new());
        assert!(matches!(snapshot.total_quantity(), Ok(200)));
    }

    #[test]
    fn test_iter_orders() {
        let orders = create_sample_orders();
        let order_count = orders.len();
        let snapshot = PriceLevelSnapshot::from_raw_parts(1000, 0, 0, order_count, orders);

        let collected: Vec<_> = snapshot.iter_orders().collect();
        assert_eq!(collected.len(), 2);

        // Verify first order
        if let OrderType::Standard { id, .. } = **collected[0] {
            assert_eq!(id, Id::from_u64(1));
        } else {
            panic!("Expected StandardOrder");
        }

        // Verify second order
        if let OrderType::IcebergOrder { id, .. } = **collected[1] {
            assert_eq!(id, Id::from_u64(2));
        } else {
            panic!("Expected IcebergOrder");
        }
    }

    #[test]
    fn test_clone() {
        let original = PriceLevelSnapshot::from_raw_parts(1000, 50, 150, 2, create_sample_orders());

        let cloned = original.clone();
        assert_eq!(cloned.price(), 1000);
        assert_eq!(cloned.visible_quantity(), 50);
        assert_eq!(cloned.hidden_quantity(), 150);
        assert_eq!(cloned.order_count(), 2);
        assert_eq!(cloned.orders().len(), 2);
    }

    #[test]
    fn test_display() {
        let snapshot = PriceLevelSnapshot::from_raw_parts(1000, 50, 150, 2, Vec::new());

        let display_str = snapshot.to_string();
        assert!(display_str.contains("price=1000"));
        assert!(display_str.contains("visible_quantity=50"));
        assert!(display_str.contains("hidden_quantity=150"));
        assert!(display_str.contains("order_count=2"));
    }

    #[test]
    fn test_from_str() {
        let input =
            "PriceLevelSnapshot:price=1000;visible_quantity=50;hidden_quantity=150;order_count=2";
        let snapshot = PriceLevelSnapshot::from_str(input).unwrap();

        assert_eq!(snapshot.price(), 1000);
        assert_eq!(snapshot.visible_quantity(), 50);
        assert_eq!(snapshot.hidden_quantity(), 150);
        assert_eq!(snapshot.order_count(), 2);
        assert!(snapshot.orders().is_empty()); // Orders can't be parsed from string representation
    }

    #[test]
    fn test_from_str_invalid_format() {
        let input = "InvalidFormat";
        let result = PriceLevelSnapshot::from_str(input);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_str_missing_field() {
        let input = "PriceLevelSnapshot:price=1000;visible_quantity=50;hidden_quantity=150";
        let result = PriceLevelSnapshot::from_str(input);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_str_invalid_field_value() {
        let input = "PriceLevelSnapshot:price=invalid;visible_quantity=50;hidden_quantity=150;order_count=2";
        let result = PriceLevelSnapshot::from_str(input);
        assert!(result.is_err());
    }

    #[test]
    fn test_roundtrip_display_fromstr() {
        let original = PriceLevelSnapshot::from_raw_parts(1000, 50, 150, 2, Vec::new());

        let string_representation = original.to_string();
        let parsed = PriceLevelSnapshot::from_str(&string_representation).unwrap();

        assert_eq!(parsed.price(), original.price());
        assert_eq!(parsed.visible_quantity(), original.visible_quantity());
        assert_eq!(parsed.hidden_quantity(), original.hidden_quantity());
        assert_eq!(parsed.order_count(), original.order_count());
    }

    // In price_level/snapshot.rs test module or in a separate test file

    #[test]
    fn test_snapshot_serialization_fields() {
        // Create a snapshot with specific field values
        let snapshot = PriceLevelSnapshot::from_raw_parts(10000, 200, 300, 5, Vec::new());

        // Add some orders (empty for now, we'll test orders separately)

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

        // Check the serialized fields
        assert!(serialized.contains("\"price\":10000"));
        assert!(serialized.contains("\"visible_quantity\":200"));
        assert!(serialized.contains("\"hidden_quantity\":300"));
        assert!(serialized.contains("\"order_count\":5"));
        assert!(serialized.contains("\"orders\":[]"));
    }

    #[test]
    fn test_snapshot_deserializer_duplicate_fields() {
        // Test with duplicate field
        let json = r#"{
        "price": 10000,
        "visible_quantity": 200,
        "hidden_quantity": 300,
        "order_count": 5,
        "price": 20000,
        "orders": []
    }"#;

        // Should fail due to duplicate field
        let result = serde_json::from_str::<PriceLevelSnapshot>(json);
        assert!(result.is_err());

        // Error should mention duplicate field
        let err = result.unwrap_err().to_string();
        assert!(err.contains("duplicate field"));
    }

    #[test]
    fn test_snapshot_visitor_implementation() {
        // Testing the visitor by providing various field values
        let json = r#"{
        "price": 10000,
        "visible_quantity": 200,
        "hidden_quantity": 300,
        "order_count": 5,
        "orders": []
    }"#;

        let snapshot: PriceLevelSnapshot = serde_json::from_str(json).unwrap();

        assert_eq!(snapshot.price(), 10000);
        assert_eq!(snapshot.visible_quantity(), 200);
        assert_eq!(snapshot.hidden_quantity(), 300);
        assert_eq!(snapshot.order_count(), 5);
        assert!(snapshot.orders().is_empty());
    }

    #[test]
    fn test_snapshot_with_actual_orders() {
        fn create_standard_order(id: u64, price: u128, quantity: u64) -> OrderType<()> {
            OrderType::<()>::Standard {
                id: Id::from_u64(id),
                price: Price::new(price),
                quantity: Quantity::new(quantity),
                side: Side::Buy,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000000),
                time_in_force: TimeInForce::Gtc,
                extra_fields: (),
            }
        }

        fn create_iceberg_order(
            id: u64,
            price: u128,
            visible_quantity: u64,
            hidden_quantity: u64,
        ) -> OrderType<()> {
            OrderType::<()>::IcebergOrder {
                id: Id::from_u64(id),
                price: Price::new(price),
                visible_quantity: Quantity::new(visible_quantity),
                hidden_quantity: Quantity::new(hidden_quantity),
                side: Side::Buy,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000000),
                time_in_force: TimeInForce::Gtc,
                extra_fields: (),
            }
        }
        // Create a snapshot with orders
        let orders = vec![
            Arc::new(create_standard_order(1, 10000u128, 100)),
            Arc::new(create_iceberg_order(2, 10000u128, 50, 250)),
        ];
        let snapshot = PriceLevelSnapshot::from_raw_parts(10000, 150, 250, 2, orders);

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

        // Check serialized fields and orders
        assert!(serialized.contains("\"price\":10000"));
        assert!(serialized.contains("\"visible_quantity\":150"));
        assert!(serialized.contains("\"hidden_quantity\":250"));
        assert!(serialized.contains("\"order_count\":2"));
        assert!(serialized.contains("\"orders\":["));
        assert!(serialized.contains("\"Standard\":{"));
        assert!(serialized.contains("\"IcebergOrder\":{"));

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

        assert_eq!(deserialized.price(), 10000);
        assert_eq!(deserialized.visible_quantity(), 150);
        assert_eq!(deserialized.hidden_quantity(), 250);
        assert_eq!(deserialized.order_count(), 2);
        assert_eq!(deserialized.orders().len(), 2);

        // Verify order types
        if let OrderType::Standard { id, quantity, .. } = &*deserialized.orders()[0] {
            assert_eq!(*id, Id::from_u64(1));
            assert_eq!(*quantity, Quantity::new(100));
        } else {
            panic!("Expected Standard order");
        }

        if let OrderType::IcebergOrder {
            id,
            visible_quantity,
            hidden_quantity,
            ..
        } = &*deserialized.orders()[1]
        {
            assert_eq!(*id, Id::from_u64(2));
            assert_eq!(*visible_quantity, Quantity::new(50));
            assert_eq!(*hidden_quantity, Quantity::new(250));
        } else {
            panic!("Expected IcebergOrder");
        }
    }
}

#[cfg(test)]
mod pricelevel_snapshot_serialization_tests {
    use crate::orders::{Hash32, Id, OrderType, Side, TimeInForce};
    use crate::price_level::PriceLevelSnapshot;
    use crate::utils::{Price, Quantity, TimestampMs};

    use std::str::FromStr;
    use std::sync::Arc;

    // Helper function to create sample orders for testing
    fn create_sample_orders() -> Vec<Arc<OrderType<()>>> {
        vec![
            Arc::new(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: (),
            }),
            Arc::new(OrderType::IcebergOrder {
                id: Id::from_u64(2),
                price: Price::new(1000),
                visible_quantity: Quantity::new(5),
                hidden_quantity: Quantity::new(15),
                side: Side::Sell,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000001),
                time_in_force: TimeInForce::Gtc,
                extra_fields: (),
            }),
            Arc::new(OrderType::PostOnly {
                id: Id::from_u64(3),
                price: Price::new(1000),
                quantity: Quantity::new(8),
                side: Side::Buy,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000002),
                time_in_force: TimeInForce::Ioc,
                extra_fields: (),
            }),
        ]
    }

    // Helper function to create a sample snapshot for testing
    fn create_sample_snapshot() -> PriceLevelSnapshot {
        PriceLevelSnapshot::from_raw_parts(
            1000,
            15, // 10 + 5 (first two orders)
            15, // hidden quantity from iceberg order
            3,
            create_sample_orders(),
        )
    }

    #[test]
    fn test_snapshot_json_serialization() {
        let snapshot = create_sample_snapshot();

        // Serialize to JSON
        let json = serde_json::to_string(&snapshot)
            .expect("Failed to serialize PriceLevelSnapshot to JSON");

        // Verify basic JSON properties
        assert!(json.contains("\"price\":1000"));
        assert!(json.contains("\"visible_quantity\":15"));
        assert!(json.contains("\"hidden_quantity\":15"));
        assert!(json.contains("\"order_count\":3"));

        // Verify orders array
        assert!(json.contains("\"orders\":["));

        // Check for order details
        assert!(json.contains("\"Standard\":{"));
        assert!(json.contains("\"id\":\"00000000-0000-0001-0000-000000000000\""));
        assert!(json.contains("\"IcebergOrder\":{"));
        assert!(json.contains("\"visible_quantity\":5"));
        assert!(json.contains("\"hidden_quantity\":15"));
        assert!(json.contains("\"PostOnly\":{"));
    }

    #[test]
    fn test_snapshot_json_deserialization() {
        let snapshot = create_sample_snapshot();

        // Serialize to JSON
        let json =
            serde_json::to_string(&snapshot).expect("Failed to serialize PriceLevelSnapshot");

        // Deserialize back to PriceLevelSnapshot
        let deserialized: PriceLevelSnapshot = serde_json::from_str(&json)
            .expect("Failed to deserialize PriceLevelSnapshot from JSON");

        // Verify basic fields
        assert_eq!(deserialized.price(), 1000);
        assert_eq!(deserialized.visible_quantity(), 15);
        assert_eq!(deserialized.hidden_quantity(), 15);
        assert_eq!(deserialized.order_count(), 3);

        // Verify orders array length
        assert_eq!(deserialized.orders().len(), 3);

        // Check specific order details
        let standard_order = &deserialized.orders()[0];
        match **standard_order {
            OrderType::Standard {
                id,
                price,
                quantity,
                side,
                ..
            } => {
                assert_eq!(id, Id::from_u64(1));
                assert_eq!(price, Price::new(1000));
                assert_eq!(quantity, Quantity::new(10));
                assert_eq!(side, Side::Buy);
            }
            _ => panic!("Expected Standard order"),
        }

        let iceberg_order = &deserialized.orders()[1];
        match **iceberg_order {
            OrderType::IcebergOrder {
                id,
                visible_quantity,
                hidden_quantity,
                side,
                ..
            } => {
                assert_eq!(id, Id::from_u64(2));
                assert_eq!(visible_quantity, Quantity::new(5));
                assert_eq!(hidden_quantity, Quantity::new(15));
                assert_eq!(side, Side::Sell);
            }
            _ => panic!("Expected IcebergOrder"),
        }

        let post_only_order = &deserialized.orders()[2];
        match **post_only_order {
            OrderType::<()>::PostOnly {
                id, quantity, side, ..
            } => {
                assert_eq!(id, Id::from_u64(3));
                assert_eq!(quantity, Quantity::new(8));
                assert_eq!(side, Side::Buy);
            }
            _ => panic!("Expected PostOnly order"),
        }
    }

    #[test]
    fn test_snapshot_string_format_serialization() {
        let snapshot = create_sample_snapshot();

        // Convert to string representation
        let display_str = snapshot.to_string();

        // Verify string format
        assert!(display_str.starts_with("PriceLevelSnapshot:"));
        assert!(display_str.contains("price=1000"));
        assert!(display_str.contains("visible_quantity=15"));
        assert!(display_str.contains("hidden_quantity=15"));
        assert!(display_str.contains("order_count=3"));

        // Note: The string format doesn't include orders as shown in the FromStr implementation
    }

    #[test]
    fn test_snapshot_string_format_deserialization() {
        // Create string representation
        let input =
            "PriceLevelSnapshot:price=1000;visible_quantity=15;hidden_quantity=15;order_count=3";

        // Parse from string
        let snapshot =
            PriceLevelSnapshot::from_str(input).expect("Failed to parse PriceLevelSnapshot");

        // Verify basic fields
        assert_eq!(snapshot.price(), 1000);
        assert_eq!(snapshot.visible_quantity(), 15);
        assert_eq!(snapshot.hidden_quantity(), 15);
        assert_eq!(snapshot.order_count(), 3);

        // Orders array should be empty when deserialized from string format (per FromStr implementation)
        assert!(snapshot.orders().is_empty());
    }

    #[test]
    fn test_snapshot_string_format_invalid_inputs() {
        // Test missing price field
        let input = "PriceLevelSnapshot:visible_quantity=15;hidden_quantity=15;order_count=3";
        let result = PriceLevelSnapshot::from_str(input);
        assert!(result.is_err());

        // Test invalid prefix
        let input = "InvalidPrefix:price=1000;visible_quantity=15;hidden_quantity=15;order_count=3";
        let result = PriceLevelSnapshot::from_str(input);
        assert!(result.is_err());

        // Test invalid field value
        let input =
            "PriceLevelSnapshot:price=invalid;visible_quantity=15;hidden_quantity=15;order_count=3";
        let result = PriceLevelSnapshot::from_str(input);
        assert!(result.is_err());

        // Test missing field separator
        let input =
            "PriceLevelSnapshot:price=1000visible_quantity=15;hidden_quantity=15;order_count=3";
        let result = PriceLevelSnapshot::from_str(input);
        assert!(result.is_err());

        // Test with unknown field
        let input = "PriceLevelSnapshot:price=1000;visible_quantity=15;hidden_quantity=15;order_count=3;unknown_field=value";
        let result = PriceLevelSnapshot::from_str(input);
        // This should still succeed as FromStr implementation doesn't validate for unknown fields
        assert!(result.is_ok());
    }

    #[test]
    fn test_snapshot_string_format_roundtrip() {
        // Create a snapshot with only basic fields (no orders)
        let original = PriceLevelSnapshot::from_raw_parts(1000, 15, 15, 3, Vec::new());

        // Convert to string
        let string_representation = original.to_string();

        // Parse back to snapshot
        let parsed = PriceLevelSnapshot::from_str(&string_representation)
            .expect("Failed to parse PriceLevelSnapshot");

        // Verify all fields match
        assert_eq!(parsed.price(), original.price());
        assert_eq!(parsed.visible_quantity(), original.visible_quantity());
        assert_eq!(parsed.hidden_quantity(), original.hidden_quantity());
        assert_eq!(parsed.order_count(), original.order_count());
    }

    #[test]
    fn test_snapshot_edge_cases() {
        // Test with zero values
        let snapshot = PriceLevelSnapshot::new(0);

        let json = serde_json::to_string(&snapshot).expect("Failed to serialize");
        let deserialized: PriceLevelSnapshot =
            serde_json::from_str(&json).expect("Failed to deserialize");

        assert_eq!(deserialized.price(), 0);
        assert_eq!(deserialized.visible_quantity(), 0);
        assert_eq!(deserialized.hidden_quantity(), 0);
        assert_eq!(deserialized.order_count(), 0);

        // Test with maximum values
        let snapshot = PriceLevelSnapshot::from_raw_parts(
            u128::MAX,
            u64::MAX,
            u64::MAX,
            usize::MAX,
            Vec::new(),
        );

        let json = serde_json::to_string(&snapshot).expect("Failed to serialize max values");
        let deserialized: PriceLevelSnapshot =
            serde_json::from_str(&json).expect("Failed to deserialize max values");

        assert_eq!(deserialized.price(), u128::MAX);
        assert_eq!(deserialized.visible_quantity(), u64::MAX);
        assert_eq!(deserialized.hidden_quantity(), u64::MAX);
        assert_eq!(deserialized.order_count(), usize::MAX);
    }

    #[test]
    fn test_snapshot_deserialization_unknown_field() {
        // Create JSON with an unknown field "unknown_field"
        let json = r#"{
            "price": 1000,
            "visible_quantity": 15,
            "hidden_quantity": 15,
            "order_count": 3,
            "orders": [],
            "unknown_field": "some value"
        }"#;

        // Attempt to deserialize - this should fail because of the unknown field
        let result = serde_json::from_str::<PriceLevelSnapshot>(json);

        // Verify that the error is of the expected type
        assert!(result.is_err());
        let err = result.unwrap_err();
        let err_string = err.to_string();

        // Verify the error message mentions the unknown field
        assert!(err_string.contains("unknown field"));
        assert!(err_string.contains("unknown_field"));

        // Verify the error message mentions the expected fields
        assert!(err_string.contains("price"));
        assert!(err_string.contains("visible_quantity"));
        assert!(err_string.contains("hidden_quantity"));
        assert!(err_string.contains("order_count"));
        assert!(err_string.contains("orders"));
    }

    #[test]
    fn test_snapshot_empty_orders() {
        // Test with an empty orders array
        let snapshot = PriceLevelSnapshot::from_raw_parts(1000, 15, 15, 0, Vec::new());

        let json = serde_json::to_string(&snapshot).expect("Failed to serialize");
        let deserialized: PriceLevelSnapshot =
            serde_json::from_str(&json).expect("Failed to deserialize");

        assert_eq!(deserialized.price(), 1000);
        assert_eq!(deserialized.orders().len(), 0);
    }

    #[test]
    fn test_snapshot_with_many_order_types() {
        // Create a snapshot with all supported order types
        let many_orders = vec![
            // Standard order
            Arc::new(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: (),
            }),
            // Iceberg order
            Arc::new(OrderType::IcebergOrder {
                id: Id::from_u64(2),
                price: Price::new(1000),
                visible_quantity: Quantity::new(5),
                hidden_quantity: Quantity::new(15),
                side: Side::Sell,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000001),
                time_in_force: TimeInForce::Gtc,
                extra_fields: (),
            }),
            // Post-only order
            Arc::new(OrderType::PostOnly {
                id: Id::from_u64(3),
                price: Price::new(1000),
                quantity: Quantity::new(8),
                side: Side::Buy,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000002),
                time_in_force: TimeInForce::Ioc,
                extra_fields: (),
            }),
            // Fill-or-kill order (as Standard with FOK time-in-force)
            Arc::new(OrderType::Standard {
                id: Id::from_u64(4),
                price: Price::new(1000),
                quantity: Quantity::new(12),
                side: Side::Buy,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000003),
                time_in_force: TimeInForce::Fok,
                extra_fields: (),
            }),
            // Good-till-date order (as Standard with GTD time-in-force)
            Arc::new(OrderType::Standard {
                id: Id::from_u64(5),
                price: Price::new(1000),
                quantity: Quantity::new(7),
                side: Side::Sell,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000004),
                time_in_force: TimeInForce::Gtd(1617000000000),
                extra_fields: (),
            }),
            // Reserve order
            Arc::new(OrderType::ReserveOrder {
                id: Id::from_u64(6),
                price: Price::new(1000),
                visible_quantity: Quantity::new(3),
                hidden_quantity: Quantity::new(12),
                side: Side::Buy,
                user_id: Hash32::zero(),
                timestamp: TimestampMs::new(1616823000005),
                time_in_force: TimeInForce::Gtc,
                replenish_threshold: Quantity::new(1),
                replenish_amount: Some(Quantity::new(2)),
                auto_replenish: true,
                extra_fields: (),
            }),
        ];

        let snapshot = PriceLevelSnapshot::from_raw_parts(
            1000,
            45, // Sum of all visible quantities
            27, // Sum of all hidden quantities
            many_orders.len(),
            many_orders,
        );

        // Serialize to JSON
        let json = serde_json::to_string(&snapshot).expect("Failed to serialize complex snapshot");

        // Deserialize back
        let deserialized: PriceLevelSnapshot =
            serde_json::from_str(&json).expect("Failed to deserialize complex snapshot");

        // Verify basic fields
        assert_eq!(deserialized.price(), 1000);
        assert_eq!(deserialized.visible_quantity(), 45);
        assert_eq!(deserialized.hidden_quantity(), 27);
        assert_eq!(deserialized.order_count(), 6);
        assert_eq!(deserialized.orders().len(), 6);

        // Verify specific order types were preserved
        let order_types = deserialized
            .orders()
            .iter()
            .map(|order| match **order {
                OrderType::Standard { .. } => "Standard",
                OrderType::IcebergOrder { .. } => "IcebergOrder",
                OrderType::PostOnly { .. } => "PostOnly",
                OrderType::ReserveOrder { .. } => "ReserveOrder",
                _ => "Other",
            })
            .collect::<Vec<_>>();

        // Count the occurrences of each order type
        let standard_count = order_types.iter().filter(|&&t| t == "Standard").count();
        let iceberg_count = order_types.iter().filter(|&&t| t == "IcebergOrder").count();
        let post_only_count = order_types.iter().filter(|&&t| t == "PostOnly").count();
        let reserve_count = order_types.iter().filter(|&&t| t == "ReserveOrder").count();

        // Verify we have the expected number of each order type
        assert_eq!(standard_count, 3); // 1 standard + 1 FOK + 1 GTD
        assert_eq!(iceberg_count, 1);
        assert_eq!(post_only_count, 1);
        assert_eq!(reserve_count, 1);

        // Check a few specific properties to ensure proper deserialization
        let reserve_order = deserialized
            .orders()
            .iter()
            .find(|order| matches!(***order, OrderType::ReserveOrder { .. }))
            .expect("Reserve order not found");

        if let OrderType::ReserveOrder {
            replenish_threshold,
            auto_replenish,
            ..
        } = **reserve_order
        {
            assert_eq!(replenish_threshold, Quantity::new(1));
            assert!(auto_replenish);
        }

        let gtd_order = deserialized
            .orders()
            .iter()
            .find(|order| {
                matches!(
                    ***order,
                    OrderType::Standard {
                        time_in_force: TimeInForce::Gtd(_),
                        ..
                    }
                )
            })
            .expect("GTD order not found");

        if let OrderType::Standard {
            time_in_force: TimeInForce::Gtd(expiry),
            ..
        } = **gtd_order
        {
            assert_eq!(expiry, 1617000000000);
        }
    }
}