Skip to main content

nautilus_execution/client/
mod.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 implementations for trading venue connectivity.
17
18use std::{
19    fmt::Debug,
20    ops::{Deref, DerefMut},
21};
22
23use nautilus_common::messages::execution::{
24    GenerateFillReports, GenerateOrderStatusReport, GenerateOrderStatusReports,
25    GeneratePositionStatusReports,
26};
27use nautilus_core::UnixNanos;
28use nautilus_model::{
29    enums::OmsType,
30    identifiers::{
31        AccountId, ClientId, ClientOrderId, InstrumentId, StrategyId, Venue, VenueOrderId,
32    },
33    instruments::InstrumentAny,
34    reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
35};
36
37pub mod core;
38
39use nautilus_common::clients::ExecutionClient;
40
41/// Wraps an [`ExecutionClient`], managing its lifecycle and providing access to the client.
42pub struct ExecutionClientAdapter {
43    pub(crate) client: Box<dyn ExecutionClient>,
44    pub client_id: ClientId,
45    pub venue: Venue,
46    pub account_id: AccountId,
47    pub oms_type: OmsType,
48}
49
50impl Deref for ExecutionClientAdapter {
51    type Target = Box<dyn ExecutionClient>;
52
53    fn deref(&self) -> &Self::Target {
54        &self.client
55    }
56}
57
58impl DerefMut for ExecutionClientAdapter {
59    fn deref_mut(&mut self) -> &mut Self::Target {
60        &mut self.client
61    }
62}
63
64impl Debug for ExecutionClientAdapter {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct(stringify!(ExecutionClientAdapter))
67            .field("client_id", &self.client_id)
68            .field("venue", &self.venue)
69            .field("account_id", &self.account_id)
70            .field("oms_type", &self.oms_type)
71            .finish()
72    }
73}
74
75impl ExecutionClientAdapter {
76    /// Creates a new [`ExecutionClientAdapter`] with the given client.
77    #[must_use]
78    pub fn new(client: Box<dyn ExecutionClient>) -> Self {
79        let client_id = client.client_id();
80        let venue = client.venue();
81        let account_id = client.account_id();
82        let oms_type = client.oms_type();
83
84        Self {
85            client,
86            client_id,
87            venue,
88            account_id,
89            oms_type,
90        }
91    }
92
93    /// Connects the execution client to the venue.
94    ///
95    /// # Errors
96    ///
97    /// Returns an error if connection fails.
98    pub async fn connect(&mut self) -> anyhow::Result<()> {
99        self.client.connect().await
100    }
101
102    /// Disconnects the execution client from the venue.
103    ///
104    /// # Errors
105    ///
106    /// Returns an error if disconnection fails.
107    pub async fn disconnect(&mut self) -> anyhow::Result<()> {
108        self.client.disconnect().await
109    }
110
111    /// Generates a single order status report.
112    ///
113    /// # Errors
114    ///
115    /// Returns an error if report generation fails.
116    pub async fn generate_order_status_report(
117        &self,
118        cmd: &GenerateOrderStatusReport,
119    ) -> anyhow::Result<Option<OrderStatusReport>> {
120        self.client.generate_order_status_report(cmd).await
121    }
122
123    /// Generates multiple order status reports.
124    ///
125    /// # Errors
126    ///
127    /// Returns an error if report generation fails.
128    pub async fn generate_order_status_reports(
129        &self,
130        cmd: &GenerateOrderStatusReports,
131    ) -> anyhow::Result<Vec<OrderStatusReport>> {
132        self.client.generate_order_status_reports(cmd).await
133    }
134
135    /// Generates fill reports based on execution results.
136    ///
137    /// # Errors
138    ///
139    /// Returns an error if fill report generation fails.
140    pub async fn generate_fill_reports(
141        &self,
142        cmd: GenerateFillReports,
143    ) -> anyhow::Result<Vec<FillReport>> {
144        self.client.generate_fill_reports(cmd).await
145    }
146
147    /// Generates position status reports.
148    ///
149    /// # Errors
150    ///
151    /// Returns an error if generation fails.
152    pub async fn generate_position_status_reports(
153        &self,
154        cmd: &GeneratePositionStatusReports,
155    ) -> anyhow::Result<Vec<PositionStatusReport>> {
156        self.client.generate_position_status_reports(cmd).await
157    }
158
159    /// Generates mass status for executions.
160    ///
161    /// # Errors
162    ///
163    /// Returns an error if status generation fails.
164    pub async fn generate_mass_status(
165        &self,
166        lookback_mins: Option<u64>,
167    ) -> anyhow::Result<Option<ExecutionMassStatus>> {
168        let mass_status = self.client.generate_mass_status(lookback_mins).await?;
169
170        if let Some(mass_status) = &mass_status {
171            anyhow::ensure!(
172                mass_status.client_id == self.client_id,
173                "Execution mass status client ID {} did not match source client {}",
174                mass_status.client_id,
175                self.client_id,
176            );
177            anyhow::ensure!(
178                mass_status.account_id == self.account_id,
179                "Execution mass status account ID {} did not match source account {}",
180                mass_status.account_id,
181                self.account_id,
182            );
183            anyhow::ensure!(
184                mass_status.venue == self.venue,
185                "Execution mass status venue {} did not match source venue {}",
186                mass_status.venue,
187                self.venue,
188            );
189        }
190
191        Ok(mass_status)
192    }
193
194    /// Forwards an instrument update to the underlying execution client.
195    pub fn on_instrument(&mut self, instrument: InstrumentAny) {
196        self.client.on_instrument(instrument);
197    }
198
199    /// Registers an external order for tracking by the execution client.
200    ///
201    /// This is called after reconciliation creates an external order, allowing the
202    /// execution client to track it for subsequent events (e.g., cancellations).
203    pub fn register_external_order(
204        &self,
205        client_order_id: ClientOrderId,
206        venue_order_id: VenueOrderId,
207        instrument_id: InstrumentId,
208        strategy_id: StrategyId,
209        ts_init: UnixNanos,
210    ) {
211        self.client.register_external_order(
212            client_order_id,
213            venue_order_id,
214            instrument_id,
215            strategy_id,
216            ts_init,
217        );
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use std::{cell::RefCell, rc::Rc};
224
225    use async_trait::async_trait;
226    use futures::future::FutureExt;
227    use nautilus_common::clients::ExecutionClient;
228    use nautilus_core::{Params, UnixNanos};
229    use nautilus_model::{
230        accounts::AccountAny,
231        enums::OmsType,
232        identifiers::{AccountId, ClientId, Venue},
233        reports::ExecutionMassStatus,
234        types::{AccountBalance, MarginBalance},
235    };
236    use rstest::rstest;
237
238    use super::ExecutionClientAdapter;
239    use crate::engine::stubs::StubExecutionClient;
240
241    struct MassStatusClient {
242        stub: StubExecutionClient,
243        mass_status: ExecutionMassStatus,
244        lookbacks: Rc<RefCell<Vec<Option<u64>>>>,
245    }
246
247    impl MassStatusClient {
248        fn new(mass_status: ExecutionMassStatus, lookbacks: Rc<RefCell<Vec<Option<u64>>>>) -> Self {
249            let stub = StubExecutionClient::new(
250                ClientId::from("SIM"),
251                AccountId::from("SIM-001"),
252                Venue::from("SIM"),
253                OmsType::Netting,
254                None,
255            );
256
257            Self {
258                stub,
259                mass_status,
260                lookbacks,
261            }
262        }
263    }
264
265    #[async_trait(?Send)]
266    impl ExecutionClient for MassStatusClient {
267        fn is_connected(&self) -> bool {
268            self.stub.is_connected()
269        }
270
271        fn client_id(&self) -> ClientId {
272            self.stub.client_id()
273        }
274
275        fn account_id(&self) -> AccountId {
276            self.stub.account_id()
277        }
278
279        fn venue(&self) -> Venue {
280            self.stub.venue()
281        }
282
283        fn oms_type(&self) -> OmsType {
284            self.stub.oms_type()
285        }
286
287        fn get_account(&self) -> Option<AccountAny> {
288            self.stub.get_account()
289        }
290
291        fn generate_account_state(
292            &self,
293            balances: Vec<AccountBalance>,
294            margins: Vec<MarginBalance>,
295            reported: bool,
296            ts_event: UnixNanos,
297            info: Option<Params>,
298        ) -> anyhow::Result<()> {
299            self.stub
300                .generate_account_state(balances, margins, reported, ts_event, info)
301        }
302
303        fn start(&mut self) -> anyhow::Result<()> {
304            self.stub.start()
305        }
306
307        fn stop(&mut self) -> anyhow::Result<()> {
308            self.stub.stop()
309        }
310
311        async fn generate_mass_status(
312            &self,
313            lookback_mins: Option<u64>,
314        ) -> anyhow::Result<Option<ExecutionMassStatus>> {
315            self.lookbacks.borrow_mut().push(lookback_mins);
316
317            Ok(Some(self.mass_status.clone()))
318        }
319    }
320
321    #[rstest]
322    #[case::matching_identity("SIM", "SIM-001", "SIM", None)]
323    #[case::mismatched_client_id(
324        "OTHER",
325        "SIM-001",
326        "SIM",
327        Some("Execution mass status client ID OTHER did not match source client SIM")
328    )]
329    #[case::mismatched_account_id(
330        "SIM",
331        "OTHER-001",
332        "SIM",
333        Some("Execution mass status account ID OTHER-001 did not match source account SIM-001")
334    )]
335    #[case::mismatched_venue(
336        "SIM",
337        "SIM-001",
338        "OTHER",
339        Some("Execution mass status venue OTHER did not match source venue SIM")
340    )]
341    fn test_generate_mass_status_validates_identity_and_forwards_lookback(
342        #[case] report_client_id: &str,
343        #[case] report_account_id: &str,
344        #[case] report_venue: &str,
345        #[case] expected_error: Option<&str>,
346    ) {
347        let mass_status = ExecutionMassStatus::new(
348            ClientId::from(report_client_id),
349            AccountId::from(report_account_id),
350            Venue::from(report_venue),
351            UnixNanos::from(42),
352            None,
353        );
354
355        let lookbacks = Rc::new(RefCell::new(Vec::new()));
356        let client = MassStatusClient::new(mass_status.clone(), Rc::clone(&lookbacks));
357        let adapter = ExecutionClientAdapter::new(Box::new(client));
358
359        let result = adapter
360            .generate_mass_status(Some(23))
361            .now_or_never()
362            .expect("mass status stub should complete immediately");
363
364        if let Some(expected_error) = expected_error {
365            assert_eq!(result.unwrap_err().to_string(), expected_error);
366        } else {
367            assert_eq!(result.unwrap(), Some(mass_status));
368        }
369
370        assert_eq!(lookbacks.borrow().as_slice(), &[Some(23)]);
371    }
372}