1use 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
35pub(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
42fn 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#[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
75pub fn reset_test_uuid_rng() {
80 TEST_UUID_STATE.with(|cell| cell.set(TEST_UUID_SEED));
81}
82
83pub trait TestDefault {
89 fn test_default() -> Self;
91}
92
93#[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 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, );
207 book.add(order, 0, 1, 2.into());
208 }
209
210 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, );
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 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}