1use std::{
17 cell::RefCell,
18 fmt::{Debug, Display},
19 rc::Rc,
20};
21
22#[cfg(all(feature = "simulation", madsim))]
23use madsim::rand::RngCore;
24use nautilus_core::{
25 UnixNanos,
26 correctness::{check_in_range_inclusive_f64, check_non_negative_f64},
27};
28use nautilus_model::{
29 data::order::BookOrder,
30 enums::{BookType, OrderSide},
31 identifiers::InstrumentId,
32 instruments::{Instrument, InstrumentAny},
33 orderbook::OrderBook,
34 orders::{Order, OrderAny},
35 types::{Price, Quantity},
36};
37use rand::{RngExt, SeedableRng, rngs::StdRng};
38use rust_decimal::Decimal;
39use rust_decimal_macros::dec;
40
41#[cfg(feature = "python")]
42use crate::python::fill::PythonFillModel;
43
44const UNLIMITED_LIQUIDITY_UNITS: u64 = 10_000_000_000;
46
47fn unlimited_liquidity(precision: u8) -> Quantity {
48 Quantity::from_mantissa_exponent(UNLIMITED_LIQUIDITY_UNITS, 0, precision)
49}
50
51pub trait FillModel {
52 fn is_limit_filled(&mut self) -> anyhow::Result<bool>;
58
59 fn is_slipped(&mut self) -> anyhow::Result<bool>;
65
66 fn fill_limit_inside_spread(&self) -> anyhow::Result<bool> {
76 Ok(false)
77 }
78
79 fn get_orderbook_for_fill_simulation(
93 &mut self,
94 instrument: &InstrumentAny,
95 order: &OrderAny,
96 best_bid: Option<Price>,
97 best_ask: Option<Price>,
98 ) -> anyhow::Result<Option<OrderBook>>;
99}
100
101#[derive(Clone)]
103pub struct FillModelHandle(Rc<RefCell<dyn FillModel>>);
104
105impl FillModelHandle {
106 #[must_use]
108 pub fn new<T>(model: T) -> Self
109 where
110 T: FillModel + 'static,
111 {
112 Self(Rc::new(RefCell::new(model)))
113 }
114
115 #[must_use]
117 pub fn from_rc(model: Rc<RefCell<dyn FillModel>>) -> Self {
118 Self(model)
119 }
120}
121
122impl Debug for FillModelHandle {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124 f.debug_tuple(stringify!(FillModelHandle))
125 .field(&"<dyn FillModel>")
126 .finish()
127 }
128}
129
130impl FillModel for FillModelHandle {
131 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
132 self.0.borrow_mut().is_limit_filled()
133 }
134
135 fn is_slipped(&mut self) -> anyhow::Result<bool> {
136 self.0.borrow_mut().is_slipped()
137 }
138
139 fn fill_limit_inside_spread(&self) -> anyhow::Result<bool> {
140 self.0.borrow().fill_limit_inside_spread()
141 }
142
143 fn get_orderbook_for_fill_simulation(
144 &mut self,
145 instrument: &InstrumentAny,
146 order: &OrderAny,
147 best_bid: Option<Price>,
148 best_ask: Option<Price>,
149 ) -> anyhow::Result<Option<OrderBook>> {
150 self.0
151 .borrow_mut()
152 .get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask)
153 }
154}
155
156impl Default for FillModelHandle {
157 fn default() -> Self {
158 FillModelAny::default().into()
159 }
160}
161
162impl From<FillModelAny> for FillModelHandle {
163 fn from(model: FillModelAny) -> Self {
164 Self::new(model)
165 }
166}
167
168#[derive(Debug)]
169pub struct ProbabilisticFillState {
170 prob_fill_on_limit: f64,
171 prob_slippage: f64,
172 random_seed: Option<u64>,
173 rng: StdRng,
174}
175
176impl ProbabilisticFillState {
177 pub fn new(
183 prob_fill_on_limit: f64,
184 prob_slippage: f64,
185 random_seed: Option<u64>,
186 ) -> anyhow::Result<Self> {
187 check_in_range_inclusive_f64(prob_fill_on_limit, 0.0, 1.0, "prob_fill_on_limit")?;
188 check_in_range_inclusive_f64(prob_slippage, 0.0, 1.0, "prob_slippage")?;
189 let rng = match random_seed {
190 Some(seed) => StdRng::seed_from_u64(seed),
191 None => default_std_rng(),
192 };
193 Ok(Self {
194 prob_fill_on_limit,
195 prob_slippage,
196 random_seed,
197 rng,
198 })
199 }
200
201 pub fn is_limit_filled(&mut self) -> bool {
202 self.event_success(self.prob_fill_on_limit)
203 }
204
205 pub fn is_slipped(&mut self) -> bool {
206 self.event_success(self.prob_slippage)
207 }
208
209 pub fn random_bool(&mut self, probability: f64) -> bool {
210 self.event_success(probability)
211 }
212
213 fn event_success(&mut self, probability: f64) -> bool {
215 if probability <= 0.0 {
216 false
217 } else if probability >= 1.0 {
218 true
219 } else {
220 self.rng.random_bool(probability)
221 }
222 }
223}
224
225impl Clone for ProbabilisticFillState {
226 fn clone(&self) -> Self {
227 Self::new(
228 self.prob_fill_on_limit,
229 self.prob_slippage,
230 self.random_seed,
231 )
232 .expect("ProbabilisticFillState clone should not fail with valid parameters")
233 }
234}
235
236fn default_std_rng() -> StdRng {
237 #[cfg(all(feature = "simulation", madsim))]
238 {
239 if madsim::runtime::Handle::try_current().is_ok() {
244 let mut seed = [0u8; 32];
245 madsim::rand::thread_rng().fill_bytes(&mut seed);
246 return StdRng::from_seed(seed);
247 }
248 }
249
250 StdRng::from_rng(&mut rand::rng()) }
252
253fn build_l2_book(instrument_id: InstrumentId) -> OrderBook {
254 OrderBook::new(instrument_id, BookType::L2_MBP)
255}
256
257fn add_order(
259 book: &mut OrderBook,
260 instrument: &InstrumentAny,
261 side: OrderSide,
262 price: Price,
263 size: Quantity,
264 order_id: u64,
265) {
266 if !is_price_tradable(instrument, price) {
267 return;
268 }
269
270 let order = BookOrder::new(side, price, size, order_id);
271 book.add(order, 0, 0, UnixNanos::default());
272}
273
274pub(crate) fn is_price_tradable(instrument: &InstrumentAny, price: Price) -> bool {
275 (instrument.allows_negative_price() || price.is_positive())
276 && instrument.min_price().is_none_or(|min| price >= min)
277 && instrument.max_price().is_none_or(|max| price <= max)
278}
279
280#[derive(Debug, Clone)]
282#[cfg_attr(
283 feature = "python",
284 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
285)]
286#[cfg_attr(
287 feature = "python",
288 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
289)]
290pub struct DefaultFillModel {
291 state: ProbabilisticFillState,
292}
293
294impl DefaultFillModel {
295 pub fn new(
301 prob_fill_on_limit: f64,
302 prob_slippage: f64,
303 random_seed: Option<u64>,
304 ) -> anyhow::Result<Self> {
305 Ok(Self {
306 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
307 })
308 }
309}
310
311impl Default for DefaultFillModel {
312 fn default() -> Self {
313 Self::new(1.0, 0.0, None).unwrap()
314 }
315}
316
317impl Display for DefaultFillModel {
318 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
319 write!(
320 f,
321 "DefaultFillModel(prob_fill_on_limit={}, prob_slippage={})",
322 self.state.prob_fill_on_limit, self.state.prob_slippage
323 )
324 }
325}
326
327impl FillModel for DefaultFillModel {
328 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
329 Ok(self.state.is_limit_filled())
330 }
331
332 fn is_slipped(&mut self) -> anyhow::Result<bool> {
333 Ok(self.state.is_slipped())
334 }
335
336 fn get_orderbook_for_fill_simulation(
337 &mut self,
338 _instrument: &InstrumentAny,
339 _order: &OrderAny,
340 _best_bid: Option<Price>,
341 _best_ask: Option<Price>,
342 ) -> anyhow::Result<Option<OrderBook>> {
343 Ok(None)
344 }
345}
346
347#[derive(Debug, Clone)]
349#[cfg_attr(
350 feature = "python",
351 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
352)]
353#[cfg_attr(
354 feature = "python",
355 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
356)]
357pub struct BestPriceFillModel {
358 state: ProbabilisticFillState,
359}
360
361impl BestPriceFillModel {
362 pub fn new(
368 prob_fill_on_limit: f64,
369 prob_slippage: f64,
370 random_seed: Option<u64>,
371 ) -> anyhow::Result<Self> {
372 Ok(Self {
373 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
374 })
375 }
376}
377
378impl Default for BestPriceFillModel {
379 fn default() -> Self {
380 Self::new(1.0, 0.0, None).unwrap()
381 }
382}
383
384impl FillModel for BestPriceFillModel {
385 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
386 Ok(self.state.is_limit_filled())
387 }
388
389 fn is_slipped(&mut self) -> anyhow::Result<bool> {
390 Ok(self.state.is_slipped())
391 }
392
393 fn fill_limit_inside_spread(&self) -> anyhow::Result<bool> {
394 Ok(true)
395 }
396
397 fn get_orderbook_for_fill_simulation(
398 &mut self,
399 instrument: &InstrumentAny,
400 order: &OrderAny,
401 best_bid: Option<Price>,
402 best_ask: Option<Price>,
403 ) -> anyhow::Result<Option<OrderBook>> {
404 let (Some(mut best_bid), Some(mut best_ask)) = (best_bid, best_ask) else {
405 return Ok(None);
406 };
407
408 if let Some(price) = order.price() {
411 match order.order_side() {
412 OrderSide::Buy if price < best_ask => {
413 if price < best_bid {
414 return Ok(None);
415 }
416
417 best_ask = price;
418 }
419 OrderSide::Sell if price > best_bid => {
420 if price > best_ask {
421 return Ok(None);
422 }
423
424 best_bid = price;
425 }
426 _ => {}
427 }
428 }
429
430 let mut book = build_l2_book(instrument.id());
431 let size_prec = instrument.size_precision();
432 add_order(
433 &mut book,
434 instrument,
435 OrderSide::Buy,
436 best_bid,
437 unlimited_liquidity(size_prec),
438 1,
439 );
440 add_order(
441 &mut book,
442 instrument,
443 OrderSide::Sell,
444 best_ask,
445 unlimited_liquidity(size_prec),
446 2,
447 );
448 Ok(Some(book))
449 }
450}
451
452#[derive(Debug, Clone)]
454#[cfg_attr(
455 feature = "python",
456 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
457)]
458#[cfg_attr(
459 feature = "python",
460 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
461)]
462pub struct OneTickSlippageFillModel {
463 state: ProbabilisticFillState,
464}
465
466impl OneTickSlippageFillModel {
467 pub fn new(
473 prob_fill_on_limit: f64,
474 prob_slippage: f64,
475 random_seed: Option<u64>,
476 ) -> anyhow::Result<Self> {
477 Ok(Self {
478 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
479 })
480 }
481}
482
483impl Default for OneTickSlippageFillModel {
484 fn default() -> Self {
485 Self::new(1.0, 0.0, None).unwrap()
486 }
487}
488
489impl FillModel for OneTickSlippageFillModel {
490 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
491 Ok(self.state.is_limit_filled())
492 }
493
494 fn is_slipped(&mut self) -> anyhow::Result<bool> {
495 Ok(self.state.is_slipped())
496 }
497
498 fn get_orderbook_for_fill_simulation(
499 &mut self,
500 instrument: &InstrumentAny,
501 _order: &OrderAny,
502 best_bid: Option<Price>,
503 best_ask: Option<Price>,
504 ) -> anyhow::Result<Option<OrderBook>> {
505 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
506 return Ok(None);
507 };
508
509 let tick = instrument.price_increment();
510 let size_prec = instrument.size_precision();
511 let mut book = build_l2_book(instrument.id());
512
513 add_order(
514 &mut book,
515 instrument,
516 OrderSide::Buy,
517 best_bid - tick,
518 unlimited_liquidity(size_prec),
519 1,
520 );
521 add_order(
522 &mut book,
523 instrument,
524 OrderSide::Sell,
525 best_ask + tick,
526 unlimited_liquidity(size_prec),
527 2,
528 );
529 Ok(Some(book))
530 }
531}
532
533#[derive(Debug, Clone)]
535#[cfg_attr(
536 feature = "python",
537 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
538)]
539#[cfg_attr(
540 feature = "python",
541 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
542)]
543pub struct ProbabilisticFillModel {
544 state: ProbabilisticFillState,
545}
546
547impl ProbabilisticFillModel {
548 pub fn new(
554 prob_fill_on_limit: f64,
555 prob_slippage: f64,
556 random_seed: Option<u64>,
557 ) -> anyhow::Result<Self> {
558 Ok(Self {
559 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
560 })
561 }
562}
563
564impl Default for ProbabilisticFillModel {
565 fn default() -> Self {
566 Self::new(1.0, 0.0, None).unwrap()
567 }
568}
569
570impl FillModel for ProbabilisticFillModel {
571 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
572 Ok(self.state.is_limit_filled())
573 }
574
575 fn is_slipped(&mut self) -> anyhow::Result<bool> {
576 Ok(self.state.is_slipped())
577 }
578
579 fn get_orderbook_for_fill_simulation(
580 &mut self,
581 instrument: &InstrumentAny,
582 _order: &OrderAny,
583 best_bid: Option<Price>,
584 best_ask: Option<Price>,
585 ) -> anyhow::Result<Option<OrderBook>> {
586 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
587 return Ok(None);
588 };
589
590 let tick = instrument.price_increment();
591 let size_prec = instrument.size_precision();
592 let mut book = build_l2_book(instrument.id());
593
594 let (best_bid, best_ask) = if self.state.random_bool(0.5) {
595 (best_bid, best_ask)
596 } else {
597 (best_bid - tick, best_ask + tick)
598 };
599
600 add_order(
601 &mut book,
602 instrument,
603 OrderSide::Buy,
604 best_bid,
605 unlimited_liquidity(size_prec),
606 1,
607 );
608 add_order(
609 &mut book,
610 instrument,
611 OrderSide::Sell,
612 best_ask,
613 unlimited_liquidity(size_prec),
614 2,
615 );
616 Ok(Some(book))
617 }
618}
619
620#[derive(Debug, Clone)]
622#[cfg_attr(
623 feature = "python",
624 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
625)]
626#[cfg_attr(
627 feature = "python",
628 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
629)]
630pub struct TwoTierFillModel {
631 state: ProbabilisticFillState,
632}
633
634impl TwoTierFillModel {
635 pub fn new(
641 prob_fill_on_limit: f64,
642 prob_slippage: f64,
643 random_seed: Option<u64>,
644 ) -> anyhow::Result<Self> {
645 Ok(Self {
646 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
647 })
648 }
649}
650
651impl Default for TwoTierFillModel {
652 fn default() -> Self {
653 Self::new(1.0, 0.0, None).unwrap()
654 }
655}
656
657impl FillModel for TwoTierFillModel {
658 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
659 Ok(self.state.is_limit_filled())
660 }
661
662 fn is_slipped(&mut self) -> anyhow::Result<bool> {
663 Ok(self.state.is_slipped())
664 }
665
666 fn get_orderbook_for_fill_simulation(
667 &mut self,
668 instrument: &InstrumentAny,
669 _order: &OrderAny,
670 best_bid: Option<Price>,
671 best_ask: Option<Price>,
672 ) -> anyhow::Result<Option<OrderBook>> {
673 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
674 return Ok(None);
675 };
676
677 let tick = instrument.price_increment();
678 let size_prec = instrument.size_precision();
679 let mut book = build_l2_book(instrument.id());
680
681 add_order(
682 &mut book,
683 instrument,
684 OrderSide::Buy,
685 best_bid,
686 Quantity::new(10.0, size_prec),
687 1,
688 );
689 add_order(
690 &mut book,
691 instrument,
692 OrderSide::Sell,
693 best_ask,
694 Quantity::new(10.0, size_prec),
695 2,
696 );
697 add_order(
698 &mut book,
699 instrument,
700 OrderSide::Buy,
701 best_bid - tick,
702 unlimited_liquidity(size_prec),
703 3,
704 );
705 add_order(
706 &mut book,
707 instrument,
708 OrderSide::Sell,
709 best_ask + tick,
710 unlimited_liquidity(size_prec),
711 4,
712 );
713 Ok(Some(book))
714 }
715}
716
717#[derive(Debug, Clone)]
719#[cfg_attr(
720 feature = "python",
721 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
722)]
723#[cfg_attr(
724 feature = "python",
725 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
726)]
727pub struct ThreeTierFillModel {
728 state: ProbabilisticFillState,
729}
730
731impl ThreeTierFillModel {
732 pub fn new(
738 prob_fill_on_limit: f64,
739 prob_slippage: f64,
740 random_seed: Option<u64>,
741 ) -> anyhow::Result<Self> {
742 Ok(Self {
743 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
744 })
745 }
746}
747
748impl Default for ThreeTierFillModel {
749 fn default() -> Self {
750 Self::new(1.0, 0.0, None).unwrap()
751 }
752}
753
754impl FillModel for ThreeTierFillModel {
755 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
756 Ok(self.state.is_limit_filled())
757 }
758
759 fn is_slipped(&mut self) -> anyhow::Result<bool> {
760 Ok(self.state.is_slipped())
761 }
762
763 fn get_orderbook_for_fill_simulation(
764 &mut self,
765 instrument: &InstrumentAny,
766 _order: &OrderAny,
767 best_bid: Option<Price>,
768 best_ask: Option<Price>,
769 ) -> anyhow::Result<Option<OrderBook>> {
770 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
771 return Ok(None);
772 };
773
774 let tick = instrument.price_increment();
775 let two_ticks = tick + tick;
776 let size_prec = instrument.size_precision();
777 let mut book = build_l2_book(instrument.id());
778
779 add_order(
780 &mut book,
781 instrument,
782 OrderSide::Buy,
783 best_bid,
784 Quantity::new(50.0, size_prec),
785 1,
786 );
787 add_order(
788 &mut book,
789 instrument,
790 OrderSide::Sell,
791 best_ask,
792 Quantity::new(50.0, size_prec),
793 2,
794 );
795 add_order(
796 &mut book,
797 instrument,
798 OrderSide::Buy,
799 best_bid - tick,
800 Quantity::new(30.0, size_prec),
801 3,
802 );
803 add_order(
804 &mut book,
805 instrument,
806 OrderSide::Sell,
807 best_ask + tick,
808 Quantity::new(30.0, size_prec),
809 4,
810 );
811 add_order(
812 &mut book,
813 instrument,
814 OrderSide::Buy,
815 best_bid - two_ticks,
816 Quantity::new(20.0, size_prec),
817 5,
818 );
819 add_order(
820 &mut book,
821 instrument,
822 OrderSide::Sell,
823 best_ask + two_ticks,
824 Quantity::new(20.0, size_prec),
825 6,
826 );
827 Ok(Some(book))
828 }
829}
830
831#[derive(Debug, Clone)]
833#[cfg_attr(
834 feature = "python",
835 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
836)]
837#[cfg_attr(
838 feature = "python",
839 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
840)]
841pub struct LimitOrderPartialFillModel {
842 state: ProbabilisticFillState,
843}
844
845impl LimitOrderPartialFillModel {
846 pub fn new(
852 prob_fill_on_limit: f64,
853 prob_slippage: f64,
854 random_seed: Option<u64>,
855 ) -> anyhow::Result<Self> {
856 Ok(Self {
857 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
858 })
859 }
860}
861
862impl Default for LimitOrderPartialFillModel {
863 fn default() -> Self {
864 Self::new(1.0, 0.0, None).unwrap()
865 }
866}
867
868impl FillModel for LimitOrderPartialFillModel {
869 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
870 Ok(self.state.is_limit_filled())
871 }
872
873 fn is_slipped(&mut self) -> anyhow::Result<bool> {
874 Ok(self.state.is_slipped())
875 }
876
877 fn get_orderbook_for_fill_simulation(
878 &mut self,
879 instrument: &InstrumentAny,
880 _order: &OrderAny,
881 best_bid: Option<Price>,
882 best_ask: Option<Price>,
883 ) -> anyhow::Result<Option<OrderBook>> {
884 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
885 return Ok(None);
886 };
887
888 let tick = instrument.price_increment();
889 let size_prec = instrument.size_precision();
890 let mut book = build_l2_book(instrument.id());
891
892 add_order(
893 &mut book,
894 instrument,
895 OrderSide::Buy,
896 best_bid,
897 Quantity::new(5.0, size_prec),
898 1,
899 );
900 add_order(
901 &mut book,
902 instrument,
903 OrderSide::Sell,
904 best_ask,
905 Quantity::new(5.0, size_prec),
906 2,
907 );
908 add_order(
909 &mut book,
910 instrument,
911 OrderSide::Buy,
912 best_bid - tick,
913 unlimited_liquidity(size_prec),
914 3,
915 );
916 add_order(
917 &mut book,
918 instrument,
919 OrderSide::Sell,
920 best_ask + tick,
921 unlimited_liquidity(size_prec),
922 4,
923 );
924 Ok(Some(book))
925 }
926}
927
928#[derive(Debug, Clone)]
931#[cfg_attr(
932 feature = "python",
933 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
934)]
935#[cfg_attr(
936 feature = "python",
937 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
938)]
939pub struct SizeAwareFillModel {
940 state: ProbabilisticFillState,
941}
942
943impl SizeAwareFillModel {
944 pub fn new(
950 prob_fill_on_limit: f64,
951 prob_slippage: f64,
952 random_seed: Option<u64>,
953 ) -> anyhow::Result<Self> {
954 Ok(Self {
955 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
956 })
957 }
958}
959
960impl Default for SizeAwareFillModel {
961 fn default() -> Self {
962 Self::new(1.0, 0.0, None).unwrap()
963 }
964}
965
966impl FillModel for SizeAwareFillModel {
967 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
968 Ok(self.state.is_limit_filled())
969 }
970
971 fn is_slipped(&mut self) -> anyhow::Result<bool> {
972 Ok(self.state.is_slipped())
973 }
974
975 fn get_orderbook_for_fill_simulation(
976 &mut self,
977 instrument: &InstrumentAny,
978 order: &OrderAny,
979 best_bid: Option<Price>,
980 best_ask: Option<Price>,
981 ) -> anyhow::Result<Option<OrderBook>> {
982 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
983 return Ok(None);
984 };
985
986 let tick = instrument.price_increment();
987 let size_prec = instrument.size_precision();
988 let mut book = build_l2_book(instrument.id());
989
990 let threshold = Quantity::new(10.0, size_prec);
991 if order.quantity() <= threshold {
992 add_order(
994 &mut book,
995 instrument,
996 OrderSide::Buy,
997 best_bid,
998 Quantity::new(50.0, size_prec),
999 1,
1000 );
1001 add_order(
1002 &mut book,
1003 instrument,
1004 OrderSide::Sell,
1005 best_ask,
1006 Quantity::new(50.0, size_prec),
1007 2,
1008 );
1009 } else {
1010 let remaining = order.quantity() - threshold;
1012 add_order(
1013 &mut book,
1014 instrument,
1015 OrderSide::Buy,
1016 best_bid,
1017 threshold,
1018 1,
1019 );
1020 add_order(
1021 &mut book,
1022 instrument,
1023 OrderSide::Sell,
1024 best_ask,
1025 threshold,
1026 2,
1027 );
1028 add_order(
1029 &mut book,
1030 instrument,
1031 OrderSide::Buy,
1032 best_bid - tick,
1033 remaining,
1034 3,
1035 );
1036 add_order(
1037 &mut book,
1038 instrument,
1039 OrderSide::Sell,
1040 best_ask + tick,
1041 remaining,
1042 4,
1043 );
1044 }
1045 Ok(Some(book))
1046 }
1047}
1048
1049#[derive(Debug, Clone)]
1051#[cfg_attr(
1052 feature = "python",
1053 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
1054)]
1055#[cfg_attr(
1056 feature = "python",
1057 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
1058)]
1059pub struct CompetitionAwareFillModel {
1060 state: ProbabilisticFillState,
1061 liquidity_factor: Decimal,
1062}
1063
1064impl CompetitionAwareFillModel {
1065 pub fn new(
1071 prob_fill_on_limit: f64,
1072 prob_slippage: f64,
1073 random_seed: Option<u64>,
1074 liquidity_factor: f64,
1075 ) -> anyhow::Result<Self> {
1076 let state = ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?;
1077 check_in_range_inclusive_f64(liquidity_factor, 0.0, 1.0, "liquidity_factor")?;
1078 let liquidity_factor = Decimal::try_from(liquidity_factor)?;
1079
1080 Ok(Self {
1081 state,
1082 liquidity_factor,
1083 })
1084 }
1085}
1086
1087impl Default for CompetitionAwareFillModel {
1088 fn default() -> Self {
1089 Self::new(1.0, 0.0, None, 0.3).unwrap()
1090 }
1091}
1092
1093impl FillModel for CompetitionAwareFillModel {
1094 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
1095 Ok(self.state.is_limit_filled())
1096 }
1097
1098 fn is_slipped(&mut self) -> anyhow::Result<bool> {
1099 Ok(self.state.is_slipped())
1100 }
1101
1102 fn get_orderbook_for_fill_simulation(
1103 &mut self,
1104 instrument: &InstrumentAny,
1105 _order: &OrderAny,
1106 best_bid: Option<Price>,
1107 best_ask: Option<Price>,
1108 ) -> anyhow::Result<Option<OrderBook>> {
1109 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
1110 return Ok(None);
1111 };
1112
1113 let size_prec = instrument.size_precision();
1114 let mut book = build_l2_book(instrument.id());
1115
1116 let available = Quantity::from_decimal_dp(
1118 (dec!(1000) * self.liquidity_factor).max(Decimal::ONE),
1119 size_prec,
1120 )?;
1121
1122 add_order(
1123 &mut book,
1124 instrument,
1125 OrderSide::Buy,
1126 best_bid,
1127 available,
1128 1,
1129 );
1130 add_order(
1131 &mut book,
1132 instrument,
1133 OrderSide::Sell,
1134 best_ask,
1135 available,
1136 2,
1137 );
1138 Ok(Some(book))
1139 }
1140}
1141
1142#[derive(Debug, Clone)]
1145#[cfg_attr(
1146 feature = "python",
1147 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
1148)]
1149#[cfg_attr(
1150 feature = "python",
1151 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
1152)]
1153pub struct VolumeSensitiveFillModel {
1154 state: ProbabilisticFillState,
1155 recent_volume: f64,
1156}
1157
1158impl VolumeSensitiveFillModel {
1159 pub fn new(
1165 prob_fill_on_limit: f64,
1166 prob_slippage: f64,
1167 random_seed: Option<u64>,
1168 ) -> anyhow::Result<Self> {
1169 Ok(Self {
1170 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
1171 recent_volume: 1000.0,
1172 })
1173 }
1174
1175 pub fn set_recent_volume(&mut self, volume: f64) {
1176 self.recent_volume = volume;
1177 }
1178}
1179
1180impl Default for VolumeSensitiveFillModel {
1181 fn default() -> Self {
1182 Self::new(1.0, 0.0, None).unwrap()
1183 }
1184}
1185
1186impl FillModel for VolumeSensitiveFillModel {
1187 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
1188 Ok(self.state.is_limit_filled())
1189 }
1190
1191 fn is_slipped(&mut self) -> anyhow::Result<bool> {
1192 Ok(self.state.is_slipped())
1193 }
1194
1195 fn get_orderbook_for_fill_simulation(
1196 &mut self,
1197 instrument: &InstrumentAny,
1198 _order: &OrderAny,
1199 best_bid: Option<Price>,
1200 best_ask: Option<Price>,
1201 ) -> anyhow::Result<Option<OrderBook>> {
1202 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
1203 return Ok(None);
1204 };
1205
1206 let tick = instrument.price_increment();
1207 let size_prec = instrument.size_precision();
1208 let mut book = build_l2_book(instrument.id());
1209
1210 check_non_negative_f64(self.recent_volume, "recent_volume")?;
1211 let recent_volume = Decimal::try_from(self.recent_volume)?;
1212
1213 let available =
1215 Quantity::from_decimal_dp((recent_volume * dec!(0.25)).max(Decimal::ONE), size_prec)?;
1216
1217 add_order(
1218 &mut book,
1219 instrument,
1220 OrderSide::Buy,
1221 best_bid,
1222 available,
1223 1,
1224 );
1225 add_order(
1226 &mut book,
1227 instrument,
1228 OrderSide::Sell,
1229 best_ask,
1230 available,
1231 2,
1232 );
1233 add_order(
1234 &mut book,
1235 instrument,
1236 OrderSide::Buy,
1237 best_bid - tick,
1238 unlimited_liquidity(size_prec),
1239 3,
1240 );
1241 add_order(
1242 &mut book,
1243 instrument,
1244 OrderSide::Sell,
1245 best_ask + tick,
1246 unlimited_liquidity(size_prec),
1247 4,
1248 );
1249 Ok(Some(book))
1250 }
1251}
1252
1253#[derive(Debug, Clone)]
1256#[cfg_attr(
1257 feature = "python",
1258 pyo3::pyclass(module = "nautilus_trader.execution", unsendable, from_py_object)
1259)]
1260#[cfg_attr(
1261 feature = "python",
1262 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
1263)]
1264pub struct MarketHoursFillModel {
1265 state: ProbabilisticFillState,
1266 is_low_liquidity: bool,
1267}
1268
1269impl MarketHoursFillModel {
1270 pub fn new(
1276 prob_fill_on_limit: f64,
1277 prob_slippage: f64,
1278 random_seed: Option<u64>,
1279 ) -> anyhow::Result<Self> {
1280 Ok(Self {
1281 state: ProbabilisticFillState::new(prob_fill_on_limit, prob_slippage, random_seed)?,
1282 is_low_liquidity: false,
1283 })
1284 }
1285
1286 pub fn set_low_liquidity_period(&mut self, is_low_liquidity: bool) {
1287 self.is_low_liquidity = is_low_liquidity;
1288 }
1289
1290 pub fn is_low_liquidity_period(&self) -> bool {
1291 self.is_low_liquidity
1292 }
1293}
1294
1295impl Default for MarketHoursFillModel {
1296 fn default() -> Self {
1297 Self::new(1.0, 0.0, None).unwrap()
1298 }
1299}
1300
1301impl FillModel for MarketHoursFillModel {
1302 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
1303 Ok(self.state.is_limit_filled())
1304 }
1305
1306 fn is_slipped(&mut self) -> anyhow::Result<bool> {
1307 Ok(self.state.is_slipped())
1308 }
1309
1310 fn get_orderbook_for_fill_simulation(
1311 &mut self,
1312 instrument: &InstrumentAny,
1313 _order: &OrderAny,
1314 best_bid: Option<Price>,
1315 best_ask: Option<Price>,
1316 ) -> anyhow::Result<Option<OrderBook>> {
1317 let (Some(best_bid), Some(best_ask)) = (best_bid, best_ask) else {
1318 return Ok(None);
1319 };
1320
1321 let tick = instrument.price_increment();
1322 let size_prec = instrument.size_precision();
1323 let mut book = build_l2_book(instrument.id());
1324 let normal_volume = 500.0;
1325
1326 let (best_bid, best_ask) = if self.is_low_liquidity {
1327 (best_bid - tick, best_ask + tick)
1328 } else {
1329 (best_bid, best_ask)
1330 };
1331
1332 add_order(
1333 &mut book,
1334 instrument,
1335 OrderSide::Buy,
1336 best_bid,
1337 Quantity::new(normal_volume, size_prec),
1338 1,
1339 );
1340 add_order(
1341 &mut book,
1342 instrument,
1343 OrderSide::Sell,
1344 best_ask,
1345 Quantity::new(normal_volume, size_prec),
1346 2,
1347 );
1348 Ok(Some(book))
1349 }
1350}
1351
1352#[derive(Clone, Debug)]
1353pub enum FillModelAny {
1354 Default(DefaultFillModel),
1355 BestPrice(BestPriceFillModel),
1356 OneTickSlippage(OneTickSlippageFillModel),
1357 Probabilistic(ProbabilisticFillModel),
1358 TwoTier(TwoTierFillModel),
1359 ThreeTier(ThreeTierFillModel),
1360 LimitOrderPartialFill(LimitOrderPartialFillModel),
1361 SizeAware(SizeAwareFillModel),
1362 CompetitionAware(CompetitionAwareFillModel),
1363 VolumeSensitive(VolumeSensitiveFillModel),
1364 MarketHours(MarketHoursFillModel),
1365 #[cfg(feature = "python")]
1366 Python(PythonFillModel),
1367}
1368
1369impl FillModel for FillModelAny {
1370 fn is_limit_filled(&mut self) -> anyhow::Result<bool> {
1371 match self {
1372 Self::Default(m) => m.is_limit_filled(),
1373 Self::BestPrice(m) => m.is_limit_filled(),
1374 Self::OneTickSlippage(m) => m.is_limit_filled(),
1375 Self::Probabilistic(m) => m.is_limit_filled(),
1376 Self::TwoTier(m) => m.is_limit_filled(),
1377 Self::ThreeTier(m) => m.is_limit_filled(),
1378 Self::LimitOrderPartialFill(m) => m.is_limit_filled(),
1379 Self::SizeAware(m) => m.is_limit_filled(),
1380 Self::CompetitionAware(m) => m.is_limit_filled(),
1381 Self::VolumeSensitive(m) => m.is_limit_filled(),
1382 Self::MarketHours(m) => m.is_limit_filled(),
1383 #[cfg(feature = "python")]
1384 Self::Python(m) => m.is_limit_filled(),
1385 }
1386 }
1387
1388 fn fill_limit_inside_spread(&self) -> anyhow::Result<bool> {
1389 match self {
1390 Self::Default(m) => m.fill_limit_inside_spread(),
1391 Self::BestPrice(m) => m.fill_limit_inside_spread(),
1392 Self::OneTickSlippage(m) => m.fill_limit_inside_spread(),
1393 Self::Probabilistic(m) => m.fill_limit_inside_spread(),
1394 Self::TwoTier(m) => m.fill_limit_inside_spread(),
1395 Self::ThreeTier(m) => m.fill_limit_inside_spread(),
1396 Self::LimitOrderPartialFill(m) => m.fill_limit_inside_spread(),
1397 Self::SizeAware(m) => m.fill_limit_inside_spread(),
1398 Self::CompetitionAware(m) => m.fill_limit_inside_spread(),
1399 Self::VolumeSensitive(m) => m.fill_limit_inside_spread(),
1400 Self::MarketHours(m) => m.fill_limit_inside_spread(),
1401 #[cfg(feature = "python")]
1402 Self::Python(m) => m.fill_limit_inside_spread(),
1403 }
1404 }
1405
1406 fn is_slipped(&mut self) -> anyhow::Result<bool> {
1407 match self {
1408 Self::Default(m) => m.is_slipped(),
1409 Self::BestPrice(m) => m.is_slipped(),
1410 Self::OneTickSlippage(m) => m.is_slipped(),
1411 Self::Probabilistic(m) => m.is_slipped(),
1412 Self::TwoTier(m) => m.is_slipped(),
1413 Self::ThreeTier(m) => m.is_slipped(),
1414 Self::LimitOrderPartialFill(m) => m.is_slipped(),
1415 Self::SizeAware(m) => m.is_slipped(),
1416 Self::CompetitionAware(m) => m.is_slipped(),
1417 Self::VolumeSensitive(m) => m.is_slipped(),
1418 Self::MarketHours(m) => m.is_slipped(),
1419 #[cfg(feature = "python")]
1420 Self::Python(m) => m.is_slipped(),
1421 }
1422 }
1423
1424 #[rustfmt::skip]
1425 fn get_orderbook_for_fill_simulation(
1426 &mut self,
1427 instrument: &InstrumentAny,
1428 order: &OrderAny,
1429 best_bid: Option<Price>,
1430 best_ask: Option<Price>,
1431 ) -> anyhow::Result<Option<OrderBook>> {
1432 match self {
1433 Self::Default(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1434 Self::BestPrice(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1435 Self::OneTickSlippage(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1436 Self::Probabilistic(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1437 Self::TwoTier(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1438 Self::ThreeTier(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1439 Self::LimitOrderPartialFill(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1440 Self::SizeAware(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1441 Self::CompetitionAware(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1442 Self::VolumeSensitive(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1443 Self::MarketHours(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1444 #[cfg(feature = "python")]
1445 Self::Python(m) => m.get_orderbook_for_fill_simulation(instrument, order, best_bid, best_ask),
1446 }
1447 }
1448}
1449
1450impl Default for FillModelAny {
1451 fn default() -> Self {
1452 Self::Default(DefaultFillModel::default())
1453 }
1454}
1455
1456impl Display for FillModelAny {
1457 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1458 match self {
1459 Self::Default(m) => write!(f, "{m}"),
1460 Self::BestPrice(_) => write!(f, "BestPriceFillModel"),
1461 Self::OneTickSlippage(_) => write!(f, "OneTickSlippageFillModel"),
1462 Self::Probabilistic(_) => write!(f, "ProbabilisticFillModel"),
1463 Self::TwoTier(_) => write!(f, "TwoTierFillModel"),
1464 Self::ThreeTier(_) => write!(f, "ThreeTierFillModel"),
1465 Self::LimitOrderPartialFill(_) => write!(f, "LimitOrderPartialFillModel"),
1466 Self::SizeAware(_) => write!(f, "SizeAwareFillModel"),
1467 Self::CompetitionAware(_) => write!(f, "CompetitionAwareFillModel"),
1468 Self::VolumeSensitive(_) => write!(f, "VolumeSensitiveFillModel"),
1469 Self::MarketHours(_) => write!(f, "MarketHoursFillModel"),
1470 #[cfg(feature = "python")]
1471 Self::Python(_) => write!(f, "PythonFillModel"),
1472 }
1473 }
1474}
1475
1476#[cfg(test)]
1477mod tests {
1478 use nautilus_core::correctness::CorrectnessError;
1479 use nautilus_model::{
1480 enums::OrderType,
1481 instruments::stubs::{
1482 audusd_sim, binary_option, crypto_perpetual_ethusdt, futures_contract_es,
1483 futures_spread_es,
1484 },
1485 orders::builder::OrderTestBuilder,
1486 };
1487 use rstest::{fixture, rstest};
1488
1489 use super::*;
1490
1491 #[fixture]
1492 fn fill_model() -> DefaultFillModel {
1493 let seed = 42;
1494 DefaultFillModel::new(0.5, 0.1, Some(seed)).unwrap()
1495 }
1496
1497 #[rstest]
1498 fn test_fill_model_display(fill_model: DefaultFillModel) {
1499 assert_eq!(
1500 format!("{fill_model}"),
1501 "DefaultFillModel(prob_fill_on_limit=0.5, prob_slippage=0.1)"
1502 );
1503 }
1504
1505 #[rstest]
1506 fn test_fill_model_param_prob_fill_on_limit_error() {
1507 let error = DefaultFillModel::new(1.1, 0.1, None).unwrap_err();
1508
1509 assert_eq!(
1510 error.downcast_ref::<CorrectnessError>(),
1511 Some(&CorrectnessError::OutOfRange {
1512 param: "prob_fill_on_limit".to_string(),
1513 min: "0".to_string(),
1514 max: "1".to_string(),
1515 value: "1.1".to_string(),
1516 type_name: "f64",
1517 })
1518 );
1519 assert_eq!(
1520 error.to_string(),
1521 "invalid f64 for 'prob_fill_on_limit' not in range [0, 1], was 1.1"
1522 );
1523 }
1524
1525 #[rstest]
1526 fn test_fill_model_param_prob_slippage_error() {
1527 let error = DefaultFillModel::new(0.5, 1.1, None).unwrap_err();
1528
1529 assert_eq!(
1530 error.downcast_ref::<CorrectnessError>(),
1531 Some(&CorrectnessError::OutOfRange {
1532 param: "prob_slippage".to_string(),
1533 min: "0".to_string(),
1534 max: "1".to_string(),
1535 value: "1.1".to_string(),
1536 type_name: "f64",
1537 })
1538 );
1539 assert_eq!(
1540 error.to_string(),
1541 "invalid f64 for 'prob_slippage' not in range [0, 1], was 1.1"
1542 );
1543 }
1544
1545 #[rstest]
1546 #[case(f64::NAN, "NaN")]
1547 #[case(f64::INFINITY, "inf")]
1548 #[case(f64::NEG_INFINITY, "-inf")]
1549 fn test_competition_aware_fill_model_rejects_non_finite_liquidity_factor(
1550 #[case] value: f64,
1551 #[case] expected_value: &str,
1552 ) {
1553 let error = CompetitionAwareFillModel::new(1.0, 0.0, None, value).unwrap_err();
1554
1555 assert_eq!(
1556 error.downcast_ref::<CorrectnessError>(),
1557 Some(&CorrectnessError::InvalidValue {
1558 param: "liquidity_factor".to_string(),
1559 value: expected_value.to_string(),
1560 type_name: "f64",
1561 })
1562 );
1563 }
1564
1565 #[rstest]
1566 #[case(-0.1, "-0.1")]
1567 #[case(1.1, "1.1")]
1568 fn test_competition_aware_fill_model_rejects_out_of_range_liquidity_factor(
1569 #[case] value: f64,
1570 #[case] expected_value: &str,
1571 ) {
1572 let error = CompetitionAwareFillModel::new(1.0, 0.0, None, value).unwrap_err();
1573
1574 assert_eq!(
1575 error.downcast_ref::<CorrectnessError>(),
1576 Some(&CorrectnessError::OutOfRange {
1577 param: "liquidity_factor".to_string(),
1578 min: "0".to_string(),
1579 max: "1".to_string(),
1580 value: expected_value.to_string(),
1581 type_name: "f64",
1582 })
1583 );
1584 }
1585
1586 #[rstest]
1587 #[case(f64::NAN, "NaN")]
1588 #[case(f64::INFINITY, "inf")]
1589 #[case(f64::NEG_INFINITY, "-inf")]
1590 fn test_volume_sensitive_fill_model_rejects_non_finite_volume(
1591 #[case] volume: f64,
1592 #[case] expected_value: &str,
1593 ) {
1594 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1595 let order = OrderTestBuilder::new(OrderType::Market)
1596 .instrument_id(instrument.id())
1597 .side(OrderSide::Buy)
1598 .quantity(Quantity::from(100_000))
1599 .build();
1600 let mut model = VolumeSensitiveFillModel::default();
1601 model.set_recent_volume(volume);
1602
1603 let error = model
1604 .get_orderbook_for_fill_simulation(
1605 &instrument,
1606 &order,
1607 Some(Price::from("0.80000")),
1608 Some(Price::from("0.80010")),
1609 )
1610 .unwrap_err();
1611
1612 assert_eq!(
1613 error.downcast_ref::<CorrectnessError>(),
1614 Some(&CorrectnessError::InvalidValue {
1615 param: "recent_volume".to_string(),
1616 value: expected_value.to_string(),
1617 type_name: "f64",
1618 })
1619 );
1620 }
1621
1622 #[rstest]
1623 fn test_volume_sensitive_fill_model_rejects_negative_volume() {
1624 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1625 let order = OrderTestBuilder::new(OrderType::Market)
1626 .instrument_id(instrument.id())
1627 .side(OrderSide::Buy)
1628 .quantity(Quantity::from(100_000))
1629 .build();
1630 let mut model = VolumeSensitiveFillModel::default();
1631 model.set_recent_volume(-1.0);
1632
1633 let error = model
1634 .get_orderbook_for_fill_simulation(
1635 &instrument,
1636 &order,
1637 Some(Price::from("0.80000")),
1638 Some(Price::from("0.80010")),
1639 )
1640 .unwrap_err();
1641
1642 assert_eq!(
1643 error.downcast_ref::<CorrectnessError>(),
1644 Some(&CorrectnessError::NegativeValue {
1645 param: "recent_volume".to_string(),
1646 value: "-1".to_string(),
1647 type_name: "f64",
1648 })
1649 );
1650 }
1651
1652 #[rstest]
1653 fn test_volume_sensitive_fill_model_rejects_volume_above_quantity_range() {
1654 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1655 let order = OrderTestBuilder::new(OrderType::Market)
1656 .instrument_id(instrument.id())
1657 .side(OrderSide::Buy)
1658 .quantity(Quantity::from(100_000))
1659 .build();
1660 let mut model = VolumeSensitiveFillModel::default();
1661 model.set_recent_volume(100_000_000_000_000_000.0);
1662
1663 let error = model
1664 .get_orderbook_for_fill_simulation(
1665 &instrument,
1666 &order,
1667 Some(Price::from("0.80000")),
1668 Some(Price::from("0.80010")),
1669 )
1670 .unwrap_err();
1671
1672 assert!(matches!(
1673 error.downcast_ref::<CorrectnessError>(),
1674 Some(CorrectnessError::PredicateViolation { message })
1675 if message.contains("QuantityRaw") || message.contains("QUANTITY_RAW_MAX")
1676 ));
1677 }
1678
1679 #[rstest]
1680 #[case(0.0, Quantity::from(1))]
1681 #[case(0.5, Quantity::from(500))]
1682 #[case(1.0, Quantity::from(1_000))]
1683 fn test_competition_aware_fill_model_builds_expected_liquidity(
1684 #[case] liquidity_factor: f64,
1685 #[case] expected_size: Quantity,
1686 ) {
1687 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1688 let order = OrderTestBuilder::new(OrderType::Market)
1689 .instrument_id(instrument.id())
1690 .side(OrderSide::Buy)
1691 .quantity(Quantity::from(100_000))
1692 .build();
1693 let best_bid = Price::from("0.80000");
1694 let best_ask = Price::from("0.80010");
1695 let mut model = CompetitionAwareFillModel::new(1.0, 0.0, None, liquidity_factor).unwrap();
1696
1697 let book = model
1698 .get_orderbook_for_fill_simulation(&instrument, &order, Some(best_bid), Some(best_ask))
1699 .unwrap()
1700 .unwrap();
1701
1702 assert_eq!(book.best_bid_price(), Some(best_bid));
1703 assert_eq!(book.best_ask_price(), Some(best_ask));
1704 assert_eq!(book.best_bid_size(), Some(expected_size));
1705 assert_eq!(book.best_ask_size(), Some(expected_size));
1706 }
1707
1708 #[rstest]
1709 fn test_competition_aware_fill_model_preserves_instrument_size_precision() {
1710 let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
1711 let order = OrderTestBuilder::new(OrderType::Market)
1712 .instrument_id(instrument.id())
1713 .side(OrderSide::Buy)
1714 .quantity(Quantity::from(100_000))
1715 .build();
1716 let best_bid = Price::from("2000.00");
1717 let best_ask = Price::from("2000.01");
1718 let mut model = CompetitionAwareFillModel::new(1.0, 0.0, None, 0.001234).unwrap();
1719
1720 let book = model
1721 .get_orderbook_for_fill_simulation(&instrument, &order, Some(best_bid), Some(best_ask))
1722 .unwrap()
1723 .unwrap();
1724
1725 assert_eq!(book.best_bid_price(), Some(best_bid));
1726 assert_eq!(book.best_ask_price(), Some(best_ask));
1727 assert_eq!(book.best_bid_size(), Some(Quantity::from("1.234")));
1728 assert_eq!(book.best_ask_size(), Some(Quantity::from("1.234")));
1729 }
1730
1731 #[rstest]
1732 fn test_volume_sensitive_fill_model_builds_expected_liquidity() {
1733 let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
1734 let order = OrderTestBuilder::new(OrderType::Market)
1735 .instrument_id(instrument.id())
1736 .side(OrderSide::Buy)
1737 .quantity(Quantity::from(100_000))
1738 .build();
1739 let best_bid = Price::from("2000.00");
1740 let best_ask = Price::from("2000.01");
1741 let mut model = VolumeSensitiveFillModel::default();
1742 model.set_recent_volume(5.678);
1743
1744 let book = model
1745 .get_orderbook_for_fill_simulation(&instrument, &order, Some(best_bid), Some(best_ask))
1746 .unwrap()
1747 .unwrap();
1748
1749 assert_eq!(book.best_bid_price(), Some(best_bid));
1750 assert_eq!(book.best_ask_price(), Some(best_ask));
1751 assert_eq!(book.best_bid_size(), Some(Quantity::from("1.420")));
1752 assert_eq!(book.best_ask_size(), Some(Quantity::from("1.420")));
1753 }
1754
1755 #[rstest]
1756 fn test_fill_model_is_limit_filled(mut fill_model: DefaultFillModel) {
1757 let result = fill_model.is_limit_filled().unwrap();
1759 assert!(!result);
1760 }
1761
1762 #[rstest]
1763 fn test_fill_model_is_slipped(mut fill_model: DefaultFillModel) {
1764 let result = fill_model.is_slipped().unwrap();
1766 assert!(!result);
1767 }
1768
1769 #[rstest]
1770 fn test_default_fill_model_returns_none() {
1771 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1772 let order = OrderTestBuilder::new(OrderType::Market)
1773 .instrument_id(instrument.id())
1774 .side(OrderSide::Buy)
1775 .quantity(Quantity::from(100_000))
1776 .build();
1777
1778 let mut model = DefaultFillModel::default();
1779 let result = model
1780 .get_orderbook_for_fill_simulation(
1781 &instrument,
1782 &order,
1783 Some(Price::from("0.80000")),
1784 Some(Price::from("0.80010")),
1785 )
1786 .unwrap();
1787 assert!(result.is_none());
1788 }
1789
1790 #[rstest]
1791 fn test_best_price_fill_model_returns_book() {
1792 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1793 let order = OrderTestBuilder::new(OrderType::Market)
1794 .instrument_id(instrument.id())
1795 .side(OrderSide::Buy)
1796 .quantity(Quantity::from(100_000))
1797 .build();
1798
1799 let mut model = BestPriceFillModel::default();
1800 let result = model
1801 .get_orderbook_for_fill_simulation(
1802 &instrument,
1803 &order,
1804 Some(Price::from("0.80000")),
1805 Some(Price::from("0.80010")),
1806 )
1807 .unwrap();
1808 assert!(result.is_some());
1809 let book = result.unwrap();
1810 assert_eq!(book.best_bid_price().unwrap(), Price::from("0.80000"));
1811 assert_eq!(book.best_ask_price().unwrap(), Price::from("0.80010"));
1812 }
1813
1814 #[rstest]
1815 #[case::buy_inside_spread(OrderSide::Buy, "0.80005", Some(("0.80000", "0.80005")))]
1816 #[case::buy_at_bid(OrderSide::Buy, "0.80000", Some(("0.80000", "0.80000")))]
1817 #[case::buy_crossing(OrderSide::Buy, "0.80020", Some(("0.80000", "0.80010")))]
1818 #[case::buy_passive(OrderSide::Buy, "0.79990", None)]
1819 #[case::sell_inside_spread(OrderSide::Sell, "0.80005", Some(("0.80005", "0.80010")))]
1820 #[case::sell_at_ask(OrderSide::Sell, "0.80010", Some(("0.80010", "0.80010")))]
1821 #[case::sell_crossing(OrderSide::Sell, "0.79990", Some(("0.80000", "0.80010")))]
1822 #[case::sell_passive(OrderSide::Sell, "0.80020", None)]
1823 fn test_best_price_fill_model_limit_book(
1824 #[case] side: OrderSide,
1825 #[case] limit_price: &str,
1826 #[case] expected_touch: Option<(&str, &str)>,
1827 ) {
1828 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1829 let order = OrderTestBuilder::new(OrderType::Limit)
1830 .instrument_id(instrument.id())
1831 .side(side)
1832 .price(Price::from(limit_price))
1833 .quantity(Quantity::from(100_000))
1834 .build();
1835
1836 let mut model = BestPriceFillModel::default();
1837 let book = model
1838 .get_orderbook_for_fill_simulation(
1839 &instrument,
1840 &order,
1841 Some(Price::from("0.80000")),
1842 Some(Price::from("0.80010")),
1843 )
1844 .unwrap();
1845
1846 let touch = book.map(|book| {
1847 (
1848 book.best_bid_price().unwrap(),
1849 book.best_ask_price().unwrap(),
1850 )
1851 });
1852
1853 let expected_touch = expected_touch.map(|(bid, ask)| (Price::from(bid), Price::from(ask)));
1854 assert_eq!(touch, expected_touch);
1855 }
1856
1857 #[rstest]
1858 #[case::at_min("0.001", true)]
1859 #[case::at_max("0.999", true)]
1860 #[case::below_min("0.000", false)]
1861 #[case::above_max("1.000", false)]
1862 fn test_is_price_tradable_respects_price_limits(#[case] price: &str, #[case] expected: bool) {
1863 let mut option = binary_option();
1864 option.min_price = Some(Price::from("0.001"));
1865 option.max_price = Some(Price::from("0.999"));
1866 let instrument = InstrumentAny::BinaryOption(option);
1867
1868 assert_eq!(is_price_tradable(&instrument, Price::from(price)), expected);
1869 }
1870
1871 #[rstest]
1872 #[case::zero_disallowed(InstrumentAny::BinaryOption(binary_option()), "0.000", false)]
1873 #[case::negative_disallowed(InstrumentAny::BinaryOption(binary_option()), "-0.001", false)]
1874 #[case::negative_allowed(InstrumentAny::FuturesSpread(futures_spread_es()), "-1.00", true)]
1875 #[case::negative_allowed_futures(
1876 InstrumentAny::FuturesContract(futures_contract_es(None, None)),
1877 "-1.00",
1878 true
1879 )]
1880 fn test_is_price_tradable_respects_price_sign(
1881 #[case] instrument: InstrumentAny,
1882 #[case] price: &str,
1883 #[case] expected: bool,
1884 ) {
1885 assert_eq!(is_price_tradable(&instrument, Price::from(price)), expected);
1886 }
1887
1888 #[rstest]
1889 fn test_one_tick_slippage_fill_model_skips_levels_outside_price_limits() {
1890 let mut option = binary_option();
1891 option.min_price = Some(Price::from("0.001"));
1892 option.max_price = Some(Price::from("0.999"));
1893 let instrument = InstrumentAny::BinaryOption(option);
1894 let order = OrderTestBuilder::new(OrderType::Market)
1895 .instrument_id(instrument.id())
1896 .side(OrderSide::Sell)
1897 .quantity(Quantity::from("10.00"))
1898 .build();
1899
1900 let mut model = OneTickSlippageFillModel::default();
1901 let book = model
1902 .get_orderbook_for_fill_simulation(
1903 &instrument,
1904 &order,
1905 Some(Price::from("0.001")),
1906 Some(Price::from("0.999")),
1907 )
1908 .unwrap()
1909 .unwrap();
1910
1911 assert_eq!(book.best_bid_price(), None);
1912 assert_eq!(book.best_ask_price(), None);
1913 }
1914
1915 #[rstest]
1916 fn test_fill_model_tolerates_probabilities_within_validation_epsilon() {
1917 let mut model =
1918 DefaultFillModel::new(1.0 + f64::EPSILON, 0.3 - 0.1 - 0.2, Some(1)).unwrap();
1919
1920 assert!(model.is_limit_filled().unwrap());
1921 assert!(!model.is_slipped().unwrap());
1922 }
1923
1924 #[rstest]
1925 fn test_one_tick_slippage_fill_model() {
1926 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1927 let order = OrderTestBuilder::new(OrderType::Market)
1928 .instrument_id(instrument.id())
1929 .side(OrderSide::Buy)
1930 .quantity(Quantity::from(100_000))
1931 .build();
1932
1933 let tick = instrument.price_increment();
1934 let best_bid = Price::from("0.80000");
1935 let best_ask = Price::from("0.80010");
1936
1937 let mut model = OneTickSlippageFillModel::default();
1938 let result = model
1939 .get_orderbook_for_fill_simulation(&instrument, &order, Some(best_bid), Some(best_ask))
1940 .unwrap();
1941 assert!(result.is_some());
1942 let book = result.unwrap();
1943
1944 assert_eq!(book.best_bid_price().unwrap(), best_bid - tick);
1945 assert_eq!(book.best_ask_price().unwrap(), best_ask + tick);
1946 }
1947
1948 #[rstest]
1949 fn test_probabilistic_fill_model_seeded_books() {
1950 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1951 let order = OrderTestBuilder::new(OrderType::Market)
1952 .instrument_id(instrument.id())
1953 .side(OrderSide::Buy)
1954 .quantity(Quantity::from(17))
1955 .build();
1956 let mut model = ProbabilisticFillModel::new(0.5, 0.1, Some(42)).unwrap();
1957 for (bid, ask) in [
1958 (dec!(0.79999), dec!(0.80011)),
1959 (dec!(0.79999), dec!(0.80011)),
1960 (dec!(0.79999), dec!(0.80011)),
1961 (dec!(0.80000), dec!(0.80010)),
1962 (dec!(0.80000), dec!(0.80010)),
1963 (dec!(0.80000), dec!(0.80010)),
1964 (dec!(0.79999), dec!(0.80011)),
1965 (dec!(0.79999), dec!(0.80011)),
1966 ] {
1967 let book = model
1968 .get_orderbook_for_fill_simulation(
1969 &instrument,
1970 &order,
1971 Some(Price::from("0.80000")),
1972 Some(Price::from("0.80010")),
1973 )
1974 .unwrap()
1975 .unwrap();
1976
1977 assert_eq!(
1978 book.bids_as_map(None).into_iter().collect::<Vec<_>>(),
1979 vec![(bid, dec!(10_000_000_000))]
1980 );
1981 assert_eq!(
1982 book.asks_as_map(None).into_iter().collect::<Vec<_>>(),
1983 vec![(ask, dec!(10_000_000_000))]
1984 );
1985 }
1986 }
1987
1988 #[rstest]
1989 fn test_fill_model_any_dispatch() {
1990 let model = FillModelAny::default();
1991 assert!(matches!(model, FillModelAny::Default(_)));
1992 }
1993
1994 #[rstest]
1995 #[case::two_tier(
1996 FillModelAny::TwoTier(TwoTierFillModel::default()),
1997 Quantity::from(10),
1998 vec![(dec!(0.80000), dec!(10)), (dec!(0.79999), dec!(10_000_000_000))],
1999 vec![(dec!(0.80010), dec!(10)), (dec!(0.80011), dec!(10_000_000_000))]
2000 )]
2001 #[case::three_tier(
2002 FillModelAny::ThreeTier(ThreeTierFillModel::default()),
2003 Quantity::from(10),
2004 vec![
2005 (dec!(0.80000), dec!(50)),
2006 (dec!(0.79999), dec!(30)),
2007 (dec!(0.79998), dec!(20)),
2008 ],
2009 vec![
2010 (dec!(0.80010), dec!(50)),
2011 (dec!(0.80011), dec!(30)),
2012 (dec!(0.80012), dec!(20)),
2013 ]
2014 )]
2015 #[case::limit_order_partial_fill(
2016 FillModelAny::LimitOrderPartialFill(LimitOrderPartialFillModel::default()),
2017 Quantity::from(10),
2018 vec![(dec!(0.80000), dec!(5)), (dec!(0.79999), dec!(10_000_000_000))],
2019 vec![(dec!(0.80010), dec!(5)), (dec!(0.80011), dec!(10_000_000_000))]
2020 )]
2021 #[case::size_aware_at_threshold(
2022 FillModelAny::SizeAware(SizeAwareFillModel::default()),
2023 Quantity::from(10),
2024 vec![(dec!(0.80000), dec!(50))],
2025 vec![(dec!(0.80010), dec!(50))]
2026 )]
2027 #[case::size_aware_above_threshold(
2028 FillModelAny::SizeAware(SizeAwareFillModel::default()),
2029 Quantity::from(11),
2030 vec![(dec!(0.80000), dec!(10)), (dec!(0.79999), dec!(1))],
2031 vec![(dec!(0.80010), dec!(10)), (dec!(0.80011), dec!(1))]
2032 )]
2033 fn test_fill_model_any_builds_expected_books(
2034 #[case] mut model: FillModelAny,
2035 #[case] order_qty: Quantity,
2036 #[case] expected_bids: Vec<(Decimal, Decimal)>,
2037 #[case] expected_asks: Vec<(Decimal, Decimal)>,
2038 ) {
2039 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
2040 let order = OrderTestBuilder::new(OrderType::Market)
2041 .instrument_id(instrument.id())
2042 .side(OrderSide::Buy)
2043 .quantity(order_qty)
2044 .build();
2045
2046 let book = model
2047 .get_orderbook_for_fill_simulation(
2048 &instrument,
2049 &order,
2050 Some(Price::from("0.80000")),
2051 Some(Price::from("0.80010")),
2052 )
2053 .unwrap()
2054 .unwrap();
2055
2056 assert_eq!(
2057 book.bids_as_map(None).into_iter().collect::<Vec<_>>(),
2058 expected_bids
2059 );
2060 assert_eq!(
2061 book.asks_as_map(None).into_iter().collect::<Vec<_>>(),
2062 expected_asks
2063 );
2064 }
2065
2066 #[rstest]
2067 fn test_fill_model_any_is_limit_filled() {
2068 let mut model = FillModelAny::Default(DefaultFillModel::new(0.5, 0.1, Some(42)).unwrap());
2069 let result = model.is_limit_filled().unwrap();
2070 assert!(!result);
2071 }
2072
2073 #[rstest]
2074 fn test_fill_model_handle_from_any_owns_state_per_conversion() {
2075 let model = FillModelAny::Default(DefaultFillModel::new(0.5, 0.0, Some(42)).unwrap());
2076 let mut expected_model = model.clone();
2077 let mut first: FillModelHandle = model.clone().into();
2078 let mut second: FillModelHandle = model.into();
2079
2080 let expected: Vec<_> = (0..16)
2081 .map(|_| expected_model.is_limit_filled().unwrap())
2082 .collect();
2083 let first_results: Vec<_> = (0..16).map(|_| first.is_limit_filled().unwrap()).collect();
2084 let second_results: Vec<_> = (0..16).map(|_| second.is_limit_filled().unwrap()).collect();
2085 let has_variation = expected.windows(2).any(|window| window[0] != window[1]);
2086
2087 assert!(has_variation);
2088 assert_eq!(first_results, expected);
2089 assert_eq!(second_results, expected);
2090 }
2091
2092 #[rstest]
2093 #[expect(clippy::redundant_clone, reason = "Clone is the behavior under test")]
2094 fn test_fill_model_clone_restarts_seeded_sequence() {
2095 let mut model = DefaultFillModel::new(0.5, 0.25, Some(42)).unwrap();
2096
2097 let expected: Vec<_> = (0..16)
2098 .map(|_| {
2099 (
2100 model.is_limit_filled().unwrap(),
2101 model.is_slipped().unwrap(),
2102 )
2103 })
2104 .collect();
2105
2106 let mut cloned = model.clone();
2107
2108 let actual: Vec<_> = (0..16)
2109 .map(|_| {
2110 (
2111 cloned.is_limit_filled().unwrap(),
2112 cloned.is_slipped().unwrap(),
2113 )
2114 })
2115 .collect();
2116
2117 assert_eq!(actual, expected);
2118 }
2119
2120 #[rstest]
2121 fn test_default_fill_model_fill_limit_inside_spread_is_false() {
2122 let model = DefaultFillModel::default();
2123 assert!(!model.fill_limit_inside_spread().unwrap());
2124 }
2125
2126 #[rstest]
2127 #[case(None, None)]
2128 #[case(None, Some(Price::from("0.80010")))]
2129 #[case(Some(Price::from("0.80000")), None)]
2130 fn test_builtin_fill_models_delegate_when_quotes_are_missing(
2131 #[case] best_bid: Option<Price>,
2132 #[case] best_ask: Option<Price>,
2133 ) {
2134 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
2135 let order = OrderTestBuilder::new(OrderType::Market)
2136 .instrument_id(instrument.id())
2137 .side(OrderSide::Buy)
2138 .quantity(Quantity::from(10))
2139 .build();
2140 let models: Vec<FillModelAny> = vec![
2141 FillModelAny::Default(DefaultFillModel::default()),
2142 FillModelAny::BestPrice(BestPriceFillModel::default()),
2143 FillModelAny::OneTickSlippage(OneTickSlippageFillModel::default()),
2144 FillModelAny::Probabilistic(ProbabilisticFillModel::default()),
2145 FillModelAny::TwoTier(TwoTierFillModel::default()),
2146 FillModelAny::ThreeTier(ThreeTierFillModel::default()),
2147 FillModelAny::LimitOrderPartialFill(LimitOrderPartialFillModel::default()),
2148 FillModelAny::SizeAware(SizeAwareFillModel::default()),
2149 FillModelAny::CompetitionAware(CompetitionAwareFillModel::default()),
2150 FillModelAny::VolumeSensitive(VolumeSensitiveFillModel::default()),
2151 FillModelAny::MarketHours(MarketHoursFillModel::default()),
2152 ];
2153
2154 for mut model in models {
2155 assert!(
2156 model
2157 .get_orderbook_for_fill_simulation(&instrument, &order, best_bid, best_ask)
2158 .unwrap()
2159 .is_none()
2160 );
2161 }
2162 }
2163
2164 #[rstest]
2165 fn test_best_price_fill_model_fill_limit_inside_spread_is_true() {
2166 let model = BestPriceFillModel::default();
2167 assert!(model.fill_limit_inside_spread().unwrap());
2168 }
2169
2170 #[rstest]
2171 fn test_one_tick_slippage_fill_model_fill_limit_inside_spread_is_false() {
2172 let model = OneTickSlippageFillModel::default();
2173 assert!(!model.fill_limit_inside_spread().unwrap());
2174 }
2175
2176 #[rstest]
2177 fn test_fill_model_any_fill_limit_inside_spread_dispatch() {
2178 let models: Vec<FillModelAny> = vec![
2179 FillModelAny::Default(DefaultFillModel::default()),
2180 FillModelAny::BestPrice(BestPriceFillModel::default()),
2181 FillModelAny::OneTickSlippage(OneTickSlippageFillModel::default()),
2182 FillModelAny::Probabilistic(ProbabilisticFillModel::default()),
2183 FillModelAny::TwoTier(TwoTierFillModel::default()),
2184 FillModelAny::ThreeTier(ThreeTierFillModel::default()),
2185 FillModelAny::LimitOrderPartialFill(LimitOrderPartialFillModel::default()),
2186 FillModelAny::SizeAware(SizeAwareFillModel::default()),
2187 FillModelAny::CompetitionAware(CompetitionAwareFillModel::default()),
2188 FillModelAny::VolumeSensitive(VolumeSensitiveFillModel::default()),
2189 FillModelAny::MarketHours(MarketHoursFillModel::default()),
2190 ];
2191
2192 let expected_policies = [
2193 false, true, false, false, false, false, false, false, false, false, false,
2194 ];
2195
2196 for (model, expected) in models.into_iter().zip(expected_policies) {
2197 assert_eq!(model.fill_limit_inside_spread().unwrap(), expected);
2198 }
2199 }
2200
2201 #[rstest]
2202 fn test_market_hours_fill_model_switches_liquidity_and_preserves_clone_state() {
2203 let instrument = InstrumentAny::CurrencyPair(audusd_sim());
2204 let order = OrderTestBuilder::new(OrderType::Market)
2205 .instrument_id(instrument.id())
2206 .side(OrderSide::Buy)
2207 .quantity(Quantity::from(17))
2208 .build();
2209 let mut model = MarketHoursFillModel::default();
2210
2211 for (low_liquidity, bid, ask) in [
2212 (false, dec!(0.80000), dec!(0.80010)),
2213 (true, dec!(0.79999), dec!(0.80011)),
2214 (false, dec!(0.80000), dec!(0.80010)),
2215 ] {
2216 model.set_low_liquidity_period(low_liquidity);
2217 let mut cloned = model.clone();
2218 let book = cloned
2219 .get_orderbook_for_fill_simulation(
2220 &instrument,
2221 &order,
2222 Some(Price::from("0.80000")),
2223 Some(Price::from("0.80010")),
2224 )
2225 .unwrap()
2226 .unwrap();
2227
2228 assert_eq!(model.is_low_liquidity_period(), low_liquidity);
2229 assert_eq!(cloned.is_low_liquidity_period(), low_liquidity);
2230 assert_eq!(
2231 book.bids_as_map(None).into_iter().collect::<Vec<_>>(),
2232 vec![(bid, dec!(500))]
2233 );
2234 assert_eq!(
2235 book.asks_as_map(None).into_iter().collect::<Vec<_>>(),
2236 vec![(ask, dec!(500))]
2237 );
2238 }
2239 }
2240}