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
//! Order representation and lifecycle
use crate::{OrderId, Price, Quantity, Side, TimeInForce, Timestamp};
/// Opaque identifier for the party that submitted an order.
///
/// Used by the matching engine for self-trade prevention (STP). Values
/// are caller-assigned and opaque — the engine never interprets them,
/// only compares them for equality. Any `u32` is a valid owner; callers
/// can map it to a user id, account id, or desk id as they see fit.
///
/// An order with `owner = None` opts out of STP entirely: it will match
/// against any counterparty regardless of policy.
///
/// See [`StpPolicy`](crate::matching::StpPolicy).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OrderOwner(pub u32);
/// Status of an order in its lifecycle.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum OrderStatus {
/// Order accepted, resting on book (no fills yet)
#[default]
New,
/// Some quantity filled, remainder still on book
PartiallyFilled,
/// Fully executed, no longer on book
Filled,
/// Removed by user request or TIF rules, no longer on book
Cancelled,
}
impl OrderStatus {
/// Returns true if the order is still active (can be filled or cancelled).
#[inline]
pub fn is_active(self) -> bool {
matches!(self, OrderStatus::New | OrderStatus::PartiallyFilled)
}
/// Returns true if the order is terminal (no further state changes).
#[inline]
pub fn is_terminal(self) -> bool {
matches!(self, OrderStatus::Filled | OrderStatus::Cancelled)
}
}
/// An order in the order book.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Order {
/// Unique identifier assigned by exchange
pub id: OrderId,
/// Buy or sell
pub side: Side,
/// Limit price (max for buy, min for sell)
pub price: Price,
/// Original quantity when submitted
pub original_quantity: Quantity,
/// Quantity still available to fill
pub remaining_quantity: Quantity,
/// Quantity that has been filled
pub filled_quantity: Quantity,
/// When the order was received by exchange
pub timestamp: Timestamp,
/// How long the order stays active
pub time_in_force: TimeInForce,
/// Current lifecycle status
pub status: OrderStatus,
/// Owner for self-trade prevention; `None` opts out of STP.
pub owner: Option<OrderOwner>,
/// Position index within the price level queue (for O(1) cancel)
pub(crate) position_in_level: usize,
}
impl Order {
/// Create a new order with the given parameters.
///
/// The order starts with `remaining_quantity == original_quantity`,
/// `filled_quantity == 0`, and `status == New`.
pub fn new(
id: OrderId,
side: Side,
price: Price,
quantity: Quantity,
timestamp: Timestamp,
time_in_force: TimeInForce,
) -> Self {
Self {
id,
side,
price,
original_quantity: quantity,
remaining_quantity: quantity,
filled_quantity: 0,
timestamp,
time_in_force,
status: OrderStatus::New,
owner: None,
position_in_level: 0,
}
}
/// Attach an owner for self-trade prevention, consuming `self`.
///
/// Convenience builder for the `Order::new(..).with_owner(OrderOwner(42))`
/// pattern.
#[inline]
pub fn with_owner(mut self, owner: OrderOwner) -> Self {
self.owner = Some(owner);
self
}
/// Decrement `remaining_quantity` without recording a fill.
///
/// Used by the matching engine when self-trade prevention causes a
/// portion of the order to be cancelled without a trade being
/// generated (see [`crate::matching::StpPolicy::DecrementAndCancel`]).
/// Sets status to `Cancelled` when the remainder reaches zero.
///
/// # Panics
///
/// Panics if `quantity > remaining_quantity`.
pub(crate) fn stp_decrement(&mut self, quantity: Quantity) {
assert!(
quantity <= self.remaining_quantity,
"stp_decrement {} exceeds remaining {}",
quantity,
self.remaining_quantity
);
self.remaining_quantity -= quantity;
if self.remaining_quantity == 0 {
self.status = OrderStatus::Cancelled;
}
}
/// Returns true if the order can still be filled or cancelled.
#[inline]
pub fn is_active(&self) -> bool {
self.status.is_active()
}
/// Fill the order by the given quantity.
///
/// Updates `remaining_quantity`, `filled_quantity`, and `status`.
///
/// # Panics
///
/// Panics if `quantity > remaining_quantity`.
pub fn fill(&mut self, quantity: Quantity) {
assert!(
quantity <= self.remaining_quantity,
"fill quantity {} exceeds remaining {}",
quantity,
self.remaining_quantity
);
self.remaining_quantity -= quantity;
self.filled_quantity += quantity;
self.status = if self.remaining_quantity == 0 {
OrderStatus::Filled
} else {
OrderStatus::PartiallyFilled
};
}
/// Cancel the order, setting status to Cancelled.
///
/// Returns the quantity that was cancelled (remaining at time of cancel).
///
/// # Panics
///
/// Panics if the order is already in a terminal state.
pub fn cancel(&mut self) -> Quantity {
assert!(
self.is_active(),
"cannot cancel order in terminal state {:?}",
self.status
);
let cancelled = self.remaining_quantity;
self.remaining_quantity = 0;
self.status = OrderStatus::Cancelled;
cancelled
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_order(quantity: Quantity) -> Order {
Order::new(
OrderId(1),
Side::Buy,
Price(100_00),
quantity,
1,
TimeInForce::GTC,
)
}
#[test]
fn new_order_initial_state() {
let order = make_order(100);
assert_eq!(order.original_quantity, 100);
assert_eq!(order.remaining_quantity, 100);
assert_eq!(order.filled_quantity, 0);
assert_eq!(order.status, OrderStatus::New);
assert!(order.is_active());
}
#[test]
fn partial_fill() {
let mut order = make_order(100);
order.fill(30);
assert_eq!(order.remaining_quantity, 70);
assert_eq!(order.filled_quantity, 30);
assert_eq!(order.status, OrderStatus::PartiallyFilled);
assert!(order.is_active());
}
#[test]
fn full_fill() {
let mut order = make_order(100);
order.fill(100);
assert_eq!(order.remaining_quantity, 0);
assert_eq!(order.filled_quantity, 100);
assert_eq!(order.status, OrderStatus::Filled);
assert!(!order.is_active());
}
#[test]
fn multiple_partial_fills() {
let mut order = make_order(100);
order.fill(30);
order.fill(50);
order.fill(20);
assert_eq!(order.remaining_quantity, 0);
assert_eq!(order.filled_quantity, 100);
assert_eq!(order.status, OrderStatus::Filled);
}
#[test]
#[should_panic(expected = "fill quantity 101 exceeds remaining 100")]
fn fill_exceeds_remaining_panics() {
let mut order = make_order(100);
order.fill(101);
}
#[test]
fn cancel_new_order() {
let mut order = make_order(100);
let cancelled = order.cancel();
assert_eq!(cancelled, 100);
assert_eq!(order.remaining_quantity, 0);
assert_eq!(order.status, OrderStatus::Cancelled);
assert!(!order.is_active());
}
#[test]
fn cancel_partially_filled_order() {
let mut order = make_order(100);
order.fill(30);
let cancelled = order.cancel();
assert_eq!(cancelled, 70);
assert_eq!(order.filled_quantity, 30);
assert_eq!(order.remaining_quantity, 0);
assert_eq!(order.status, OrderStatus::Cancelled);
}
#[test]
#[should_panic(expected = "cannot cancel order in terminal state")]
fn cancel_filled_order_panics() {
let mut order = make_order(100);
order.fill(100);
order.cancel();
}
#[test]
#[should_panic(expected = "cannot cancel order in terminal state")]
fn cancel_already_cancelled_panics() {
let mut order = make_order(100);
order.cancel();
order.cancel();
}
#[test]
fn order_status_is_active() {
assert!(OrderStatus::New.is_active());
assert!(OrderStatus::PartiallyFilled.is_active());
assert!(!OrderStatus::Filled.is_active());
assert!(!OrderStatus::Cancelled.is_active());
}
#[test]
fn order_status_is_terminal() {
assert!(!OrderStatus::New.is_terminal());
assert!(!OrderStatus::PartiallyFilled.is_terminal());
assert!(OrderStatus::Filled.is_terminal());
assert!(OrderStatus::Cancelled.is_terminal());
}
#[test]
fn quantity_invariant_holds() {
let mut order = make_order(100);
// After partial fill
order.fill(30);
assert_eq!(
order.original_quantity,
order.remaining_quantity + order.filled_quantity
);
// After another fill
order.fill(50);
assert_eq!(
order.original_quantity,
order.remaining_quantity + order.filled_quantity
);
}
}