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
//! Order book operations like adding, modifying and canceling orders
use super::book::OrderBook;
use super::error::OrderBookError;
use pricelevel::{Hash32, Id, MatchResult, OrderType, Price, Quantity, Side, TimeInForce};
use std::sync::Arc;
use tracing::trace;
impl<T> OrderBook<T>
where
T: Clone + Send + Sync + Default + 'static,
{
/// Add a limit order to the book.
///
/// This convenience method sets `user_id` to `Hash32::zero()`. When STP
/// is enabled on this book, use [`Self::add_limit_order_with_user`] instead
/// to supply the owner identity.
///
/// # Errors
/// Returns [`OrderBookError::MissingUserId`] when STP is enabled.
pub fn add_limit_order(
&self,
id: Id,
price: u128,
quantity: u64,
side: Side,
time_in_force: TimeInForce,
extra_fields: Option<T>,
) -> Result<Arc<OrderType<T>>, OrderBookError> {
self.add_limit_order_with_user(
id,
price,
quantity,
side,
time_in_force,
Hash32::zero(),
extra_fields,
)
}
/// Add a limit order to the book with an explicit `user_id`.
///
/// When Self-Trade Prevention (STP) is enabled, `user_id` must be non-zero
/// so the matching engine can detect same-user conflicts.
///
/// # Arguments
/// * `id` — Unique order identifier.
/// * `price` — Limit price.
/// * `quantity` — Order quantity.
/// * `side` — Buy or Sell.
/// * `time_in_force` — Time-in-force policy.
/// * `user_id` — Owner identity for STP checks.
/// * `extra_fields` — Optional application-specific payload.
///
/// # Errors
/// Returns [`OrderBookError::MissingUserId`] when STP is enabled and
/// `user_id` is `Hash32::zero()`.
#[allow(clippy::too_many_arguments)]
pub fn add_limit_order_with_user(
&self,
id: Id,
price: u128,
quantity: u64,
side: Side,
time_in_force: TimeInForce,
user_id: Hash32,
extra_fields: Option<T>,
) -> Result<Arc<OrderType<T>>, OrderBookError> {
// Top-of-fn kill-switch gate so we skip the clock read and
// extra_fields / OrderType construction below when halted.
self.check_kill_switch_or_reject(id)?;
let extra_fields: T = extra_fields.unwrap_or_default();
let order = OrderType::Standard {
id,
price: Price::new(price),
quantity: Quantity::new(quantity),
side,
user_id,
timestamp: self.clock().now_millis(),
time_in_force,
extra_fields,
};
trace!(
"Adding limit order {} {} {} {} {}",
id, price, quantity, side, time_in_force
);
self.add_order(order)
}
/// Add an iceberg order to the book.
///
/// This convenience method sets `user_id` to `Hash32::zero()`. When STP
/// is enabled, use [`Self::add_iceberg_order_with_user`] instead.
///
/// # Errors
/// Returns [`OrderBookError::MissingUserId`] when STP is enabled.
#[allow(clippy::too_many_arguments)]
pub fn add_iceberg_order(
&self,
id: Id,
price: u128,
visible_quantity: u64,
hidden_quantity: u64,
side: Side,
time_in_force: TimeInForce,
extra_fields: Option<T>,
) -> Result<Arc<OrderType<T>>, OrderBookError> {
self.add_iceberg_order_with_user(
id,
price,
visible_quantity,
hidden_quantity,
side,
time_in_force,
Hash32::zero(),
extra_fields,
)
}
/// Add an iceberg order to the book with an explicit `user_id`.
///
/// # Arguments
/// * `id` — Unique order identifier.
/// * `price` — Limit price.
/// * `visible_quantity` — Displayed quantity.
/// * `hidden_quantity` — Hidden (reserve) quantity.
/// * `side` — Buy or Sell.
/// * `time_in_force` — Time-in-force policy.
/// * `user_id` — Owner identity for STP checks.
/// * `extra_fields` — Optional application-specific payload.
///
/// # Errors
/// Returns [`OrderBookError::MissingUserId`] when STP is enabled and
/// `user_id` is `Hash32::zero()`.
#[allow(clippy::too_many_arguments)]
pub fn add_iceberg_order_with_user(
&self,
id: Id,
price: u128,
visible_quantity: u64,
hidden_quantity: u64,
side: Side,
time_in_force: TimeInForce,
user_id: Hash32,
extra_fields: Option<T>,
) -> Result<Arc<OrderType<T>>, OrderBookError> {
// Top-of-fn kill-switch gate so we skip the clock read and
// extra_fields / OrderType construction below when halted.
self.check_kill_switch_or_reject(id)?;
let extra_fields: T = extra_fields.unwrap_or_default();
let order = OrderType::IcebergOrder {
id,
price: Price::new(price),
visible_quantity: Quantity::new(visible_quantity),
hidden_quantity: Quantity::new(hidden_quantity),
side,
user_id,
timestamp: self.clock().now_millis(),
time_in_force,
extra_fields,
};
trace!(
"Adding iceberg order {} {} {} {} {}",
id, price, visible_quantity, hidden_quantity, side
);
self.add_order(order)
}
/// Add a post-only order to the book.
///
/// This convenience method sets `user_id` to `Hash32::zero()`. When STP
/// is enabled, use [`Self::add_post_only_order_with_user`] instead.
///
/// # Errors
/// Returns [`OrderBookError::MissingUserId`] when STP is enabled.
pub fn add_post_only_order(
&self,
id: Id,
price: u128,
quantity: u64,
side: Side,
time_in_force: TimeInForce,
extra_fields: Option<T>,
) -> Result<Arc<OrderType<T>>, OrderBookError> {
self.add_post_only_order_with_user(
id,
price,
quantity,
side,
time_in_force,
Hash32::zero(),
extra_fields,
)
}
/// Add a post-only order to the book with an explicit `user_id`.
///
/// # Arguments
/// * `id` — Unique order identifier.
/// * `price` — Limit price.
/// * `quantity` — Order quantity.
/// * `side` — Buy or Sell.
/// * `time_in_force` — Time-in-force policy.
/// * `user_id` — Owner identity for STP checks.
/// * `extra_fields` — Optional application-specific payload.
///
/// # Errors
/// Returns [`OrderBookError::MissingUserId`] when STP is enabled and
/// `user_id` is `Hash32::zero()`.
#[allow(clippy::too_many_arguments)]
pub fn add_post_only_order_with_user(
&self,
id: Id,
price: u128,
quantity: u64,
side: Side,
time_in_force: TimeInForce,
user_id: Hash32,
extra_fields: Option<T>,
) -> Result<Arc<OrderType<T>>, OrderBookError> {
// Top-of-fn kill-switch gate so we skip the clock read and
// extra_fields / OrderType construction below when halted.
self.check_kill_switch_or_reject(id)?;
let extra_fields: T = extra_fields.unwrap_or_default();
let order = OrderType::PostOnly {
id,
price: Price::new(price),
quantity: Quantity::new(quantity),
side,
user_id,
timestamp: self.clock().now_millis(),
time_in_force,
extra_fields,
};
trace!(
"Adding post-only order {} {} {} {} {}",
id, price, quantity, side, time_in_force
);
self.add_order(order)
}
/// Submit a simple market order.
///
/// This convenience method bypasses STP (uses `Hash32::zero()`).
/// Use [`Self::submit_market_order_with_user`] when STP is needed.
///
/// # Errors
/// Returns [`OrderBookError::KillSwitchActive`] when the kill switch
/// is engaged. The check happens at the top of the function before
/// any matching, fee, or STP work.
pub fn submit_market_order(
&self,
id: Id,
quantity: u64,
side: Side,
) -> Result<MatchResult, OrderBookError> {
self.check_kill_switch_or_reject(id)?;
// Pre-trade risk gate. Per design decision C, market orders
// currently bypass every check (no submitted price; no rest);
// the call exists to keep the gate ordering consistent across
// submit and add paths.
self.risk_state.check_market_admission(Hash32::zero())?;
trace!("Submitting market order {} {} {}", id, quantity, side);
OrderBook::<T>::match_market_order(self, id, quantity, side)
}
/// Submit a market order with Self-Trade Prevention support.
///
/// When STP is enabled and `user_id` is non-zero, the matching engine
/// checks resting orders for same-user conflicts before executing fills.
///
/// # Arguments
/// * `id` — Unique identifier for this market order.
/// * `quantity` — Quantity to match.
/// * `side` — Buy or Sell.
/// * `user_id` — Owner of the incoming order for STP checks.
/// Pass `Hash32::zero()` to bypass STP.
///
/// # Errors
/// Returns [`OrderBookError::SelfTradePrevented`] when STP cancels the
/// taker before any fills occur. Returns
/// [`OrderBookError::KillSwitchActive`] when the kill switch is
/// engaged; the check happens at the top of the function before any
/// matching, fee, or STP work.
pub fn submit_market_order_with_user(
&self,
id: Id,
quantity: u64,
side: Side,
user_id: Hash32,
) -> Result<MatchResult, OrderBookError> {
self.check_kill_switch_or_reject(id)?;
// Pre-trade risk gate. Per design decision C, market orders
// currently bypass every check; the call exists to keep the
// gate ordering consistent across submit and add paths.
self.risk_state.check_market_admission(user_id)?;
trace!(
"Submitting market order {} {} {} (user: {})",
id, quantity, side, user_id
);
OrderBook::<T>::match_market_order_with_user(self, id, quantity, side, user_id)
}
}