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
use crate::errors::PriceLevelError;
use crate::orders::OrderType;
use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use std::fmt;
use std::str::FromStr;
use std::sync::Arc;

/// A snapshot of a price level in the order book. This struct provides a summary of the state of a specific price level
/// at a given point in time, including the price, visible and hidden quantities, order count, and a vector of the orders
/// at that level.
#[derive(Debug, Default, Clone)]
pub struct PriceLevelSnapshot {
    /// The price of this level.
    price: u128,
    /// Total visible quantity at this level in the smallest unit.
    visible_quantity: u64,
    /// Total hidden quantity at this level in the smallest unit.
    hidden_quantity: u64,
    /// Number of orders at this level.
    order_count: usize,
    /// Orders at this level.
    orders: Vec<Arc<OrderType<()>>>,
}

impl PriceLevelSnapshot {
    /// Create a new empty snapshot at the given price.
    #[must_use]
    pub fn new(price: u128) -> Self {
        Self {
            price,
            visible_quantity: 0,
            hidden_quantity: 0,
            order_count: 0,
            orders: Vec::new(),
        }
    }

    /// Creates a snapshot populated with orders, computing aggregates automatically.
    pub fn with_orders(
        price: u128,
        orders: Vec<Arc<OrderType<()>>>,
    ) -> Result<Self, PriceLevelError> {
        let mut snapshot = Self {
            price,
            visible_quantity: 0,
            hidden_quantity: 0,
            order_count: 0,
            orders,
        };
        snapshot.refresh_aggregates()?;
        Ok(snapshot)
    }

    /// Returns the price of this level.
    #[must_use]
    pub fn price(&self) -> u128 {
        self.price
    }

    /// Returns the total visible quantity.
    #[must_use]
    pub fn visible_quantity(&self) -> u64 {
        self.visible_quantity
    }

    /// Returns the total hidden quantity.
    #[must_use]
    pub fn hidden_quantity(&self) -> u64 {
        self.hidden_quantity
    }

    /// Returns the number of orders.
    #[must_use]
    pub fn order_count(&self) -> usize {
        self.order_count
    }

    /// Returns a reference to the orders in this snapshot.
    #[must_use]
    pub fn orders(&self) -> &[Arc<OrderType<()>>] {
        &self.orders
    }

    /// Consumes the snapshot and returns the inner orders vector.
    #[must_use]
    pub fn into_orders(self) -> Vec<Arc<OrderType<()>>> {
        self.orders
    }

    /// Constructs a snapshot with pre-computed aggregates.
    ///
    /// This is intended for internal crate use where the caller has already
    /// computed the aggregate values (e.g., from atomic counters).
    #[must_use]
    pub(crate) fn from_raw_parts(
        price: u128,
        visible_quantity: u64,
        hidden_quantity: u64,
        order_count: usize,
        orders: Vec<Arc<OrderType<()>>>,
    ) -> Self {
        Self {
            price,
            visible_quantity,
            hidden_quantity,
            order_count,
            orders,
        }
    }

    /// Get the total quantity (visible + hidden) at this price level.
    pub fn total_quantity(&self) -> Result<u64, PriceLevelError> {
        self.visible_quantity
            .checked_add(self.hidden_quantity)
            .ok_or_else(|| PriceLevelError::InvalidOperation {
                message: "snapshot total quantity overflow".to_string(),
            })
    }

    /// Get an iterator over the orders in this snapshot
    pub fn iter_orders(&self) -> impl Iterator<Item = &Arc<OrderType<()>>> {
        self.orders.iter()
    }

    /// Recomputes aggregate fields (`visible_quantity`, `hidden_quantity`, and `order_count`) based on current orders.
    pub fn refresh_aggregates(&mut self) -> Result<(), PriceLevelError> {
        self.order_count = self.orders.len();

        let mut visible_total: u64 = 0;
        let mut hidden_total: u64 = 0;

        for order in &self.orders {
            visible_total = visible_total
                .checked_add(order.visible_quantity())
                .ok_or_else(|| PriceLevelError::InvalidOperation {
                    message: "snapshot visible quantity overflow".to_string(),
                })?;

            hidden_total = hidden_total
                .checked_add(order.hidden_quantity())
                .ok_or_else(|| PriceLevelError::InvalidOperation {
                    message: "snapshot hidden quantity overflow".to_string(),
                })?;
        }

        self.visible_quantity = visible_total;
        self.hidden_quantity = hidden_total;

        Ok(())
    }
}

/// Format version for checksum-enabled price level snapshots.
pub const SNAPSHOT_FORMAT_VERSION: u32 = 1;

/// Serialized representation of a price level snapshot including checksum validation metadata.
///
/// All fields are private to protect checksum integrity.
/// Use the provided accessor methods to read package data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceLevelSnapshotPackage {
    /// Version of the serialized snapshot schema to support future migrations.
    version: u32,
    /// Captured snapshot data.
    snapshot: PriceLevelSnapshot,
    /// Hex-encoded checksum used to validate the snapshot integrity.
    checksum: String,
}

impl PriceLevelSnapshotPackage {
    /// Returns the schema version of this package.
    #[must_use]
    pub fn version(&self) -> u32 {
        self.version
    }

    /// Returns a reference to the contained snapshot.
    #[must_use]
    pub fn snapshot(&self) -> &PriceLevelSnapshot {
        &self.snapshot
    }

    /// Returns the hex-encoded checksum.
    #[must_use]
    pub fn checksum(&self) -> &str {
        &self.checksum
    }
}

impl PriceLevelSnapshotPackage {
    /// Creates a new snapshot package computing the checksum for the provided snapshot.
    pub fn new(mut snapshot: PriceLevelSnapshot) -> Result<Self, PriceLevelError> {
        snapshot.refresh_aggregates()?;

        let checksum = Self::compute_checksum(&snapshot)?;

        Ok(Self {
            version: SNAPSHOT_FORMAT_VERSION,
            snapshot,
            checksum,
        })
    }

    /// Serializes the package to JSON.
    pub fn to_json(&self) -> Result<String, PriceLevelError> {
        serde_json::to_string(self).map_err(|error| PriceLevelError::SerializationError {
            message: error.to_string(),
        })
    }

    /// Deserializes a package from JSON.
    pub fn from_json(data: &str) -> Result<Self, PriceLevelError> {
        serde_json::from_str(data).map_err(|error| PriceLevelError::DeserializationError {
            message: error.to_string(),
        })
    }

    /// Validates the checksum contained in the package against the serialized snapshot data.
    pub fn validate(&self) -> Result<(), PriceLevelError> {
        if self.version != SNAPSHOT_FORMAT_VERSION {
            return Err(PriceLevelError::InvalidOperation {
                message: format!(
                    "Unsupported snapshot version: {} (expected {})",
                    self.version, SNAPSHOT_FORMAT_VERSION
                ),
            });
        }

        let computed = Self::compute_checksum(&self.snapshot)?;
        if computed != self.checksum {
            return Err(PriceLevelError::ChecksumMismatch {
                expected: self.checksum.clone(),
                actual: computed,
            });
        }

        Ok(())
    }

    /// Consumes the package after validating the checksum and returns the contained snapshot.
    pub fn into_snapshot(self) -> Result<PriceLevelSnapshot, PriceLevelError> {
        self.validate()?;
        Ok(self.snapshot)
    }

    fn compute_checksum(snapshot: &PriceLevelSnapshot) -> Result<String, PriceLevelError> {
        let payload =
            serde_json::to_vec(snapshot).map_err(|error| PriceLevelError::SerializationError {
                message: error.to_string(),
            })?;

        let mut hasher = Sha256::new();
        hasher.update(payload);

        let checksum_bytes = hasher.finalize();
        Ok(format!("{:x}", checksum_bytes))
    }
}

impl Serialize for PriceLevelSnapshot {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("PriceLevelSnapshot", 5)?;

        state.serialize_field("price", &self.price)?;
        state.serialize_field("visible_quantity", &self.visible_quantity)?;
        state.serialize_field("hidden_quantity", &self.hidden_quantity)?;
        state.serialize_field("order_count", &self.order_count)?;

        let plain_orders: Vec<OrderType<()>> =
            self.orders.iter().map(|arc_order| **arc_order).collect();

        state.serialize_field("orders", &plain_orders)?;

        state.end()
    }
}

impl<'de> Deserialize<'de> for PriceLevelSnapshot {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Field {
            Price,
            VisibleQuantity,
            HiddenQuantity,
            OrderCount,
            Orders,
        }

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
            where
                D: Deserializer<'de>,
            {
                struct FieldVisitor;

                impl Visitor<'_> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str("`price`, `visible_quantity`, `hidden_quantity`, `order_count`, or `orders`")
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        match value {
                            "price" => Ok(Field::Price),
                            "visible_quantity" => Ok(Field::VisibleQuantity),
                            "hidden_quantity" => Ok(Field::HiddenQuantity),
                            "order_count" => Ok(Field::OrderCount),
                            "orders" => Ok(Field::Orders),
                            _ => Err(de::Error::unknown_field(
                                value,
                                &[
                                    "price",
                                    "visible_quantity",
                                    "hidden_quantity",
                                    "order_count",
                                    "orders",
                                ],
                            )),
                        }
                    }
                }

                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct PriceLevelSnapshotVisitor;

        impl<'de> Visitor<'de> for PriceLevelSnapshotVisitor {
            type Value = PriceLevelSnapshot;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct PriceLevelSnapshot")
            }

            fn visit_map<V>(self, mut map: V) -> Result<PriceLevelSnapshot, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut price = None;
                let mut visible_quantity = None;
                let mut hidden_quantity = None;
                let mut order_count = None;
                let mut orders = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Price => {
                            if price.is_some() {
                                return Err(de::Error::duplicate_field("price"));
                            }
                            price = Some(map.next_value()?);
                        }
                        Field::VisibleQuantity => {
                            if visible_quantity.is_some() {
                                return Err(de::Error::duplicate_field("visible_quantity"));
                            }
                            visible_quantity = Some(map.next_value()?);
                        }
                        Field::HiddenQuantity => {
                            if hidden_quantity.is_some() {
                                return Err(de::Error::duplicate_field("hidden_quantity"));
                            }
                            hidden_quantity = Some(map.next_value()?);
                        }
                        Field::OrderCount => {
                            if order_count.is_some() {
                                return Err(de::Error::duplicate_field("order_count"));
                            }
                            order_count = Some(map.next_value()?);
                        }
                        Field::Orders => {
                            if orders.is_some() {
                                return Err(de::Error::duplicate_field("orders"));
                            }
                            let plain_orders: Vec<OrderType<()>> = map.next_value()?;
                            orders = Some(plain_orders.into_iter().map(Arc::new).collect());
                        }
                    }
                }

                let price = price.ok_or_else(|| de::Error::missing_field("price"))?;
                let visible_quantity =
                    visible_quantity.ok_or_else(|| de::Error::missing_field("visible_quantity"))?;
                let hidden_quantity =
                    hidden_quantity.ok_or_else(|| de::Error::missing_field("hidden_quantity"))?;
                let order_count =
                    order_count.ok_or_else(|| de::Error::missing_field("order_count"))?;
                let orders = orders.unwrap_or_default();

                Ok(PriceLevelSnapshot {
                    price,
                    visible_quantity,
                    hidden_quantity,
                    order_count,
                    orders,
                })
            }
        }

        const FIELDS: &[&str] = &[
            "price",
            "visible_quantity",
            "hidden_quantity",
            "order_count",
            "orders",
        ];
        deserializer.deserialize_struct("PriceLevelSnapshot", FIELDS, PriceLevelSnapshotVisitor)
    }
}

impl fmt::Display for PriceLevelSnapshot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "PriceLevelSnapshot:price={};visible_quantity={};hidden_quantity={};order_count={}",
            self.price, self.visible_quantity, self.hidden_quantity, self.order_count
        )
    }
}

impl FromStr for PriceLevelSnapshot {
    type Err = PriceLevelError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() != 2 || parts[0] != "PriceLevelSnapshot" {
            return Err(PriceLevelError::InvalidFormat);
        }

        let fields_str = parts[1];
        let mut fields = std::collections::HashMap::new();

        for field_pair in fields_str.split(';') {
            let kv: Vec<&str> = field_pair.split('=').collect();
            if kv.len() == 2 {
                fields.insert(kv[0], kv[1]);
            }
        }

        let get_field = |field: &str| -> Result<&str, PriceLevelError> {
            match fields.get(field) {
                Some(result) => Ok(*result),
                None => Err(PriceLevelError::MissingField(field.to_string())),
            }
        };

        let parse_u64 = |field: &str, value: &str| -> Result<u64, PriceLevelError> {
            value
                .parse::<u64>()
                .map_err(|_| PriceLevelError::InvalidFieldValue {
                    field: field.to_string(),
                    value: value.to_string(),
                })
        };

        let parse_u128 = |field: &str, value: &str| -> Result<u128, PriceLevelError> {
            value
                .parse::<u128>()
                .map_err(|_| PriceLevelError::InvalidFieldValue {
                    field: field.to_string(),
                    value: value.to_string(),
                })
        };

        let parse_usize = |field: &str, value: &str| -> Result<usize, PriceLevelError> {
            value
                .parse::<usize>()
                .map_err(|_| PriceLevelError::InvalidFieldValue {
                    field: field.to_string(),
                    value: value.to_string(),
                })
        };

        // Parse fields
        let price_str = get_field("price")?;
        let price = parse_u128("price", price_str)?;

        let visible_quantity_str = get_field("visible_quantity")?;
        let visible_quantity = parse_u64("visible_quantity", visible_quantity_str)?;

        let hidden_quantity_str = get_field("hidden_quantity")?;
        let hidden_quantity = parse_u64("hidden_quantity", hidden_quantity_str)?;

        let order_count_str = get_field("order_count")?;
        let order_count = parse_usize("order_count", order_count_str)?;

        // Create a new snapshot - note that orders cannot be serialized/deserialized in this simple format
        Ok(PriceLevelSnapshot {
            price,
            visible_quantity,
            hidden_quantity,
            order_count,
            orders: Vec::new(),
        })
    }
}