Skip to main content

nautilus_model/
stubs.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Type stubs to facilitate testing.
17
18use std::cell::Cell;
19
20use nautilus_core::UUID4;
21use rstest::fixture;
22use rust_decimal::prelude::ToPrimitive;
23
24use crate::{
25    data::order::BookOrder,
26    enums::{BookType, LiquiditySide, OrderSide, OrderType},
27    identifiers::InstrumentId,
28    instruments::{CurrencyPair, Instrument, InstrumentAny, stubs::audusd_sim},
29    orderbook::OrderBook,
30    orders::{builder::OrderTestBuilder, stubs::OrderFilledTestBuilder},
31    position::Position,
32    types::{Money, Price, Quantity},
33};
34
35/// Seed used by [`test_uuid`] for deterministic UUIDs in test fixtures.
36pub(crate) const TEST_UUID_SEED: u64 = 42;
37
38thread_local! {
39    static TEST_UUID_STATE: Cell<u64> = const { Cell::new(TEST_UUID_SEED) };
40}
41
42// SplitMix64 PRNG (Steele, Lea, Flood 2014): owning the algorithm here keeps the test UUID
43// sequence stable regardless of upstream PRNG crate versions, with zero added dependencies.
44fn splitmix64(state: &mut u64) -> u64 {
45    *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
46    let mut z = *state;
47    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
48    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
49    z ^ (z >> 31)
50}
51
52/// Returns the next [`UUID4`] in a per-thread deterministic sequence seeded with a fixed value.
53///
54/// The official test runner is `cargo nextest`, which spawns one process per test, so the
55/// sequence resets at every test boundary without explicit teardown. Multiple events constructed
56/// within a single test get distinct UUIDs, and re-running the same test produces the same
57/// sequence.
58///
59/// Intended for use as a default in test specs and fixtures only.
60#[must_use]
61pub fn test_uuid() -> UUID4 {
62    TEST_UUID_STATE.with(|cell| {
63        let mut state = cell.get();
64        let hi = splitmix64(&mut state).to_be_bytes();
65        let lo = splitmix64(&mut state).to_be_bytes();
66        cell.set(state);
67
68        let mut bytes = [0u8; 16];
69        bytes[..8].copy_from_slice(&hi);
70        bytes[8..].copy_from_slice(&lo);
71        UUID4::from_bytes(bytes)
72    })
73}
74
75/// Resets the per-thread test UUID state to its seed.
76///
77/// Only needed under runners that share a process across tests (e.g. plain `cargo test`); under
78/// nextest each test starts with fresh thread-local state already.
79pub fn reset_test_uuid_rng() {
80    TEST_UUID_STATE.with(|cell| cell.set(TEST_UUID_SEED));
81}
82
83/// A trait for providing test-only default values.
84///
85/// This trait is intentionally separate from [`Default`] to make it clear
86/// that these default values are only meaningful in testing contexts and should
87/// not be used in production code.
88pub trait TestDefault {
89    /// Creates a new instance with test-appropriate default values.
90    fn test_default() -> Self;
91}
92
93/// Calculate commission for testing.
94///
95/// # Panics
96///
97/// This function panics if:
98/// - The liquidity side is `NoLiquiditySide`.
99/// - `instrument.maker_fee()` or `instrument.taker_fee()` cannot be converted to `f64`.
100#[must_use]
101pub fn calculate_commission(
102    instrument: &InstrumentAny,
103    last_qty: Quantity,
104    last_px: Price,
105    use_quote_for_inverse: Option<bool>,
106) -> Money {
107    let liquidity_side = LiquiditySide::Taker;
108    assert_ne!(
109        liquidity_side,
110        LiquiditySide::NoLiquiditySide,
111        "Invalid liquidity side"
112    );
113    let notional = instrument
114        .calculate_notional_value(last_qty, last_px, use_quote_for_inverse)
115        .as_f64();
116    let commission = if liquidity_side == LiquiditySide::Maker {
117        notional * instrument.maker_fee().to_f64().unwrap()
118    } else if liquidity_side == LiquiditySide::Taker {
119        notional * instrument.taker_fee().to_f64().unwrap()
120    } else {
121        panic!("Invalid liquidity side {liquidity_side}")
122    };
123
124    if instrument.is_inverse() && !use_quote_for_inverse.unwrap_or(false) {
125        Money::new(commission, instrument.base_currency().unwrap())
126    } else {
127        Money::new(commission, instrument.quote_currency())
128    }
129}
130
131#[fixture]
132pub fn stub_position_long(audusd_sim: CurrencyPair) -> Position {
133    let audusd_sim = InstrumentAny::CurrencyPair(audusd_sim);
134    let order = OrderTestBuilder::new(OrderType::Market)
135        .instrument_id(audusd_sim.id())
136        .side(OrderSide::Buy)
137        .quantity(Quantity::from(1))
138        .build();
139    let filled = OrderFilledTestBuilder::new(&order, &audusd_sim)
140        .last_px(Price::from("1.0002"))
141        .build();
142    Position::new(&audusd_sim, filled.into())
143}
144
145#[fixture]
146pub fn stub_position_short(audusd_sim: CurrencyPair) -> Position {
147    let audusd_sim = InstrumentAny::CurrencyPair(audusd_sim);
148    let order = OrderTestBuilder::new(OrderType::Market)
149        .instrument_id(audusd_sim.id())
150        .side(OrderSide::Sell)
151        .quantity(Quantity::from(1))
152        .build();
153    let filled = OrderFilledTestBuilder::new(&order, &audusd_sim)
154        .last_px(Price::from("22000.0"))
155        .build();
156    Position::new(&audusd_sim, filled.into())
157}
158
159#[must_use]
160pub fn stub_order_book_mbp_appl_xnas() -> OrderBook {
161    stub_order_book_mbp(
162        InstrumentId::from("AAPL.XNAS"),
163        101.0,
164        100.0,
165        100.0,
166        100.0,
167        2,
168        0.01,
169        0,
170        100.0,
171        10,
172    )
173}
174
175#[expect(clippy::too_many_arguments)]
176#[must_use]
177pub fn stub_order_book_mbp(
178    instrument_id: InstrumentId,
179    top_ask_price: f64,
180    top_bid_price: f64,
181    top_ask_size: f64,
182    top_bid_size: f64,
183    price_precision: u8,
184    price_increment: f64,
185    size_precision: u8,
186    size_increment: f64,
187    num_levels: usize,
188) -> OrderBook {
189    let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
190
191    // Generate bids
192    for i in 0..num_levels {
193        let price = Price::new(
194            price_increment.mul_add(-(i as f64), top_bid_price),
195            price_precision,
196        );
197        let size = Quantity::new(
198            size_increment.mul_add(i as f64, top_bid_size),
199            size_precision,
200        );
201        let order = BookOrder::new(
202            OrderSide::Buy,
203            price,
204            size,
205            0, // order_id not applicable for MBP (market by price) books
206        );
207        book.add(order, 0, 1, 2.into());
208    }
209
210    // Generate asks
211    for i in 0..num_levels {
212        let price = Price::new(
213            price_increment.mul_add(i as f64, top_ask_price),
214            price_precision,
215        );
216        let size = Quantity::new(
217            size_increment.mul_add(i as f64, top_ask_size),
218            size_precision,
219        );
220        let order = BookOrder::new(
221            OrderSide::Sell,
222            price,
223            size,
224            0, // order_id not applicable for MBP (market by price) books
225        );
226        book.add(order, 0, 1, 2.into());
227    }
228
229    book
230}
231
232#[cfg(test)]
233mod tests {
234    use rstest::rstest;
235
236    use super::*;
237
238    #[rstest]
239    fn test_uuid_is_valid_v4_rfc4122() {
240        reset_test_uuid_rng();
241        let s = test_uuid().to_string();
242        // Format invariants per RFC 4122: position 14 is the version digit, position 19 the variant.
243        assert_eq!(s.len(), 36);
244        assert_eq!(&s[14..15], "4", "version digit must be 4, was {s}");
245        let variant = s.chars().nth(19).unwrap();
246        assert!(
247            matches!(variant, '8' | '9' | 'a' | 'b'),
248            "variant nibble must be one of 8/9/a/b, was {variant} in {s}",
249        );
250    }
251}