nautilus-model 0.55.0

Domain model for the Nautilus trading engine
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
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

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

use nautilus_core::ffi::{abort_on_panic, cvec::CVec, string::str_to_cstr};

use super::level::BookLevel_API;
use crate::{
    data::{
        BookOrder, OrderBookDelta, OrderBookDeltas_API, OrderBookDepth10, QuoteTick, TradeTick,
    },
    enums::{BookType, OrderSide, OrderSideSpecified},
    identifiers::InstrumentId,
    orderbook::{OrderBook, analysis::book_check_integrity, ladder::BookPrice},
    types::{ERROR_PRICE, Price, Quantity, price::PriceRaw},
};

/// C compatible Foreign Function Interface (FFI) for an underlying `OrderBook`.
///
/// This struct wraps `OrderBook` in a way that makes it compatible with C function
/// calls, enabling interaction with `OrderBook` in a C environment.
///
/// It implements the `Deref` trait, allowing instances of `OrderBook_API` to be
/// dereferenced to `OrderBook`, providing access to `OrderBook`'s methods without
/// having to manually access the underlying `OrderBook` instance.
#[repr(C)]
#[derive(Debug)]
#[allow(non_camel_case_types)]
pub struct OrderBook_API(Box<OrderBook>);

impl Deref for OrderBook_API {
    type Target = OrderBook;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for OrderBook_API {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_new(instrument_id: InstrumentId, book_type: BookType) -> OrderBook_API {
    OrderBook_API(Box::new(OrderBook::new(instrument_id, book_type)))
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_drop(book: OrderBook_API) {
    drop(book); // Memory freed here
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_reset(book: &mut OrderBook_API) {
    book.reset();
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_instrument_id(book: &OrderBook_API) -> InstrumentId {
    book.instrument_id
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_book_type(book: &OrderBook_API) -> BookType {
    book.book_type
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_sequence(book: &OrderBook_API) -> u64 {
    book.sequence
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_ts_last(book: &OrderBook_API) -> u64 {
    book.ts_last.into()
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_update_count(book: &OrderBook_API) -> u64 {
    book.update_count
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_add(
    book: &mut OrderBook_API,
    order: BookOrder,
    flags: u8,
    sequence: u64,
    ts_event: u64,
) {
    book.add(order, flags, sequence, ts_event.into());
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_update(
    book: &mut OrderBook_API,
    order: BookOrder,
    flags: u8,
    sequence: u64,
    ts_event: u64,
) {
    book.update(order, flags, sequence, ts_event.into());
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_delete(
    book: &mut OrderBook_API,
    order: BookOrder,
    flags: u8,
    sequence: u64,
    ts_event: u64,
) {
    book.delete(order, flags, sequence, ts_event.into());
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_clear(book: &mut OrderBook_API, sequence: u64, ts_event: u64) {
    book.clear(sequence, ts_event.into());
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_clear_bids(book: &mut OrderBook_API, sequence: u64, ts_event: u64) {
    book.clear_bids(sequence, ts_event.into());
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_clear_asks(book: &mut OrderBook_API, sequence: u64, ts_event: u64) {
    book.clear_asks(sequence, ts_event.into());
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_apply_delta(book: &mut OrderBook_API, delta: &OrderBookDelta) {
    if let Err(e) = book.apply_delta_unchecked(delta) {
        log::error!("Failed to apply order book delta: {e}");
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_apply_deltas(book: &mut OrderBook_API, deltas: &OrderBookDeltas_API) {
    // Clone will actually copy the contents of the `deltas` vec
    if let Err(e) = book.apply_deltas_unchecked(deltas.deref()) {
        log::error!("Failed to apply order book deltas: {e}");
    }
}

/// Creates an `OrderBookDeltas` snapshot from the current order book state.
///
/// This is the reverse operation of `orderbook_apply_deltas`: it converts the current book state
/// back into a snapshot format with a `Clear` delta followed by `Add` deltas for all orders.
///
/// # Parameters
///
/// * `book` - The order book to convert.
/// * `sequence` - The message sequence number for the snapshot.
/// * `ts_event` - UNIX timestamp (nanoseconds) when the book event occurred.
/// * `ts_init` - UNIX timestamp (nanoseconds) when the instance was created.
///
/// # Returns
///
/// An `OrderBookDeltas_API` containing a snapshot of the current order book state.
#[unsafe(no_mangle)]
pub extern "C" fn orderbook_to_snapshot_deltas(
    book: &OrderBook_API,
    ts_event: u64,
    ts_init: u64,
) -> OrderBookDeltas_API {
    use nautilus_core::UnixNanos;
    OrderBookDeltas_API::new(book.to_deltas(UnixNanos::from(ts_event), UnixNanos::from(ts_init)))
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_apply_depth(book: &mut OrderBook_API, depth: &OrderBookDepth10) {
    if let Err(e) = book.apply_depth_unchecked(depth) {
        log::error!("Failed to apply order book depth: {e}");
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_bids(book: &mut OrderBook_API) -> CVec {
    book.bids
        .levels
        .values()
        .map(|level| BookLevel_API::new(level.clone()))
        .collect::<Vec<BookLevel_API>>()
        .into()
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_asks(book: &mut OrderBook_API) -> CVec {
    book.asks
        .levels
        .values()
        .map(|level| BookLevel_API::new(level.clone()))
        .collect::<Vec<BookLevel_API>>()
        .into()
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_bids_down_to(
    book: &mut OrderBook_API,
    price_raw: PriceRaw,
    price_prec: u8,
) -> CVec {
    let price = Price::from_raw(price_raw, price_prec);
    let bound = BookPrice::new(price, OrderSideSpecified::Buy);
    book.bids
        .levels
        .range(..=bound)
        .map(|(_, level)| BookLevel_API::new(level.clone()))
        .collect::<Vec<BookLevel_API>>()
        .into()
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_asks_up_to(
    book: &mut OrderBook_API,
    price_raw: PriceRaw,
    price_prec: u8,
) -> CVec {
    let price = Price::from_raw(price_raw, price_prec);
    let bound = BookPrice::new(price, OrderSideSpecified::Sell);
    book.asks
        .levels
        .range(..=bound)
        .map(|(_, level)| BookLevel_API::new(level.clone()))
        .collect::<Vec<BookLevel_API>>()
        .into()
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_has_bid(book: &mut OrderBook_API) -> u8 {
    u8::from(book.has_bid())
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_has_ask(book: &mut OrderBook_API) -> u8 {
    u8::from(book.has_ask())
}

/// # Panics
///
/// Panics if there are no bid orders for best bid price.
#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_best_bid_price(book: &mut OrderBook_API) -> Price {
    abort_on_panic(|| {
        book.best_bid_price()
            .expect("Error: No bid orders for best bid price")
    })
}

/// # Panics
///
/// Panics if there are no ask orders for best ask price.
#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_best_ask_price(book: &mut OrderBook_API) -> Price {
    abort_on_panic(|| {
        book.best_ask_price()
            .expect("Error: No ask orders for best ask price")
    })
}

/// # Panics
///
/// Panics if there are no bid orders for best bid size.
#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_best_bid_size(book: &mut OrderBook_API) -> Quantity {
    abort_on_panic(|| {
        book.best_bid_size()
            .expect("Error: No bid orders for best bid size")
    })
}

/// # Panics
///
/// Panics if there are no ask orders for best ask size.
#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_best_ask_size(book: &mut OrderBook_API) -> Quantity {
    abort_on_panic(|| {
        book.best_ask_size()
            .expect("Error: No ask orders for best ask size")
    })
}

/// # Panics
///
/// Panics if unable to calculate spread (requires at least one bid and one ask).
#[unsafe(no_mangle)]
pub extern "C" fn orderbook_spread(book: &mut OrderBook_API) -> f64 {
    abort_on_panic(|| {
        book.spread()
            .expect("Error: Unable to calculate `spread` (no bid or ask)")
    })
}

/// # Panics
///
/// Panics if unable to calculate midpoint (requires at least one bid and one ask).
#[unsafe(no_mangle)]
pub extern "C" fn orderbook_midpoint(book: &mut OrderBook_API) -> f64 {
    abort_on_panic(|| {
        book.midpoint()
            .expect("Error: Unable to calculate `midpoint` (no bid or ask)")
    })
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_get_avg_px_for_quantity(
    book: &mut OrderBook_API,
    qty: Quantity,
    order_side: OrderSide,
) -> f64 {
    book.get_avg_px_for_quantity(qty, order_side)
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_get_worst_px_for_quantity(
    book: &mut OrderBook_API,
    qty: Quantity,
    order_side: OrderSide,
) -> Price {
    book.get_worst_px_for_quantity(qty, order_side)
        .unwrap_or(ERROR_PRICE)
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_get_quantity_for_price(
    book: &mut OrderBook_API,
    price: Price,
    order_side: OrderSide,
) -> f64 {
    book.get_quantity_for_price(price, order_side)
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_get_quantity_at_level(
    book: &OrderBook_API,
    price: Price,
    order_side: OrderSide,
    size_precision: u8,
) -> Quantity {
    book.get_quantity_at_level(price, order_side, size_precision)
}

/// Updates the order book with a quote tick.
///
/// # Panics
///
/// Panics if book type is not `L1_MBP`.
#[unsafe(no_mangle)]
pub extern "C" fn orderbook_update_quote_tick(book: &mut OrderBook_API, quote: &QuoteTick) {
    book.update_quote_tick(quote).unwrap();
}

/// Updates the order book with a trade tick.
///
/// # Panics
///
/// Panics if book type is not `L1_MBP`.
#[unsafe(no_mangle)]
pub extern "C" fn orderbook_update_trade_tick(book: &mut OrderBook_API, trade: &TradeTick) {
    book.update_trade_tick(trade).unwrap();
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_simulate_fills(book: &OrderBook_API, order: BookOrder) -> CVec {
    book.simulate_fills(&order).into()
}

#[unsafe(no_mangle)]
#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
pub extern "C" fn orderbook_get_all_crossed_levels(
    book: &OrderBook_API,
    order_side: OrderSide,
    price: Price,
    size_precision: u8,
) -> CVec {
    book.get_all_crossed_levels(order_side, price, size_precision)
        .into()
}

#[unsafe(no_mangle)]
pub extern "C" fn orderbook_check_integrity(book: &OrderBook_API) -> u8 {
    u8::from(book_check_integrity(book).is_ok())
}

#[unsafe(no_mangle)]
pub extern "C" fn vec_drop_fills(v: CVec) {
    if v.ptr.is_null() {
        return;
    }

    let CVec { ptr, len, cap } = v;
    let data: Vec<(Price, Quantity)> =
        unsafe { Vec::from_raw_parts(ptr.cast::<(Price, Quantity)>(), len, cap) };
    drop(data); // Memory freed here
}

/// Returns a pretty printed `OrderBook` number of levels per side, as a C string pointer.
#[unsafe(no_mangle)]
pub extern "C" fn orderbook_pprint_to_cstr(
    book: &OrderBook_API,
    num_levels: usize,
) -> *const c_char {
    str_to_cstr(&book.pprint(num_levels, None))
}