nautilus-model 0.58.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// -------------------------------------------------------------------------------------------------
//  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::{
    collections::HashSet,
    fmt::Display,
    hash::{Hash, Hasher},
};

use nautilus_core::UnixNanos;
use serde::{Deserialize, Serialize};

use crate::{
    identifiers::{ClientOrderId, InstrumentId, OrderListId, StrategyId},
    orders::{Order, OrderAny},
};

/// Lightweight identifier container for a group of related orders.
///
/// Stores only the order IDs; full order data lives in the cache.
/// For serialization payload, see `SubmitOrderList.order_inits`.
///
/// All orders should share the same venue. The production constructors
/// enforce this: [`OrderList::from_orders`] and `OrderFactory::create_list`
/// panic on mixed venues, and `Strategy::submit_order_list` bails at the
/// user-facing entry. [`OrderList::new`] is infallible and takes
/// `instrument_id` directly; it does not verify the venues of the supplied
/// `client_order_ids`. The `instrument_id` is a representative value taken
/// from the first order; orders may target different instruments at that
/// venue. Downstream consumers that need a per-order instrument should
/// resolve each order from the cache.
#[derive(Clone, Eq, Debug, Serialize, Deserialize)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
)]
pub struct OrderList {
    pub id: OrderListId,
    pub instrument_id: InstrumentId,
    pub strategy_id: StrategyId,
    pub client_order_ids: Vec<ClientOrderId>,
    pub ts_init: UnixNanos,
}

impl OrderList {
    /// Creates a new [`OrderList`] instance.
    ///
    /// Construction is infallible. [`OrderList::validate`] checks the
    /// syntactic invariants (non-empty, unique `client_order_ids`); the
    /// strategy submission path (`Strategy::submit_order_list`) runs it
    /// before the list reaches the cache.
    #[must_use]
    pub fn new(
        order_list_id: OrderListId,
        instrument_id: InstrumentId,
        strategy_id: StrategyId,
        client_order_ids: Vec<ClientOrderId>,
        ts_init: UnixNanos,
    ) -> Self {
        Self {
            id: order_list_id,
            instrument_id,
            strategy_id,
            client_order_ids,
            ts_init,
        }
    }

    /// Creates a new [`OrderList`] from a slice of orders.
    ///
    /// Derives `order_list_id`, `instrument_id`, and `strategy_id` from the
    /// first order. The `instrument_id` is representative only; orders in
    /// the list may target different instruments at the same venue.
    /// Callers in the production path (`OrderFactory` plus a single
    /// strategy instance) produce orders with a consistent `order_list_id`
    /// and `strategy_id`. [`OrderList::validate`] checks the syntactic
    /// invariants (non-empty, unique `client_order_ids`); it does not
    /// check cross-field consistency.
    ///
    /// # Panics
    ///
    /// Panics if `orders` is empty, if the first order has no
    /// `order_list_id`, or if orders span more than one venue. Callers
    /// are expected to guard non-empty input; `Strategy::submit_order_list`
    /// filters out the empty case and bails on mixed venues before
    /// reaching this constructor.
    #[must_use]
    pub fn from_orders(orders: &[OrderAny], ts_init: UnixNanos) -> Self {
        let first = orders
            .first()
            .expect("OrderList::from_orders requires non-empty orders");
        let order_list_id = first
            .order_list_id()
            .expect("OrderList::from_orders requires first order to have order_list_id");
        let instrument_id = first.instrument_id();
        let strategy_id = first.strategy_id();
        let venue = instrument_id.venue;

        for order in orders {
            assert!(
                order.instrument_id().venue == venue,
                "OrderList::from_orders requires all orders to share the same venue; \
                 expected {venue}, found {} on {}",
                order.instrument_id().venue,
                order.client_order_id(),
            );
        }

        let client_order_ids = orders.iter().map(|o| o.client_order_id()).collect();

        Self {
            id: order_list_id,
            instrument_id,
            strategy_id,
            client_order_ids,
            ts_init,
        }
    }

    /// Validates this [`OrderList`]'s own invariants.
    ///
    /// # Errors
    ///
    /// Returns an error if `client_order_ids` is empty or contains duplicates.
    pub fn validate(&self) -> anyhow::Result<()> {
        if self.client_order_ids.is_empty() {
            anyhow::bail!("OrderList {} has no orders", self.id);
        }

        let unique: HashSet<&ClientOrderId> = self.client_order_ids.iter().collect();
        if unique.len() != self.client_order_ids.len() {
            anyhow::bail!("OrderList {} contains duplicate client_order_ids", self.id);
        }

        Ok(())
    }

    #[must_use]
    pub fn first(&self) -> Option<&ClientOrderId> {
        self.client_order_ids.first()
    }

    /// Returns the number of orders in the list.
    #[must_use]
    pub fn len(&self) -> usize {
        self.client_order_ids.len()
    }

    /// Returns true if the list contains no orders.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.client_order_ids.is_empty()
    }
}

impl PartialEq for OrderList {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Hash for OrderList {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl Display for OrderList {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "OrderList(\
            id={}, \
            instrument_id={}, \
            strategy_id={}, \
            client_order_ids={:?}, \
            ts_init={}\
            )",
            self.id, self.instrument_id, self.strategy_id, self.client_order_ids, self.ts_init,
        )
    }
}

#[cfg(test)]
mod tests {
    use std::collections::hash_map::DefaultHasher;

    use rstest::rstest;

    use super::*;
    use crate::{
        enums::OrderType,
        identifiers::{InstrumentId, OrderListId},
        orders::builder::OrderTestBuilder,
        types::Quantity,
    };

    fn create_client_order_ids(count: usize) -> Vec<ClientOrderId> {
        (0..count)
            .map(|i| ClientOrderId::from(format!("O-00{}", i + 1).as_str()))
            .collect()
    }

    fn create_orders(count: usize, order_list_id: OrderListId) -> Vec<OrderAny> {
        (0..count)
            .map(|i| {
                OrderTestBuilder::new(OrderType::Market)
                    .instrument_id(InstrumentId::from("AUD/USD.SIM"))
                    .client_order_id(ClientOrderId::from(format!("O-00{}", i + 1).as_str()))
                    .order_list_id(order_list_id)
                    .quantity(Quantity::from(1))
                    .build()
            })
            .collect()
    }

    #[rstest]
    fn test_new_and_display() {
        let orders = create_client_order_ids(3);

        let order_list = OrderList::new(
            OrderListId::from("OL-001"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders,
            UnixNanos::default(),
        );

        assert!(order_list.to_string().starts_with(
            "OrderList(id=OL-001, instrument_id=AUD/USD.SIM, strategy_id=S-001, client_order_ids="
        ));
    }

    fn create_orders_for_instrument(
        instrument_ids: &[&str],
        order_list_id: OrderListId,
    ) -> Vec<OrderAny> {
        instrument_ids
            .iter()
            .enumerate()
            .map(|(i, instrument)| {
                OrderTestBuilder::new(OrderType::Market)
                    .instrument_id(InstrumentId::from(*instrument))
                    .client_order_id(ClientOrderId::from(format!("O-00{}", i + 1).as_str()))
                    .order_list_id(order_list_id)
                    .quantity(Quantity::from(1))
                    .build()
            })
            .collect()
    }

    #[rstest]
    fn test_from_orders_accepts_mixed_instruments_same_venue() {
        let order_list_id = OrderListId::from("OL-MIXED-001");
        let orders = create_orders_for_instrument(&["AUD/USD.SIM", "EUR/USD.SIM"], order_list_id);

        let order_list = OrderList::from_orders(&orders, UnixNanos::default());

        assert_eq!(order_list.len(), 2);
        assert_eq!(order_list.instrument_id, InstrumentId::from("AUD/USD.SIM"));
    }

    #[rstest]
    #[should_panic(expected = "share the same venue")]
    fn test_from_orders_panics_on_mixed_venues() {
        let order_list_id = OrderListId::from("OL-MIXED-002");
        let orders =
            create_orders_for_instrument(&["AUD/USD.SIM", "EUR/USD.IDEALPRO"], order_list_id);

        let _ = OrderList::from_orders(&orders, UnixNanos::default());
    }

    #[rstest]
    fn test_from_orders() {
        let order_list_id = OrderListId::from("OL-002");
        let orders = create_orders(3, order_list_id);

        let order_list = OrderList::from_orders(&orders, UnixNanos::default());

        assert_eq!(order_list.id, order_list_id);
        assert_eq!(order_list.len(), 3);
        assert_eq!(order_list.instrument_id, InstrumentId::from("AUD/USD.SIM"));
        assert_eq!(order_list.client_order_ids[0], ClientOrderId::from("O-001"));
    }

    #[rstest]
    fn test_order_list_equality() {
        let orders = create_client_order_ids(1);

        let order_list1 = OrderList::new(
            OrderListId::from("OL-006"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders.clone(),
            UnixNanos::default(),
        );

        let order_list2 = OrderList::new(
            OrderListId::from("OL-006"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders,
            UnixNanos::default(),
        );

        assert_eq!(order_list1, order_list2);
    }

    #[rstest]
    fn test_order_list_inequality() {
        let orders = create_client_order_ids(1);

        let order_list1 = OrderList::new(
            OrderListId::from("OL-007"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders.clone(),
            UnixNanos::default(),
        );

        let order_list2 = OrderList::new(
            OrderListId::from("OL-008"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders,
            UnixNanos::default(),
        );

        assert_ne!(order_list1, order_list2);
    }

    #[rstest]
    fn test_order_list_first() {
        let orders = create_client_order_ids(2);
        let first_id = orders[0];

        let order_list = OrderList::new(
            OrderListId::from("OL-009"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders,
            UnixNanos::default(),
        );

        let first = order_list.first();
        assert!(first.is_some());
        assert_eq!(*first.unwrap(), first_id);
    }

    #[rstest]
    fn test_order_list_len() {
        let orders = create_client_order_ids(3);

        let order_list = OrderList::new(
            OrderListId::from("OL-010"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders,
            UnixNanos::default(),
        );

        assert_eq!(order_list.len(), 3);
        assert!(!order_list.is_empty());
    }

    #[rstest]
    fn test_order_list_hash() {
        let orders = create_client_order_ids(1);

        let order_list1 = OrderList::new(
            OrderListId::from("OL-011"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders.clone(),
            UnixNanos::default(),
        );

        let order_list2 = OrderList::new(
            OrderListId::from("OL-011"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders,
            UnixNanos::default(),
        );

        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        order_list1.hash(&mut hasher1);
        order_list2.hash(&mut hasher2);

        assert_eq!(hasher1.finish(), hasher2.finish());
    }

    #[rstest]
    fn test_validate_accepts_well_formed_list() {
        let orders = create_client_order_ids(3);
        let order_list = OrderList::new(
            OrderListId::from("OL-VALID-001"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            orders,
            UnixNanos::default(),
        );
        order_list
            .validate()
            .expect("well-formed list should validate");
    }

    #[rstest]
    fn test_validate_rejects_empty_list() {
        let order_list = OrderList::new(
            OrderListId::from("OL-EMPTY-001"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            Vec::new(),
            UnixNanos::default(),
        );
        let err = order_list.validate().expect_err("empty list should fail");
        assert!(
            err.to_string().contains("OL-EMPTY-001") && err.to_string().contains("no orders"),
            "unexpected error: {err}",
        );
    }

    #[rstest]
    fn test_validate_rejects_duplicate_client_order_ids() {
        let id = ClientOrderId::from("O-001");
        let order_list = OrderList::new(
            OrderListId::from("OL-DUP-001"),
            InstrumentId::from("AUD/USD.SIM"),
            StrategyId::from("S-001"),
            vec![id, id],
            UnixNanos::default(),
        );
        let err = order_list
            .validate()
            .expect_err("duplicate client_order_ids should fail");
        assert!(
            err.to_string().contains("duplicate client_order_ids"),
            "unexpected error: {err}",
        );
    }
}