Skip to main content

nautilus_common/clients/
execution.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//! Execution client trait definition.
17
18use std::{fmt::Debug, future::Future, pin::Pin};
19
20use anyhow::Context;
21use async_trait::async_trait;
22use indexmap::IndexMap;
23use nautilus_core::{DurationNanos, Params, UnixNanos, time::get_atomic_clock_realtime};
24use nautilus_model::{
25    accounts::AccountAny,
26    enums::{LiquiditySide, OmsType},
27    identifiers::{
28        AccountId, ClientId, ClientOrderId, InstrumentId, StrategyId, Venue, VenueOrderId,
29    },
30    instruments::InstrumentAny,
31    orders::OrderAny,
32    reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
33    types::{AccountBalance, MarginBalance, Money, Price, Quantity},
34};
35use rust_decimal::Decimal;
36
37use super::log_not_implemented;
38use crate::messages::execution::{
39    BatchCancelOrders, BatchModifyOrders, CancelAllOrders, CancelOrder, GenerateFillReports,
40    GenerateFillReportsBuilder, GenerateOrderStatusReport, GenerateOrderStatusReports,
41    GenerateOrderStatusReportsBuilder, GeneratePositionStatusReports,
42    GeneratePositionStatusReportsBuilder, ModifyOrder, QueryAccount, QueryOrder, SubmitOrder,
43    SubmitOrderList,
44};
45
46/// Default maximum absolute position difference tolerated during reconciliation.
47pub const DEFAULT_POSITION_RECONCILIATION_TOLERANCE: Decimal =
48    Decimal::from_parts(1, 0, 0, false, 8);
49
50/// Owned report collection with a core-thread continuation.
51///
52/// Only `collection` runs on a worker. After the worker terminates, `finish` uses the caller's
53/// core state to complete reports without moving the live client or cache.
54#[must_use]
55pub struct ExecutionReportTask<T> {
56    /// Worker-safe collection, including decoding and report construction.
57    pub collection: Pin<Box<dyn Future<Output = ()> + Send>>,
58    /// Synchronous core-thread finalization after the collection worker is joined.
59    pub finish: Box<dyn FnOnce() -> anyhow::Result<T>>,
60}
61
62impl<T> Debug for ExecutionReportTask<T> {
63    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        formatter
65            .debug_struct(stringify!(ExecutionReportTask))
66            .finish_non_exhaustive()
67    }
68}
69
70impl<T: 'static> ExecutionReportTask<T> {
71    /// Creates an owned collection and a synchronous core-thread continuation.
72    ///
73    /// The collection must not access the live cache. Neither phase may apply execution events.
74    /// The continuation runs only after the worker terminates; canceled collections never run it.
75    ///
76    /// Finalization propagates collection errors without calling the continuation. It also returns
77    /// an error if collection is unfinished or stopped without a result.
78    pub fn new<C, F, M>(collection: F, finish: M) -> Self
79    where
80        C: Send + 'static,
81        F: Future<Output = anyhow::Result<C>> + Send + 'static,
82        M: FnOnce(C) -> anyhow::Result<T> + 'static,
83    {
84        let (sender, mut receiver) = futures::channel::oneshot::channel();
85        Self {
86            collection: Box::pin(async move {
87                let _ = sender.send(collection.await);
88            }),
89            finish: Box::new(move || {
90                let collected = receiver
91                    .try_recv()
92                    .context("report collection stopped without a result")?
93                    .context("report collection has not finished")??;
94                finish(collected)
95            }),
96        }
97    }
98}
99
100/// Defines the interface for an execution client managing order operations.
101///
102/// # Thread Safety
103///
104/// Client instances are not intended to be sent across threads. The `?Send` bound
105/// allows implementations to hold non-Send state for any Python interop.
106#[async_trait(?Send)]
107pub trait ExecutionClient {
108    fn is_connected(&self) -> bool;
109    fn client_id(&self) -> ClientId;
110    fn account_id(&self) -> AccountId;
111    fn venue(&self) -> Venue;
112    fn oms_type(&self) -> OmsType;
113    fn get_account(&self) -> Option<AccountAny>;
114
115    /// Returns whether unacknowledged orders require venue evidence before local closure.
116    ///
117    /// `LiveNode` registers this requirement with the live execution manager automatically.
118    /// Registered clients retain these orders after recovery exhaustion, even when local timeout
119    /// or missing-order resolution is enabled.
120    fn retain_unresolved_submissions(&self) -> bool {
121        false
122    }
123
124    /// Returns venue order ID histories for startup reconciliation, keyed by client order ID.
125    ///
126    /// Each history covers one proven logical order: at least two IDs, oldest first and current last.
127    ///
128    /// - Reports share a client order ID and exclude cached orders and indexed venue IDs.
129    /// - Previous reports are closed and contribute only fills and ID history.
130    /// - The current report is open, with logical quantity and cumulative fills.
131    /// - Its acceptance time is no later than any fill in the history.
132    ///
133    /// The live execution manager consumes these histories. Defaults to `None`; overrides must not
134    /// change client state.
135    fn venue_order_ids(
136        &self,
137        _mass_status: &ExecutionMassStatus,
138    ) -> Option<IndexMap<ClientOrderId, Vec<VenueOrderId>>> {
139        None
140    }
141
142    /// Returns the maximum absolute position difference tolerated during reconciliation.
143    fn position_reconciliation_tolerance(&self) -> Decimal {
144        DEFAULT_POSITION_RECONCILIATION_TOLERANCE
145    }
146
147    /// Returns whether reconciliation may raise the order quantity so this fill can apply.
148    ///
149    /// The default is `false`, so an overfill stays rejected when `allow_overfills` is disabled.
150    /// An override must not change client state. The engine raises the quantity to the order's
151    /// filled quantity plus this fill, then applies the fill unchanged.
152    fn allows_reconciliation_overfill(&self, _order: &OrderAny, _report: &FillReport) -> bool {
153        false
154    }
155
156    /// Returns whether order status reconciliation requires authoritative fills.
157    ///
158    /// When true, order status alone cannot create inferred fills. Missing executions and dependent
159    /// status transitions wait for venue fills from private updates or reconciliation. Defaults to
160    /// `false`. Position-only synthetic corrections are unaffected.
161    fn requires_authoritative_fills(&self) -> bool {
162        false
163    }
164
165    /// Returns whether this client can execute orders for the given instrument venue.
166    ///
167    /// Single-venue clients should use the default behavior. Routing execution providers can
168    /// override this when their client venue identifies the provider rather than
169    /// the instrument's exchange venue.
170    fn handles_order_venue(&self, venue: Venue) -> bool {
171        self.venue() == venue
172    }
173
174    /// Returns whether a bulk position status report request provides complete coverage for the
175    /// given instrument, so that an absent report is evidence the position is flat.
176    fn provides_bulk_position_coverage(&self, _instrument_id: InstrumentId) -> bool {
177        true
178    }
179
180    /// Returns whether this client's venue settles expiring contracts itself, such as a
181    /// simulated venue that closes positions with expiration fills.
182    ///
183    /// The execution engine does not apply `InstrumentClose` settlement for such a venue.
184    fn settles_contract_expirations(&self) -> bool {
185        false
186    }
187
188    /// Generates and publishes the account state event.
189    ///
190    /// Implementations may publish synchronously. Callers must release shared state borrows,
191    /// including clock and cache borrows, before calling this method because subscribers may
192    /// access the same state.
193    ///
194    /// # Errors
195    ///
196    /// Returns an error if generating the account state fails.
197    fn generate_account_state(
198        &self,
199        balances: Vec<AccountBalance>,
200        margins: Vec<MarginBalance>,
201        reported: bool,
202        ts_event: UnixNanos,
203        info: Option<Params>,
204    ) -> anyhow::Result<()>;
205
206    /// Starts the execution client.
207    ///
208    /// # Errors
209    ///
210    /// Returns an error if the client fails to start.
211    fn start(&mut self) -> anyhow::Result<()>;
212
213    /// Stops the execution client.
214    ///
215    /// Implementations must be idempotent: the engine and node teardown paths
216    /// (e.g. backtest `end` -> `reset` -> `dispose`) may call `stop()` more
217    /// than once per run. Guard with an internal `is_stopped` check or
218    /// equivalent so repeated calls are safe.
219    ///
220    /// # Errors
221    ///
222    /// Returns an error if the client fails to stop.
223    fn stop(&mut self) -> anyhow::Result<()>;
224
225    /// Resets the execution client to its initial state.
226    ///
227    /// The default implementation is a no-op. Adapters with reconnectable state
228    /// (caches, sequence counters, in-flight orders) should override this.
229    ///
230    /// # Errors
231    ///
232    /// Returns an error if the client fails to reset.
233    fn reset(&mut self) -> anyhow::Result<()> {
234        Ok(())
235    }
236
237    /// Disposes of client resources and cleans up.
238    ///
239    /// The default implementation is a no-op. Adapters that hold async tasks,
240    /// background threads, or external handles should override this.
241    ///
242    /// # Errors
243    ///
244    /// Returns an error if the client fails to dispose.
245    fn dispose(&mut self) -> anyhow::Result<()> {
246        Ok(())
247    }
248
249    /// Connects the client to the execution venue.
250    ///
251    /// # Errors
252    ///
253    /// Returns an error if connection fails.
254    async fn connect(&mut self) -> anyhow::Result<()> {
255        Ok(())
256    }
257
258    /// Disconnects the client from the execution venue.
259    ///
260    /// # Errors
261    ///
262    /// Returns an error if disconnection fails.
263    async fn disconnect(&mut self) -> anyhow::Result<()> {
264        Ok(())
265    }
266
267    /// Submits a single order command to the execution venue.
268    ///
269    /// # Errors
270    ///
271    /// Returns an error if submission fails.
272    fn submit_order(&self, cmd: SubmitOrder) -> anyhow::Result<()> {
273        log_not_implemented(self.client_id(), &cmd);
274        Ok(())
275    }
276
277    /// Submits a list of orders to the execution venue.
278    ///
279    /// # Errors
280    ///
281    /// Returns an error if submission fails.
282    fn submit_order_list(&self, cmd: SubmitOrderList) -> anyhow::Result<()> {
283        log_not_implemented(self.client_id(), &cmd);
284        Ok(())
285    }
286
287    /// Modifies an existing order.
288    ///
289    /// # Errors
290    ///
291    /// Returns an error if modification fails.
292    fn modify_order(&self, cmd: ModifyOrder) -> anyhow::Result<()> {
293        log_not_implemented(self.client_id(), &cmd);
294        Ok(())
295    }
296
297    /// Modifies a batch of orders.
298    ///
299    /// The default implementation fans out to [`Self::modify_order`] so existing execution
300    /// clients remain compatible until they add native batch support.
301    ///
302    /// # Errors
303    ///
304    /// Returns an error if any child modification fails.
305    fn batch_modify_orders(&self, cmd: BatchModifyOrders) -> anyhow::Result<()> {
306        for modify in cmd.modifies {
307            self.modify_order(modify)?;
308        }
309        Ok(())
310    }
311
312    /// Cancels a specific order.
313    ///
314    /// # Errors
315    ///
316    /// Returns an error if cancellation fails.
317    fn cancel_order(&self, cmd: CancelOrder) -> anyhow::Result<()> {
318        log_not_implemented(self.client_id(), &cmd);
319        Ok(())
320    }
321
322    /// Cancels all orders.
323    ///
324    /// # Errors
325    ///
326    /// Returns an error if cancellation fails.
327    fn cancel_all_orders(&self, cmd: CancelAllOrders) -> anyhow::Result<()> {
328        log_not_implemented(self.client_id(), &cmd);
329        Ok(())
330    }
331
332    /// Cancels a batch of orders.
333    ///
334    /// # Errors
335    ///
336    /// Returns an error if batch cancellation fails.
337    fn batch_cancel_orders(&self, cmd: BatchCancelOrders) -> anyhow::Result<()> {
338        log_not_implemented(self.client_id(), &cmd);
339        Ok(())
340    }
341
342    /// Queries the status of an account.
343    ///
344    /// # Errors
345    ///
346    /// Returns an error if the query fails.
347    fn query_account(&self, cmd: QueryAccount) -> anyhow::Result<()> {
348        log_not_implemented(self.client_id(), &cmd);
349        Ok(())
350    }
351
352    /// Queries the status of an order.
353    ///
354    /// # Errors
355    ///
356    /// Returns an error if the query fails.
357    fn query_order(&self, cmd: QueryOrder) -> anyhow::Result<()> {
358        log_not_implemented(self.client_id(), &cmd);
359        Ok(())
360    }
361
362    /// Prepares worker-safe single-order collection, or uses inline collection.
363    ///
364    /// Preparation and the task's continuation run synchronously on the core thread.
365    /// Return `None` when collection is not yet worker-safe.
366    fn generate_order_status_report_task(
367        &self,
368        _cmd: &GenerateOrderStatusReport,
369    ) -> Option<ExecutionReportTask<Option<OrderStatusReport>>> {
370        None
371    }
372
373    /// Generates a single order status report.
374    ///
375    /// # Errors
376    ///
377    /// Returns an error if report generation fails.
378    async fn generate_order_status_report(
379        &self,
380        cmd: &GenerateOrderStatusReport,
381    ) -> anyhow::Result<Option<OrderStatusReport>> {
382        log_not_implemented(self.client_id(), cmd);
383        Ok(None)
384    }
385
386    /// Prepares worker-safe bulk order collection, or uses inline collection.
387    fn generate_order_status_reports_task(
388        &self,
389        _cmd: &GenerateOrderStatusReports,
390    ) -> Option<ExecutionReportTask<Vec<OrderStatusReport>>> {
391        None
392    }
393
394    /// Generates multiple order status reports.
395    ///
396    /// # Errors
397    ///
398    /// Returns an error if report generation fails.
399    async fn generate_order_status_reports(
400        &self,
401        cmd: &GenerateOrderStatusReports,
402    ) -> anyhow::Result<Vec<OrderStatusReport>> {
403        log_not_implemented(self.client_id(), cmd);
404        Ok(Vec::new())
405    }
406
407    /// Prepares worker-safe fill collection, or uses inline collection.
408    fn generate_fill_reports_task(
409        &self,
410        _cmd: &GenerateFillReports,
411    ) -> Option<ExecutionReportTask<Vec<FillReport>>> {
412        None
413    }
414
415    /// Generates fill reports based on execution results.
416    ///
417    /// # Errors
418    ///
419    /// Returns an error if fill report generation fails.
420    async fn generate_fill_reports(
421        &self,
422        cmd: GenerateFillReports,
423    ) -> anyhow::Result<Vec<FillReport>> {
424        log_not_implemented(self.client_id(), &cmd);
425        Ok(Vec::new())
426    }
427
428    /// Prepares worker-safe position collection, or uses inline collection.
429    fn generate_position_status_reports_task(
430        &self,
431        _cmd: &GeneratePositionStatusReports,
432    ) -> Option<ExecutionReportTask<Vec<PositionStatusReport>>> {
433        None
434    }
435
436    /// Generates position status reports.
437    ///
438    /// # Errors
439    ///
440    /// Returns an error if generation fails.
441    async fn generate_position_status_reports(
442        &self,
443        cmd: &GeneratePositionStatusReports,
444    ) -> anyhow::Result<Vec<PositionStatusReport>> {
445        log_not_implemented(self.client_id(), cmd);
446        Ok(Vec::new())
447    }
448
449    /// Generates mass status for executions.
450    ///
451    /// The default composes the granular report generators using the realtime atomic clock.
452    /// This is clock-correct only for live/realtime clients; clients using a mocked or backtest
453    /// clock must override this method to compose reports with their own clock.
454    ///
455    /// # Errors
456    ///
457    /// Returns an error if status generation fails.
458    async fn generate_mass_status(
459        &self,
460        lookback_mins: Option<u64>,
461    ) -> anyhow::Result<Option<ExecutionMassStatus>> {
462        generate_mass_status(
463            self,
464            lookback_mins,
465            get_atomic_clock_realtime().get_time_ns(),
466        )
467        .await
468    }
469
470    /// Registers an external order for tracking by the execution client.
471    ///
472    /// This is called after reconciliation creates an external order, allowing the
473    /// execution client to track it for subsequent events (e.g., cancellations).
474    fn register_external_order(
475        &self,
476        _client_order_id: ClientOrderId,
477        _venue_order_id: VenueOrderId,
478        _instrument_id: InstrumentId,
479        _strategy_id: StrategyId,
480        _ts_init: UnixNanos,
481    ) {
482        // Default no-op implementation
483    }
484
485    /// Handles an instrument update received via the message bus.
486    ///
487    /// Exec clients that need live instrument updates (e.g. for internal maps)
488    /// can override this to process instruments for their venue.
489    fn on_instrument(&mut self, _instrument: InstrumentAny) {
490        // Default no-op
491    }
492
493    /// Calculates the commission for a reconciliation fill.
494    ///
495    /// Override this method to provide venue-specific commission logic
496    /// for inferred fills generated during reconciliation.
497    /// The quantity, price, and liquidity side match the inferred fill event,
498    /// including any price derived for only the unbooked incremental quantity.
499    ///
500    /// Returns `Ok(None)` by default, signaling callers to use their own
501    /// generic commission formula. An error means the venue formula applies
502    /// but its result could not be represented, so callers must not substitute
503    /// a zero or generic commission for it.
504    ///
505    /// # Errors
506    ///
507    /// Returns an error if the venue commission cannot be calculated or represented.
508    #[expect(unused_variables)]
509    fn calculate_commission(
510        &self,
511        instrument: &InstrumentAny,
512        last_qty: Quantity,
513        last_px: Price,
514        liquidity_side: LiquiditySide,
515    ) -> anyhow::Result<Option<Money>> {
516        Ok(None)
517    }
518}
519
520/// Composes an execution mass status using the supplied client clock timestamp.
521///
522/// # Errors
523///
524/// Returns an error if the lookback cannot be represented or a report source fails.
525pub async fn generate_mass_status<C: ExecutionClient + ?Sized>(
526    client: &C,
527    lookback_mins: Option<u64>,
528    ts_init: UnixNanos,
529) -> anyhow::Result<Option<ExecutionMassStatus>> {
530    let start = lookback_mins
531        .map(DurationNanos::try_from_mins)
532        .transpose()?
533        .map(|lookback| ts_init.saturating_sub(lookback));
534
535    let order_cmd = GenerateOrderStatusReportsBuilder::default()
536        .ts_init(ts_init)
537        .open_only(false)
538        .start(start)
539        .build()
540        .context("failed to build order status reports command")?;
541    let fill_cmd = GenerateFillReportsBuilder::default()
542        .ts_init(ts_init)
543        .start(start)
544        .build()
545        .context("failed to build fill reports command")?;
546    let position_cmd = GeneratePositionStatusReportsBuilder::default()
547        .ts_init(ts_init)
548        .start(start)
549        .build()
550        .context("failed to build position status reports command")?;
551
552    let (order_reports, fill_reports, position_reports) = futures::try_join!(
553        async {
554            client
555                .generate_order_status_reports(&order_cmd)
556                .await
557                .context("failed to generate order status reports")
558        },
559        async {
560            client
561                .generate_fill_reports(fill_cmd)
562                .await
563                .context("failed to generate fill reports")
564        },
565        async {
566            client
567                .generate_position_status_reports(&position_cmd)
568                .await
569                .context("failed to generate position status reports")
570        },
571    )?;
572
573    let mut mass_status = ExecutionMassStatus::new(
574        client.client_id(),
575        client.account_id(),
576        client.venue(),
577        ts_init,
578        None,
579    );
580    mass_status.add_order_reports(order_reports);
581    mass_status.add_fill_reports(fill_reports);
582    mass_status.add_position_reports(position_reports);
583
584    Ok(Some(mass_status))
585}
586
587#[cfg(test)]
588mod tests {
589    use std::{
590        cell::{Cell, RefCell},
591        rc::Rc,
592    };
593
594    use nautilus_core::UUID4;
595    use nautilus_model::{
596        enums::{
597            LiquiditySide, OmsType, OrderSide, OrderStatus, OrderType, PositionSide, TimeInForce,
598        },
599        identifiers::{PositionId, TradeId, TraderId, Venue},
600        types::Currency,
601    };
602    use rstest::rstest;
603
604    use super::*;
605
606    #[rstest]
607    fn report_task_rejects_unfinished_collection() {
608        let finalized = Rc::new(Cell::new(0));
609        let finalized_for_task = Rc::clone(&finalized);
610
611        let task = ExecutionReportTask::new(async { Ok(17) }, move |value| {
612            finalized_for_task.set(value);
613            Ok(value)
614        });
615
616        let error = (task.finish)().unwrap_err();
617
618        assert_eq!(error.to_string(), "report collection has not finished");
619        assert_eq!(finalized.get(), 0);
620    }
621
622    #[rstest]
623    fn report_task_propagates_collection_error_without_finalizing() {
624        let finalized = Rc::new(Cell::new(0));
625        let finalized_for_task = Rc::clone(&finalized);
626
627        let task = ExecutionReportTask::new(
628            async { Err::<usize, _>(anyhow::anyhow!("report endpoint unavailable")) },
629            move |value| {
630                finalized_for_task.set(value);
631                Ok(value)
632            },
633        );
634
635        futures::executor::block_on(task.collection);
636
637        let error = (task.finish)().unwrap_err();
638
639        assert_eq!(error.to_string(), "report endpoint unavailable");
640        assert_eq!(finalized.get(), 0);
641    }
642
643    #[rstest]
644    #[case::unpolled(false)]
645    #[case::pending(true)]
646    fn report_task_rejects_dropped_collection(#[case] poll_collection: bool) {
647        let finalized = Rc::new(Cell::new(0));
648        let finalized_for_task = Rc::clone(&finalized);
649        let mut task = ExecutionReportTask::new(std::future::pending(), move |value: usize| {
650            finalized_for_task.set(value);
651            Ok(value)
652        });
653
654        if poll_collection {
655            let mut context = std::task::Context::from_waker(futures::task::noop_waker_ref());
656            assert!(task.collection.as_mut().poll(&mut context).is_pending());
657        }
658
659        drop(task.collection);
660
661        let error = (task.finish)().unwrap_err();
662
663        assert_eq!(
664            error.to_string(),
665            "report collection stopped without a result"
666        );
667        assert_eq!(finalized.get(), 0);
668    }
669
670    #[rstest]
671    fn report_task_finalizes_with_current_core_state() {
672        let current = Rc::new(Cell::new(11));
673        let current_for_task = Rc::clone(&current);
674
675        let task = ExecutionReportTask::new(async { Ok(13) }, move |value| {
676            Ok(value + current_for_task.get())
677        });
678
679        futures::executor::block_on(task.collection);
680        current.set(29);
681
682        let result = (task.finish)().unwrap();
683
684        assert_eq!(result, 42);
685    }
686
687    #[rstest]
688    fn report_task_propagates_continuation_error() {
689        let finalized = Rc::new(Cell::new(0));
690        let finalized_for_task = Rc::clone(&finalized);
691
692        let task = ExecutionReportTask::new(async { Ok(23) }, move |value| {
693            finalized_for_task.set(value);
694            Err::<usize, _>(anyhow::anyhow!("report finalization failed"))
695        });
696
697        futures::executor::block_on(task.collection);
698
699        let error = (task.finish)().unwrap_err();
700
701        assert_eq!(error.to_string(), "report finalization failed");
702        assert_eq!(finalized.get(), 23);
703    }
704
705    struct RecordingExecutionClient {
706        modified_order_ids: Rc<RefCell<Vec<ClientOrderId>>>,
707    }
708
709    impl RecordingExecutionClient {
710        fn new(modified_order_ids: Rc<RefCell<Vec<ClientOrderId>>>) -> Self {
711            Self { modified_order_ids }
712        }
713    }
714
715    #[async_trait(?Send)]
716    impl ExecutionClient for RecordingExecutionClient {
717        fn is_connected(&self) -> bool {
718            true
719        }
720
721        fn client_id(&self) -> ClientId {
722            ClientId::from("TEST")
723        }
724
725        fn account_id(&self) -> AccountId {
726            AccountId::from("TEST-001")
727        }
728
729        fn venue(&self) -> Venue {
730            Venue::from("SIM")
731        }
732
733        fn oms_type(&self) -> OmsType {
734            OmsType::Netting
735        }
736
737        fn get_account(&self) -> Option<AccountAny> {
738            None
739        }
740
741        fn generate_account_state(
742            &self,
743            _balances: Vec<AccountBalance>,
744            _margins: Vec<MarginBalance>,
745            _reported: bool,
746            _ts_event: UnixNanos,
747            _info: Option<Params>,
748        ) -> anyhow::Result<()> {
749            Ok(())
750        }
751
752        fn start(&mut self) -> anyhow::Result<()> {
753            Ok(())
754        }
755
756        fn stop(&mut self) -> anyhow::Result<()> {
757            Ok(())
758        }
759
760        fn modify_order(&self, cmd: ModifyOrder) -> anyhow::Result<()> {
761            self.modified_order_ids
762                .borrow_mut()
763                .push(cmd.client_order_id);
764
765            Ok(())
766        }
767    }
768
769    struct MassStatusExecutionClient {
770        order_commands: RefCell<Vec<GenerateOrderStatusReports>>,
771        fill_requests: RefCell<Vec<GenerateFillReports>>,
772        position_queries: RefCell<Vec<GeneratePositionStatusReports>>,
773        fail_fill: bool,
774    }
775
776    impl MassStatusExecutionClient {
777        fn new(fail_fill: bool) -> Self {
778            Self {
779                order_commands: RefCell::new(Vec::new()),
780                fill_requests: RefCell::new(Vec::new()),
781                position_queries: RefCell::new(Vec::new()),
782                fail_fill,
783            }
784        }
785    }
786
787    #[async_trait(?Send)]
788    impl ExecutionClient for MassStatusExecutionClient {
789        fn is_connected(&self) -> bool {
790            true
791        }
792
793        fn client_id(&self) -> ClientId {
794            ClientId::from("MASS-STATUS")
795        }
796
797        fn account_id(&self) -> AccountId {
798            AccountId::from("MASS-STATUS-001")
799        }
800
801        fn venue(&self) -> Venue {
802            Venue::from("SIM")
803        }
804
805        fn oms_type(&self) -> OmsType {
806            OmsType::Netting
807        }
808
809        fn get_account(&self) -> Option<AccountAny> {
810            None
811        }
812
813        fn generate_account_state(
814            &self,
815            _balances: Vec<AccountBalance>,
816            _margins: Vec<MarginBalance>,
817            _reported: bool,
818            _ts_event: UnixNanos,
819            _info: Option<Params>,
820        ) -> anyhow::Result<()> {
821            Ok(())
822        }
823
824        fn start(&mut self) -> anyhow::Result<()> {
825            Ok(())
826        }
827
828        fn stop(&mut self) -> anyhow::Result<()> {
829            Ok(())
830        }
831
832        async fn generate_order_status_reports(
833            &self,
834            cmd: &GenerateOrderStatusReports,
835        ) -> anyhow::Result<Vec<OrderStatusReport>> {
836            self.order_commands.borrow_mut().push(cmd.clone());
837            Ok(vec![test_order_report()])
838        }
839
840        async fn generate_fill_reports(
841            &self,
842            cmd: GenerateFillReports,
843        ) -> anyhow::Result<Vec<FillReport>> {
844            self.fill_requests.borrow_mut().push(cmd);
845
846            if self.fail_fill {
847                anyhow::bail!("sentinel fill report failure");
848            }
849            Ok(vec![test_fill_report()])
850        }
851
852        async fn generate_position_status_reports(
853            &self,
854            cmd: &GeneratePositionStatusReports,
855        ) -> anyhow::Result<Vec<PositionStatusReport>> {
856            self.position_queries.borrow_mut().push(cmd.clone());
857            Ok(vec![test_position_report()])
858        }
859    }
860
861    fn test_order_report() -> OrderStatusReport {
862        OrderStatusReport::new(
863            AccountId::from("MASS-STATUS-001"),
864            InstrumentId::from("AUD/USD.SIM"),
865            None,
866            VenueOrderId::from("ORDER-001"),
867            OrderSide::Buy.into(),
868            OrderType::Limit,
869            TimeInForce::Gtc,
870            OrderStatus::Accepted,
871            Quantity::from("10"),
872            Quantity::from("0"),
873            UnixNanos::from(1_000_000_000),
874            UnixNanos::from(2_000_000_000),
875            UnixNanos::from(3_000_000_000),
876            None,
877        )
878    }
879
880    fn test_fill_report() -> FillReport {
881        FillReport::new(
882            AccountId::from("MASS-STATUS-001"),
883            InstrumentId::from("AUD/USD.SIM"),
884            VenueOrderId::from("ORDER-001"),
885            TradeId::from("TRADE-001"),
886            OrderSide::Buy,
887            Quantity::from("5"),
888            Price::from("1.00010"),
889            Money::new(1.0, Currency::USD()),
890            LiquiditySide::Taker,
891            None,
892            None,
893            UnixNanos::from(4_000_000_000),
894            UnixNanos::from(5_000_000_000),
895            None,
896        )
897    }
898
899    fn test_position_report() -> PositionStatusReport {
900        PositionStatusReport::new(
901            AccountId::from("MASS-STATUS-001"),
902            InstrumentId::from("AUD/USD.SIM"),
903            PositionSide::Long,
904            Quantity::from("5"),
905            UnixNanos::from(6_000_000_000),
906            UnixNanos::from(7_000_000_000),
907            None,
908            Some(PositionId::from("POSITION-001")),
909            None,
910        )
911    }
912
913    #[rstest]
914    fn batch_modify_orders_default_fans_out_to_modify_order() {
915        let modified_order_ids = Rc::new(RefCell::new(Vec::new()));
916        let client = RecordingExecutionClient::new(modified_order_ids.clone());
917        let instrument_id = InstrumentId::from("AUD/USD.SIM");
918        let order1 = ClientOrderId::from("O-DEFAULT-BATCH-001");
919        let order2 = ClientOrderId::from("O-DEFAULT-BATCH-002");
920        let command = BatchModifyOrders::new(
921            TraderId::from("TRADER-001"),
922            Some(ClientId::from("TEST")),
923            StrategyId::from("S-001"),
924            instrument_id,
925            vec![
926                ModifyOrder::new(
927                    TraderId::from("TRADER-001"),
928                    Some(ClientId::from("TEST")),
929                    StrategyId::from("S-001"),
930                    instrument_id,
931                    order1,
932                    None,
933                    Some(Quantity::from("10")),
934                    Some(Price::from("1.00010")),
935                    None,
936                    UUID4::new(),
937                    UnixNanos::default(),
938                    None,
939                    None,
940                ),
941                ModifyOrder::new(
942                    TraderId::from("TRADER-001"),
943                    Some(ClientId::from("TEST")),
944                    StrategyId::from("S-001"),
945                    instrument_id,
946                    order2,
947                    None,
948                    Some(Quantity::from("20")),
949                    Some(Price::from("1.00020")),
950                    None,
951                    UUID4::new(),
952                    UnixNanos::default(),
953                    None,
954                    None,
955                ),
956            ],
957            UUID4::new(),
958            UnixNanos::default(),
959            None,
960            None,
961        );
962
963        client.batch_modify_orders(command).unwrap();
964
965        assert_eq!(modified_order_ids.borrow().as_slice(), &[order1, order2]);
966    }
967
968    #[rstest]
969    fn generate_mass_status_default_composes_granular_reports() {
970        let client = MassStatusExecutionClient::new(false);
971
972        let mass_status = futures::executor::block_on(client.generate_mass_status(Some(5)))
973            .unwrap()
974            .unwrap();
975
976        assert_eq!(mass_status.client_id, ClientId::from("MASS-STATUS"));
977        assert_eq!(mass_status.account_id, AccountId::from("MASS-STATUS-001"));
978        assert_eq!(mass_status.venue, Venue::from("SIM"));
979
980        let order_reports = mass_status.order_reports();
981        let fill_reports = mass_status.fill_reports();
982        let position_reports = mass_status.position_reports();
983        let order_report = order_reports.get(&VenueOrderId::from("ORDER-001")).unwrap();
984        let fill_report = &fill_reports.get(&VenueOrderId::from("ORDER-001")).unwrap()[0];
985        let position_report = &position_reports
986            .get(&InstrumentId::from("AUD/USD.SIM"))
987            .unwrap()[0];
988        assert_eq!(order_reports.len(), 1);
989        assert_eq!(fill_reports.len(), 1);
990        assert_eq!(position_reports.len(), 1);
991        assert_eq!(
992            order_report.instrument_id,
993            InstrumentId::from("AUD/USD.SIM")
994        );
995        assert_eq!(fill_report.trade_id, TradeId::from("TRADE-001"));
996        assert_eq!(
997            position_report.venue_position_id,
998            Some(PositionId::from("POSITION-001")),
999        );
1000
1001        let order_commands = client.order_commands.borrow();
1002        let fill_requests = client.fill_requests.borrow();
1003        let position_queries = client.position_queries.borrow();
1004        assert_eq!(order_commands.len(), 1);
1005        assert_eq!(fill_requests.len(), 1);
1006        assert_eq!(position_queries.len(), 1);
1007
1008        let order_cmd = &order_commands[0];
1009        let fill_cmd = &fill_requests[0];
1010        let position_cmd = &position_queries[0];
1011        assert_eq!(order_cmd.ts_init, mass_status.ts_init);
1012        assert_eq!(fill_cmd.ts_init, mass_status.ts_init);
1013        assert_eq!(position_cmd.ts_init, mass_status.ts_init);
1014        assert_ne!(test_order_report().ts_init, mass_status.ts_init);
1015        assert_ne!(test_fill_report().ts_init, mass_status.ts_init);
1016        assert_ne!(test_position_report().ts_init, mass_status.ts_init);
1017
1018        let expected_start = mass_status
1019            .ts_init
1020            .saturating_sub(DurationNanos::from_mins(5));
1021        assert_eq!(order_cmd.start, Some(expected_start));
1022        assert_eq!(fill_cmd.start, Some(expected_start));
1023        assert_eq!(position_cmd.start, Some(expected_start));
1024        assert!(!order_cmd.open_only);
1025        assert!(order_cmd.instrument_id.is_none());
1026        assert!(order_cmd.end.is_none());
1027        assert!(order_cmd.params.is_none());
1028        assert!(fill_cmd.instrument_id.is_none());
1029        assert!(fill_cmd.venue_order_id.is_none());
1030        assert!(fill_cmd.end.is_none());
1031        assert!(fill_cmd.params.is_none());
1032        assert!(position_cmd.instrument_id.is_none());
1033        assert!(position_cmd.end.is_none());
1034        assert!(position_cmd.params.is_none());
1035    }
1036
1037    #[rstest]
1038    fn generate_mass_status_uses_supplied_clock_for_all_sources() {
1039        let client = MassStatusExecutionClient::new(false);
1040        let timestamp = UnixNanos::from(900_000_000_123);
1041
1042        let report = futures::executor::block_on(generate_mass_status(&client, Some(3), timestamp))
1043            .unwrap()
1044            .unwrap();
1045
1046        let expected_start = Some(UnixNanos::from(720_000_000_123));
1047        assert_eq!(report.ts_init, timestamp);
1048        assert_eq!(client.order_commands.borrow()[0].ts_init, timestamp);
1049        assert_eq!(client.order_commands.borrow()[0].start, expected_start);
1050        assert_eq!(client.fill_requests.borrow()[0].ts_init, timestamp);
1051        assert_eq!(client.fill_requests.borrow()[0].start, expected_start);
1052        assert_eq!(client.position_queries.borrow()[0].ts_init, timestamp);
1053        assert_eq!(client.position_queries.borrow()[0].start, expected_start);
1054    }
1055
1056    #[rstest]
1057    fn generate_mass_status_default_propagates_granular_error() {
1058        let client = MassStatusExecutionClient::new(true);
1059
1060        let error = futures::executor::block_on(client.generate_mass_status(Some(5))).unwrap_err();
1061
1062        let error_chain = format!("{error:#}");
1063        assert!(error_chain.contains("failed to generate fill reports"));
1064        assert!(error_chain.contains("sentinel fill report failure"));
1065    }
1066}