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
use super::{LimitOrder, MarketOrder};
use crate::{LevelId, Price, SequenceNumber, Side, Timestamp};

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

/// Represents a resting price-conditional order
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestingPriceConditionalOrder {
    /// The time priority of the order
    time_priority: SequenceNumber,
    /// The ID of the level the order is resting at
    level_id: LevelId,
    /// The price-conditional order
    inner: PriceConditionalOrder,
}

impl RestingPriceConditionalOrder {
    /// Create a new resting price-conditional order
    pub fn new(
        time_priority: SequenceNumber,
        level_id: LevelId,
        inner: PriceConditionalOrder,
    ) -> Self {
        Self {
            time_priority,
            level_id,
            inner,
        }
    }

    /// Get the time priority of the order
    pub fn time_priority(&self) -> SequenceNumber {
        self.time_priority
    }

    /// Update the time priority of the order
    pub(crate) fn update_time_priority(&mut self, new_time_priority: SequenceNumber) {
        self.time_priority = new_time_priority;
    }

    /// Get the ID of the level the order is resting at
    pub fn level_id(&self) -> LevelId {
        self.level_id
    }

    /// Update the ID of the level the order is resting at
    pub(crate) fn update_level_id(&mut self, new_level_id: LevelId) {
        self.level_id = new_level_id;
    }

    /// Get the price-conditional order
    pub fn inner(&self) -> &PriceConditionalOrder {
        &self.inner
    }

    /// Convert the resting price-conditional order into a price-conditional order
    pub fn into_inner(self) -> PriceConditionalOrder {
        self.inner
    }
}

impl Deref for RestingPriceConditionalOrder {
    type Target = PriceConditionalOrder;

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

/// Represents a price-conditional order
///
/// A price-conditional order remains inactive until a specified price condition is satisfied.
/// For example, the order may be activated when the market price is at or above (or at or below) a given trigger price.
///
/// Once the condition is met, the order is activated and a new order is submitted to the order book.
/// The resulting order is treated as a fresh submission with its own time priority.
///
/// The activated order can be either a market order or a limit order, allowing
/// this type to model a variety of common conditional orders, including:
///
/// - Stop-loss orders
/// - Take-profit orders
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PriceConditionalOrder {
    /// The condition that must be met for the order to be activated
    price_condition: PriceCondition,
    /// The target order to execute when the condition is met
    target_order: TriggerOrder,
}

impl PriceConditionalOrder {
    /// Create a new stop market order
    pub fn stop_market(trigger_price: Price, order: MarketOrder) -> Self {
        Self::new(
            PriceCondition::new(trigger_price, TriggerDirection::stop(order.side())),
            TriggerOrder::Market(order),
        )
    }

    /// Create a new stop limit order
    pub fn stop_limit(trigger_price: Price, order: LimitOrder) -> Self {
        Self::new(
            PriceCondition::new(trigger_price, TriggerDirection::stop(order.side())),
            TriggerOrder::Limit(order),
        )
    }

    /// Create a new take profit market order
    pub fn take_profit_market(trigger_price: Price, order: MarketOrder) -> Self {
        Self::new(
            PriceCondition::new(trigger_price, TriggerDirection::take_profit(order.side())),
            TriggerOrder::Market(order),
        )
    }

    /// Create a new take profit limit order
    pub fn take_profit_limit(trigger_price: Price, order: LimitOrder) -> Self {
        Self::new(
            PriceCondition::new(trigger_price, TriggerDirection::take_profit(order.side())),
            TriggerOrder::Limit(order),
        )
    }
}

impl PriceConditionalOrder {
    /// Create a new price-conditional order
    pub fn new(price_condition: PriceCondition, target_order: TriggerOrder) -> Self {
        Self {
            price_condition,
            target_order,
        }
    }

    /// Get the condition that must be met for the order to be activated
    pub fn price_condition(&self) -> PriceCondition {
        self.price_condition
    }

    /// Update the condition that must be met for the order to be activated
    pub(crate) fn update_price_condition(&mut self, new_price_condition: PriceCondition) {
        self.price_condition = new_price_condition;
    }

    /// Get the target order to execute when the condition is met
    pub fn target_order(&self) -> &TriggerOrder {
        &self.target_order
    }

    /// Convert the price-conditional order into its target order to execute when the condition is met
    pub fn into_target_order(self) -> TriggerOrder {
        self.target_order
    }

    /// Update the target order to execute when the condition is met
    pub(crate) fn update_target_order(&mut self, new_target_order: TriggerOrder) {
        self.target_order = new_target_order;
    }

    /// Check if the target order is expired at a given timestamp
    pub fn is_expired(&self, timestamp: Timestamp) -> bool {
        self.target_order.is_expired(timestamp)
    }

    /// Check if the price-conditional order is ready to be activated at a given price
    pub fn is_ready(&self, price: Price) -> bool {
        self.price_condition.is_met(price)
    }
}

impl Deref for PriceConditionalOrder {
    type Target = PriceCondition;

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

/// Represents the condition that must be met for a price-conditional order to be activated
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PriceCondition {
    /// The reference price that defines when the condition activates
    trigger_price: Price,
    /// The condition direction:
    /// - `AtOrAbove`: activates when market price >= `trigger_price`
    /// - `AtOrBelow`: activates when market price <= `trigger_price`
    direction: TriggerDirection,
}

impl PriceCondition {
    /// Create a new price condition
    pub fn new(trigger_price: Price, direction: TriggerDirection) -> Self {
        Self {
            trigger_price,
            direction,
        }
    }

    /// Get the reference price that defines when the condition activates
    pub fn trigger_price(&self) -> Price {
        self.trigger_price
    }

    /// Get the direction in which the price must move relative to `trigger_price`
    pub fn direction(&self) -> TriggerDirection {
        self.direction
    }

    /// Check if the price condition is met at a given price
    pub fn is_met(&self, price: Price) -> bool {
        match self.direction() {
            TriggerDirection::AtOrAbove => price >= self.trigger_price(),
            TriggerDirection::AtOrBelow => price <= self.trigger_price(),
        }
    }
}

/// Direction of trigger evaluation relative to the trigger price
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TriggerDirection {
    /// Trigger when the observed price >= trigger_price
    AtOrAbove,
    /// Trigger when the observed price <= trigger_price
    AtOrBelow,
}

impl TriggerDirection {
    /// Create a new stop trigger direction
    pub fn stop(side: Side) -> Self {
        match side {
            Side::Buy => Self::AtOrAbove,
            Side::Sell => Self::AtOrBelow,
        }
    }

    /// Create a new take profit trigger direction
    pub fn take_profit(side: Side) -> Self {
        match side {
            Side::Buy => Self::AtOrBelow,
            Side::Sell => Self::AtOrAbove,
        }
    }
}

/// Represents the order to execute when the condition is met
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TriggerOrder {
    /// Execute a market order
    Market(MarketOrder),
    /// Execute a limit order
    Limit(LimitOrder),
}

impl TriggerOrder {
    /// Check if the order is expired at a given timestamp
    pub fn is_expired(&self, timestamp: Timestamp) -> bool {
        match self {
            TriggerOrder::Market(_) => false,
            TriggerOrder::Limit(order) => order.is_expired(timestamp),
        }
    }
}

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

    #[test]
    fn test_is_expired() {
        let test_ts = 1771180000;

        struct Case {
            name: &'static str,
            order: PriceConditionalOrder,
            expected: bool,
        }

        let cases = [
            Case {
                name: "market order",
                order: PriceConditionalOrder::new(
                    PriceCondition::new(Price(100), TriggerDirection::AtOrAbove),
                    TriggerOrder::Market(MarketOrder::new(Quantity(100), Side::Buy, true)),
                ),
                expected: false,
            },
            Case {
                name: "limit order (GTC)",
                order: PriceConditionalOrder::new(
                    PriceCondition::new(Price(100), TriggerDirection::AtOrAbove),
                    TriggerOrder::Limit(LimitOrder::new(
                        Price(100),
                        QuantityPolicy::Standard {
                            quantity: Quantity(100),
                        },
                        OrderFlags::new(Side::Buy, false, TimeInForce::Gtc),
                    )),
                ),
                expected: false,
            },
            Case {
                name: "limit order (unexpired GTD)",
                order: PriceConditionalOrder::new(
                    PriceCondition::new(Price(100), TriggerDirection::AtOrAbove),
                    TriggerOrder::Limit(LimitOrder::new(
                        Price(100),
                        QuantityPolicy::Standard {
                            quantity: Quantity(100),
                        },
                        OrderFlags::new(
                            Side::Buy,
                            false,
                            TimeInForce::Gtd(Timestamp(test_ts + 1000)),
                        ),
                    )),
                ),
                expected: false,
            },
            Case {
                name: "limit order (expired GTD)",
                order: PriceConditionalOrder::new(
                    PriceCondition::new(Price(100), TriggerDirection::AtOrAbove),
                    TriggerOrder::Limit(LimitOrder::new(
                        Price(100),
                        QuantityPolicy::Standard {
                            quantity: Quantity(100),
                        },
                        OrderFlags::new(Side::Buy, false, TimeInForce::Gtd(Timestamp(test_ts))),
                    )),
                ),
                expected: true,
            },
        ];

        for case in cases {
            assert_eq!(
                case.order.is_expired(Timestamp(test_ts)),
                case.expected,
                "case: {}",
                case.name
            );
        }
    }

    #[test]
    fn test_is_met() {
        struct Case {
            name: &'static str,
            price_condition: PriceCondition,
            market_price: Price,
            expected: bool,
        }

        let cases = [
            Case {
                name: "at or above trigger price",
                price_condition: PriceCondition::new(Price(100), TriggerDirection::AtOrAbove),
                market_price: Price(100),
                expected: true,
            },
            Case {
                name: "at or below trigger price",
                price_condition: PriceCondition::new(Price(100), TriggerDirection::AtOrBelow),
                market_price: Price(100),
                expected: true,
            },
            Case {
                name: "at or above trigger price (not ready)",
                price_condition: PriceCondition::new(Price(100), TriggerDirection::AtOrAbove),
                market_price: Price(99),
                expected: false,
            },
            Case {
                name: "at or below trigger price (not ready)",
                price_condition: PriceCondition::new(Price(100), TriggerDirection::AtOrBelow),
                market_price: Price(101),
                expected: false,
            },
        ];

        for case in cases {
            assert_eq!(
                case.price_condition.is_met(case.market_price),
                case.expected,
                "case: {}",
                case.name
            );
        }
    }
}