matchcore 0.4.0

A high-performance order book and price-time matching engine implemented as a single-threaded, deterministic, in-memory state machine
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
use super::{LevelEntries, QueueEntry};
use crate::{OrderId, Quantity, RestingLimitOrder, SequenceNumber};

use std::ops::{Deref, DerefMut};

use rustc_hash::FxHashMap;

/// Price level that manages the status of the orders with the same price.
/// It does not store the orders themselves, but only the time priority information of the orders.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub struct PriceLevel {
    /// Total visible quantity at this price level
    pub(crate) visible_quantity: Quantity,
    /// Total hidden quantity at this price level
    pub(crate) hidden_quantity: Quantity,
    /// The level entries for this price level
    level_entries: LevelEntries,
}

impl Default for PriceLevel {
    fn default() -> Self {
        Self::new()
    }
}

impl PriceLevel {
    /// Create a new price level
    pub fn new() -> Self {
        Self {
            visible_quantity: Quantity(0),
            hidden_quantity: Quantity(0),
            level_entries: LevelEntries::new(),
        }
    }

    /// Get the visible quantity at this price level
    pub fn visible_quantity(&self) -> Quantity {
        self.visible_quantity
    }

    /// Get the hidden quantity at this price level
    pub fn hidden_quantity(&self) -> Quantity {
        self.hidden_quantity
    }

    /// Get the total quantity at this price level (visible + hidden)
    pub fn total_quantity(&self) -> Quantity {
        self.visible_quantity + self.hidden_quantity
    }

    /// Get the level entries for this price level
    pub fn level_entries(&self) -> &LevelEntries {
        &self.level_entries
    }

    /// Add an order entry to the price level
    pub(crate) fn add_order_entry(
        &mut self,
        queue_entry: QueueEntry,
        visible: Quantity,
        hidden: Quantity,
    ) {
        self.visible_quantity += visible;
        self.hidden_quantity += hidden;

        self.push(queue_entry);
        self.increment_order_count();
    }

    /// Mark an order as removed from the price level
    /// Note that it does not remove the queue entry from the queue.
    /// The stale queue entry will be cleaned up when the order is peeked from the queue.
    pub(crate) fn mark_order_removed(&mut self, visible: Quantity, hidden: Quantity) {
        self.visible_quantity -= visible;
        self.hidden_quantity -= hidden;
        self.decrement_order_count();
    }

    /// Pop the first queue entry from the price level and remove the order from the order book
    /// If the price level is empty, do nothing
    /// Note that it does not update the quantity of the price level
    pub(crate) fn remove_head_order(&mut self, orders: &mut FxHashMap<OrderId, RestingLimitOrder>) {
        let Some(queue_entry) = self.pop() else {
            return;
        };
        orders.remove(&queue_entry.order_id());
        self.decrement_order_count();
    }

    /// Apply the replenished quantity to the price level
    pub(crate) fn apply_replenishment(&mut self, replenished: Quantity) {
        self.visible_quantity += replenished;
        self.hidden_quantity -= replenished;
    }

    /// Reprioritize the front order and move it to the back of the queue
    ///
    /// # Panics
    /// Panics if the queue is empty.
    pub(crate) fn reprioritize_front(&mut self, time_priority: SequenceNumber) {
        let queue_entry = self.pop().unwrap();
        self.push(queue_entry.reprioritize(time_priority));
    }
}

impl Deref for PriceLevel {
    type Target = LevelEntries;

    fn deref(&self) -> &Self::Target {
        &self.level_entries
    }
}
impl DerefMut for PriceLevel {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.level_entries
    }
}

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

    use rustc_hash::FxHashMap;

    #[test]
    fn test_total_quantity() {
        let mut price_level = PriceLevel::new();
        assert_eq!(price_level.total_quantity(), Quantity(0));

        price_level.visible_quantity = Quantity(10);
        price_level.hidden_quantity = Quantity(20);
        assert_eq!(price_level.total_quantity(), Quantity(30));
    }

    #[test]
    fn test_order_count() {
        let mut price_level = PriceLevel::new();
        assert_eq!(price_level.order_count(), 0);
        assert!(price_level.is_empty());

        price_level.increment_order_count();
        assert_eq!(price_level.order_count(), 1);
        assert!(!price_level.is_empty());

        price_level.decrement_order_count();
        assert_eq!(price_level.order_count(), 0);
        assert!(price_level.is_empty());
    }

    #[test]
    fn test_add_order_entry_and_mark_order_removed() {
        let mut price_level = PriceLevel::new();
        assert_eq!(price_level.visible_quantity, Quantity(0));
        assert_eq!(price_level.hidden_quantity, Quantity(0));
        assert_eq!(price_level.order_count(), 0);

        price_level.add_order_entry(
            QueueEntry::new(SequenceNumber(0), OrderId(0)),
            Quantity(10),
            Quantity(0),
        );
        assert_eq!(price_level.visible_quantity, Quantity(10));
        assert_eq!(price_level.hidden_quantity, Quantity(0));
        assert_eq!(price_level.order_count(), 1);

        price_level.add_order_entry(
            QueueEntry::new(SequenceNumber(1), OrderId(1)),
            Quantity(20),
            Quantity(0),
        );
        assert_eq!(price_level.visible_quantity, Quantity(30));
        assert_eq!(price_level.hidden_quantity, Quantity(0));
        assert_eq!(price_level.order_count(), 2);

        price_level.add_order_entry(
            QueueEntry::new(SequenceNumber(2), OrderId(2)),
            Quantity(30),
            Quantity(0),
        );
        assert_eq!(price_level.visible_quantity, Quantity(60));
        assert_eq!(price_level.hidden_quantity, Quantity(0));
        assert_eq!(price_level.order_count(), 3);

        price_level.add_order_entry(
            QueueEntry::new(SequenceNumber(3), OrderId(3)),
            Quantity(40),
            Quantity(0),
        );
        assert_eq!(price_level.visible_quantity, Quantity(100));
        assert_eq!(price_level.hidden_quantity, Quantity(0));
        assert_eq!(price_level.order_count(), 4);

        price_level.add_order_entry(
            QueueEntry::new(SequenceNumber(4), OrderId(4)),
            Quantity(50),
            Quantity(50),
        );
        assert_eq!(price_level.visible_quantity, Quantity(150));
        assert_eq!(price_level.hidden_quantity, Quantity(50));
        assert_eq!(price_level.order_count(), 5);

        price_level.mark_order_removed(Quantity(10), Quantity(0));
        assert_eq!(price_level.visible_quantity, Quantity(140));
        assert_eq!(price_level.hidden_quantity, Quantity(50));
        assert_eq!(price_level.order_count(), 4);

        price_level.mark_order_removed(Quantity(20), Quantity(0));
        assert_eq!(price_level.visible_quantity, Quantity(120));
        assert_eq!(price_level.hidden_quantity, Quantity(50));
        assert_eq!(price_level.order_count(), 3);

        price_level.mark_order_removed(Quantity(30), Quantity(0));
        assert_eq!(price_level.visible_quantity, Quantity(90));
        assert_eq!(price_level.hidden_quantity, Quantity(50));
        assert_eq!(price_level.order_count(), 2);

        price_level.mark_order_removed(Quantity(40), Quantity(0));
        assert_eq!(price_level.visible_quantity, Quantity(50));
        assert_eq!(price_level.hidden_quantity, Quantity(50));
        assert_eq!(price_level.order_count(), 1);

        price_level.mark_order_removed(Quantity(50), Quantity(50));
        assert_eq!(price_level.visible_quantity, Quantity(0));
        assert_eq!(price_level.hidden_quantity, Quantity(0));
        assert_eq!(price_level.order_count(), 0);
    }

    #[test]
    fn test_remove_head_order() {
        let mut limit_orders = FxHashMap::default();

        let mut price_level = PriceLevel::new();
        assert!(price_level.peek().is_none());

        limit_orders.insert(
            OrderId(0),
            RestingLimitOrder::new(
                SequenceNumber(0),
                0,
                LimitOrder::new(
                    Price(100),
                    QuantityPolicy::Standard {
                        quantity: Quantity(10),
                    },
                    OrderFlags::new(Side::Buy, true, TimeInForce::Gtc),
                ),
            ),
        );
        price_level.add_order_entry(
            QueueEntry::new(SequenceNumber(0), OrderId(0)),
            Quantity(10),
            Quantity(0),
        );
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(0), OrderId(0)))
        );

        price_level.remove_head_order(&mut limit_orders);
        assert!(price_level.peek().is_none());

        limit_orders.insert(
            OrderId(1),
            RestingLimitOrder::new(
                SequenceNumber(1),
                0,
                LimitOrder::new(
                    Price(100),
                    QuantityPolicy::Standard {
                        quantity: Quantity(20),
                    },
                    OrderFlags::new(Side::Buy, true, TimeInForce::Gtc),
                ),
            ),
        );
        price_level.add_order_entry(
            QueueEntry::new(SequenceNumber(1), OrderId(1)),
            Quantity(20),
            Quantity(0),
        );
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(1), OrderId(1)))
        );

        limit_orders.insert(
            OrderId(2),
            RestingLimitOrder::new(
                SequenceNumber(2),
                0,
                LimitOrder::new(
                    Price(100),
                    QuantityPolicy::Standard {
                        quantity: Quantity(30),
                    },
                    OrderFlags::new(Side::Buy, true, TimeInForce::Gtc),
                ),
            ),
        );
        price_level.add_order_entry(
            QueueEntry::new(SequenceNumber(2), OrderId(2)),
            Quantity(30),
            Quantity(0),
        );
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(1), OrderId(1)))
        );

        price_level.remove_head_order(&mut limit_orders);
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(2), OrderId(2)))
        );

        price_level.remove_head_order(&mut limit_orders);
        assert!(price_level.peek().is_none());
    }

    #[test]
    fn test_reprioritize_front() {
        let mut price_level = PriceLevel::new();
        assert_eq!(price_level.peek(), None);

        price_level.push(QueueEntry::new(SequenceNumber(0), OrderId(0)));
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(0), OrderId(0)))
        );

        price_level.reprioritize_front(SequenceNumber(1));
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(1), OrderId(0)))
        );

        price_level.push(QueueEntry::new(SequenceNumber(2), OrderId(2)));
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(1), OrderId(0)))
        );

        price_level.reprioritize_front(SequenceNumber(3));
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(2), OrderId(2)))
        );

        price_level.reprioritize_front(SequenceNumber(4));
        assert_eq!(
            price_level.peek(),
            Some(QueueEntry::new(SequenceNumber(3), OrderId(0)))
        );
    }

    #[test]
    fn test_apply_replenishment() {
        let mut price_level = PriceLevel::new();
        assert_eq!(price_level.visible_quantity, Quantity(0));
        assert_eq!(price_level.hidden_quantity, Quantity(0));

        price_level.visible_quantity = Quantity(10);
        price_level.hidden_quantity = Quantity(100);

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(20));
        assert_eq!(price_level.hidden_quantity, Quantity(90));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(30));
        assert_eq!(price_level.hidden_quantity, Quantity(80));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(40));
        assert_eq!(price_level.hidden_quantity, Quantity(70));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(50));
        assert_eq!(price_level.hidden_quantity, Quantity(60));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(60));
        assert_eq!(price_level.hidden_quantity, Quantity(50));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(70));
        assert_eq!(price_level.hidden_quantity, Quantity(40));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(80));
        assert_eq!(price_level.hidden_quantity, Quantity(30));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(90));
        assert_eq!(price_level.hidden_quantity, Quantity(20));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(100));
        assert_eq!(price_level.hidden_quantity, Quantity(10));

        price_level.apply_replenishment(Quantity(10));
        assert_eq!(price_level.visible_quantity, Quantity(110));
        assert_eq!(price_level.hidden_quantity, Quantity(0));
    }
}