Skip to main content

nautilus_live/python/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//! Connects custom Python adapters to the Rust live node through PyO3.
17//!
18//! Implements the Rust data and execution client traits by forwarding operations to Python
19//! clients, and manages factory construction, event-loop binding, and client lifetimes. Adapters
20//! receive a read-only cache view and submit typed output to the live runner for processing
21//! inside the synchronous core boundary.
22
23pub mod requests;
24pub mod responses;
25
26use std::{
27    any::Any,
28    cell::RefCell,
29    collections::HashMap,
30    rc::Rc,
31    sync::{
32        Arc,
33        atomic::{AtomicU64, Ordering},
34    },
35    thread::{self, ThreadId},
36};
37
38use async_trait::async_trait;
39use nautilus_common::{
40    cache::{Cache, CacheView},
41    clients::{
42        DEFAULT_POSITION_RECONCILIATION_TOLERANCE, DataClient, ExecutionClient,
43        generate_mass_status,
44    },
45    clock::Clock,
46    factories::{ClientConfig, DataClientFactory, ExecutionClientFactory, OrderEventFactory},
47    live::{
48        runner::{get_data_event_sender, get_exec_event_sender},
49        sender::EventSender,
50    },
51    messages::{
52        DataEvent, ExecutionEvent, ExecutionReport,
53        data::{
54            DataRequestFailed, DataResponseEnvelope, RequestBars, RequestBookDeltas,
55            RequestBookDepth, RequestBookSnapshot, RequestCustomData, RequestFundingRates,
56            RequestInstrument, RequestInstruments, RequestOptionChainReferencePrice, RequestQuotes,
57            RequestTrades, SubscribeBars, SubscribeBookDeltas, SubscribeBookDepth,
58            SubscribeCustomData, SubscribeFundingRates, SubscribeIndexPrices, SubscribeInstrument,
59            SubscribeInstrumentClose, SubscribeInstrumentStatus, SubscribeInstruments,
60            SubscribeMarkPrices, SubscribeOptionGreeks, SubscribeQuotes, SubscribeTrades,
61            UnsubscribeBars, UnsubscribeBookDeltas, UnsubscribeBookDepth, UnsubscribeCustomData,
62            UnsubscribeFundingRates, UnsubscribeIndexPrices, UnsubscribeInstrument,
63            UnsubscribeInstrumentClose, UnsubscribeInstrumentStatus, UnsubscribeInstruments,
64            UnsubscribeMarkPrices, UnsubscribeOptionGreeks, UnsubscribeQuotes, UnsubscribeTrades,
65        },
66        execution::{
67            BatchCancelOrders, BatchModifyOrders, CancelAllOrders, CancelOrder,
68            GenerateFillReports, GenerateOrderStatusReport, GenerateOrderStatusReports,
69            GeneratePositionStatusReports, ModifyOrder, QueryAccount, QueryOrder, SubmitOrder,
70            SubmitOrderList,
71        },
72    },
73    python::clock::PyClock,
74};
75use nautilus_core::{
76    Params, UUID4, UnixNanos,
77    python::{params::pydict_to_params, to_pyruntime_err, to_pytype_err},
78};
79use nautilus_model::{
80    accounts::AccountAny,
81    data::{
82        Bar, CustomData, Data, FundingRateUpdate, IndexPriceUpdate, InstrumentClose,
83        InstrumentStatus, MarkPriceUpdate, OptionGreeks, OrderBookDelta, OrderBookDeltas,
84        OrderBookDepth, QuoteTick, TradeTick,
85    },
86    enums::{AccountType, LiquiditySide, OmsType, OrderSide, PositionSide},
87    events::{
88        AccountState, OrderAccepted, OrderAcceptedBatch, OrderCanceled, OrderCanceledBatch,
89        OrderSubmitted, OrderSubmittedBatch,
90    },
91    identifiers::{
92        AccountId, ClientId, ClientOrderId, InstrumentId, OrderListId, PositionId, StrategyId,
93        TradeId, TraderId, Venue, VenueOrderId,
94    },
95    instruments::InstrumentAny,
96    orderbook::OrderBook,
97    orders::OrderList,
98    position::Position,
99    python::{
100        account::account_any_to_pyobject,
101        events::order::pyobject_to_order_event,
102        instruments::{instrument_any_to_pyobject, pyobject_to_instrument_any},
103        orders::{order_any_to_pyobject, pyobject_to_order_any},
104    },
105    reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
106    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
107};
108use parking_lot::Mutex;
109use pyo3::{
110    prelude::*,
111    types::{PyCFunction, PyDict, PyTuple},
112};
113use rust_decimal::Decimal;
114
115use self::{
116    requests::{
117        PyRequestBars, PyRequestBookDeltas, PyRequestBookDepth, PyRequestBookSnapshot,
118        PyRequestCustomData, PyRequestFundingRates, PyRequestInstrument, PyRequestInstruments,
119        PyRequestOptionChainReferencePrice, PyRequestQuotes, PyRequestTrades,
120    },
121    responses::extract_response,
122};
123use super::runtime::PythonOperation;
124
125static CACHE_ID: AtomicU64 = AtomicU64::new(1);
126
127thread_local! {
128    static CLIENT_CACHES: RefCell<HashMap<u64, CacheView>> = RefCell::new(HashMap::new());
129}
130
131/// Read-only access to the owning node's cache.
132#[pyclass(name = "ClientCache", module = "nautilus_trader.live", frozen)]
133#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")]
134#[derive(Debug)]
135pub struct PyClientCache {
136    id: u64,
137}
138
139#[pymethods]
140#[pyo3_stub_gen::derive::gen_stub_pymethods]
141impl PyClientCache {
142    #[pyo3(name = "instrument")]
143    fn py_instrument(
144        &self,
145        py: Python<'_>,
146        instrument_id: InstrumentId,
147    ) -> PyResult<Option<Py<PyAny>>> {
148        let view = self.view()?;
149        let instrument = view
150            .try_borrow()
151            .map_err(to_pyruntime_err)?
152            .instrument(&instrument_id)
153            .cloned();
154        instrument
155            .map(|instrument| instrument_any_to_pyobject(py, instrument))
156            .transpose()
157    }
158
159    #[pyo3(name = "quote", signature = (instrument_id, index=0))]
160    fn py_quote(&self, instrument_id: InstrumentId, index: usize) -> PyResult<Option<QuoteTick>> {
161        let view = self.view()?;
162        Ok(view
163            .try_borrow()
164            .map_err(to_pyruntime_err)?
165            .quote_at_index(&instrument_id, index)
166            .copied())
167    }
168    #[pyo3(name = "get")]
169    fn py_get(&self, key: &str) -> PyResult<Option<Vec<u8>>> {
170        self.read(|cache| {
171            cache
172                .get(key)
173                .map(|value| value.map(|bytes| bytes.to_vec()))
174        })?
175        .map_err(to_pyruntime_err)
176    }
177
178    #[pyo3(name = "instruments", signature = (venue=None))]
179    fn py_instruments(&self, py: Python<'_>, venue: Option<Venue>) -> PyResult<Vec<Py<PyAny>>> {
180        let instruments = self.read(|cache| {
181            cache
182                .instrument_ids(venue.as_ref())
183                .into_iter()
184                .filter_map(|id| cache.instrument(id).cloned())
185                .collect::<Vec<_>>()
186        })?;
187
188        instruments
189            .into_iter()
190            .map(|instrument| instrument_any_to_pyobject(py, instrument))
191            .collect()
192    }
193
194    #[pyo3(name = "instrument_ids", signature = (venue=None))]
195    fn py_instrument_ids(&self, venue: Option<Venue>) -> PyResult<Vec<InstrumentId>> {
196        self.read(|cache| {
197            cache
198                .instrument_ids(venue.as_ref())
199                .into_iter()
200                .copied()
201                .collect()
202        })
203    }
204
205    #[pyo3(name = "account")]
206    fn py_account(&self, py: Python<'_>, account_id: AccountId) -> PyResult<Option<Py<PyAny>>> {
207        self.read(|cache| cache.account_owned(&account_id))?
208            .map(|account| account_any_to_pyobject(py, account))
209            .transpose()
210    }
211
212    #[pyo3(name = "order")]
213    fn py_order(
214        &self,
215        py: Python<'_>,
216        client_order_id: ClientOrderId,
217    ) -> PyResult<Option<Py<PyAny>>> {
218        self.read(|cache| cache.order_owned(&client_order_id))?
219            .map(|order| order_any_to_pyobject(py, order))
220            .transpose()
221    }
222
223    #[pyo3(name = "client_order_id")]
224    fn py_client_order_id(&self, venue_order_id: VenueOrderId) -> PyResult<Option<ClientOrderId>> {
225        self.read(|cache| cache.client_order_id(&venue_order_id).copied())
226    }
227
228    #[pyo3(name = "venue_order_id")]
229    fn py_venue_order_id(&self, client_order_id: ClientOrderId) -> PyResult<Option<VenueOrderId>> {
230        self.read(|cache| cache.venue_order_id(&client_order_id).copied())
231    }
232
233    #[pyo3(name = "position_id")]
234    fn py_position_id(&self, client_order_id: ClientOrderId) -> PyResult<Option<PositionId>> {
235        self.read(|cache| cache.position_id(&client_order_id).copied())
236    }
237
238    #[pyo3(name = "strategy_id_for_order")]
239    fn py_strategy_id_for_order(
240        &self,
241        client_order_id: ClientOrderId,
242    ) -> PyResult<Option<StrategyId>> {
243        self.read(|cache| cache.strategy_id_for_order(&client_order_id).copied())
244    }
245
246    #[pyo3(name = "order_list")]
247    fn py_order_list(&self, order_list_id: OrderListId) -> PyResult<Option<OrderList>> {
248        self.read(|cache| cache.order_list(&order_list_id).cloned())
249    }
250
251    #[pyo3(name = "order_book")]
252    fn py_order_book(&self, instrument_id: InstrumentId) -> PyResult<Option<OrderBook>> {
253        self.read(|cache| cache.order_book(&instrument_id).cloned())
254    }
255
256    #[pyo3(name = "position")]
257    fn py_position(&self, position_id: PositionId) -> PyResult<Option<Position>> {
258        self.read(|cache| cache.position_owned(&position_id))
259    }
260
261    #[pyo3(name = "orders", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
262    fn py_orders(
263        &self,
264        py: Python<'_>,
265        venue: Option<Venue>,
266        instrument_id: Option<InstrumentId>,
267        strategy_id: Option<StrategyId>,
268        account_id: Option<AccountId>,
269        side: Option<OrderSide>,
270    ) -> PyResult<Vec<Py<PyAny>>> {
271        let orders = self.read(|cache| {
272            cache
273                .orders(
274                    venue.as_ref(),
275                    instrument_id.as_ref(),
276                    strategy_id.as_ref(),
277                    account_id.as_ref(),
278                    side,
279                )
280                .into_iter()
281                .map(|value| value.clone())
282                .collect::<Vec<_>>()
283        })?;
284
285        orders
286            .into_iter()
287            .map(|order| order_any_to_pyobject(py, order))
288            .collect()
289    }
290
291    #[pyo3(name = "orders_open", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
292    fn py_orders_open(
293        &self,
294        py: Python<'_>,
295        venue: Option<Venue>,
296        instrument_id: Option<InstrumentId>,
297        strategy_id: Option<StrategyId>,
298        account_id: Option<AccountId>,
299        side: Option<OrderSide>,
300    ) -> PyResult<Vec<Py<PyAny>>> {
301        let orders = self.read(|cache| {
302            cache
303                .orders_open(
304                    venue.as_ref(),
305                    instrument_id.as_ref(),
306                    strategy_id.as_ref(),
307                    account_id.as_ref(),
308                    side,
309                )
310                .into_iter()
311                .map(|value| value.clone())
312                .collect::<Vec<_>>()
313        })?;
314
315        orders
316            .into_iter()
317            .map(|order| order_any_to_pyobject(py, order))
318            .collect()
319    }
320
321    #[pyo3(name = "orders_inflight", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
322    fn py_orders_inflight(
323        &self,
324        py: Python<'_>,
325        venue: Option<Venue>,
326        instrument_id: Option<InstrumentId>,
327        strategy_id: Option<StrategyId>,
328        account_id: Option<AccountId>,
329        side: Option<OrderSide>,
330    ) -> PyResult<Vec<Py<PyAny>>> {
331        let orders = self.read(|cache| {
332            cache
333                .orders_inflight(
334                    venue.as_ref(),
335                    instrument_id.as_ref(),
336                    strategy_id.as_ref(),
337                    account_id.as_ref(),
338                    side,
339                )
340                .into_iter()
341                .map(|value| value.clone())
342                .collect::<Vec<_>>()
343        })?;
344
345        orders
346            .into_iter()
347            .map(|order| order_any_to_pyobject(py, order))
348            .collect()
349    }
350
351    #[pyo3(name = "orders_open_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
352    fn py_orders_open_count(
353        &self,
354        venue: Option<Venue>,
355        instrument_id: Option<InstrumentId>,
356        strategy_id: Option<StrategyId>,
357        account_id: Option<AccountId>,
358        side: Option<OrderSide>,
359    ) -> PyResult<usize> {
360        self.read(|cache| {
361            cache.orders_open_count(
362                venue.as_ref(),
363                instrument_id.as_ref(),
364                strategy_id.as_ref(),
365                account_id.as_ref(),
366                side,
367            )
368        })
369    }
370
371    #[pyo3(name = "client_order_ids_open", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
372    fn py_client_order_ids_open(
373        &self,
374        venue: Option<Venue>,
375        instrument_id: Option<InstrumentId>,
376        strategy_id: Option<StrategyId>,
377        account_id: Option<AccountId>,
378    ) -> PyResult<Vec<ClientOrderId>> {
379        self.read(|cache| {
380            cache
381                .client_order_ids_open(
382                    venue.as_ref(),
383                    instrument_id.as_ref(),
384                    strategy_id.as_ref(),
385                    account_id.as_ref(),
386                )
387                .into_iter()
388                .collect()
389        })
390    }
391
392    #[pyo3(name = "positions_open", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
393    fn py_positions_open(
394        &self,
395        venue: Option<Venue>,
396        instrument_id: Option<InstrumentId>,
397        strategy_id: Option<StrategyId>,
398        account_id: Option<AccountId>,
399        side: Option<PositionSide>,
400    ) -> PyResult<Vec<Position>> {
401        self.read(|cache| {
402            cache
403                .positions_open(
404                    venue.as_ref(),
405                    instrument_id.as_ref(),
406                    strategy_id.as_ref(),
407                    account_id.as_ref(),
408                    side,
409                )
410                .into_iter()
411                .map(|value| value.clone())
412                .collect()
413        })
414    }
415}
416
417impl PyClientCache {
418    fn read<T>(&self, read: impl FnOnce(&Cache) -> T) -> PyResult<T> {
419        let view = self.view()?;
420        let cache = view.try_borrow().map_err(to_pyruntime_err)?;
421        Ok(read(&cache))
422    }
423
424    fn view(&self) -> PyResult<CacheView> {
425        CLIENT_CACHES
426            .with_borrow(|caches| caches.get(&self.id).cloned())
427            .ok_or_else(|| {
428                to_pyruntime_err("Client cache is disposed or accessed from a foreign thread")
429            })
430    }
431}
432
433/// Queues typed client output on its owner thread.
434#[pyclass(
435    name = "_ClientOutput",
436    module = "nautilus_trader.live",
437    frozen,
438    from_py_object
439)]
440#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")]
441#[derive(Debug, Clone)]
442pub struct ClientOutput {
443    state: Arc<Mutex<OutputState>>,
444    owner: ThreadId,
445}
446
447#[derive(Debug, Default)]
448struct OutputState {
449    sender: Option<EventSender<DataEvent>>,
450    bound: bool,
451    disposed: bool,
452    claimed: bool,
453    client_id: Option<ClientId>,
454    exec_sender: Option<EventSender<ExecutionEvent>>,
455    event_factory: Option<OrderEventFactory>,
456    venue: Option<Venue>,
457}
458
459#[pymethods]
460#[pyo3_stub_gen::derive::gen_stub_pymethods]
461impl ClientOutput {
462    #[new]
463    fn py_new() -> Self {
464        Self {
465            state: Arc::default(),
466            owner: thread::current().id(),
467        }
468    }
469
470    #[pyo3(name = "instrument")]
471    fn py_instrument(&self, py: Python<'_>, instrument: Py<PyAny>) -> PyResult<()> {
472        self.sender()?;
473        self.send(DataEvent::Data(
474            pyobject_to_instrument_any(py, instrument)?.into(),
475        ))
476    }
477
478    #[pyo3(name = "data")]
479    fn py_data(&self, data: &Bound<'_, PyAny>) -> PyResult<()> {
480        self.sender()?;
481        self.send(DataEvent::Data(extract_data(data)?))
482    }
483
484    #[pyo3(name = "response", signature = (response, completed=None, sub_correlation_id=None))]
485    fn py_response(
486        &self,
487        response: &Bound<'_, PyAny>,
488        completed: Option<bool>,
489        sub_correlation_id: Option<nautilus_core::UUID4>,
490    ) -> PyResult<()> {
491        self.sender()?;
492        let (client_id, response) = extract_response(response)?;
493        if self.state.lock().client_id != Some(client_id) {
494            return Err(to_pytype_err(
495                "Response client identity does not match its owner",
496            ));
497        }
498
499        let envelope =
500            DataResponseEnvelope::new(response, completed.unwrap_or(true), sub_correlation_id);
501        self.send(DataEvent::ResponseEnvelope(envelope))
502    }
503
504    /// Completes a failed data request, preserving an optional partial response.
505    #[pyo3(name = "request_failed", signature = (request_id, reason, response=None))]
506    fn py_request_failed(
507        &self,
508        request_id: nautilus_core::UUID4,
509        reason: String,
510        response: Option<&Bound<'_, PyAny>>,
511    ) -> PyResult<()> {
512        self.sender()?;
513        let response = response.map(extract_response).transpose()?;
514        if let Some((client_id, response)) = &response
515            && (self.state.lock().client_id != Some(*client_id)
516                || response.correlation_id() != &request_id)
517        {
518            return Err(to_pytype_err(
519                "Partial response identity does not match the failed request",
520            ));
521        }
522
523        self.send(DataEvent::RequestFailed(DataRequestFailed {
524            request_id,
525            reason,
526            response: response.map(|(_, response)| response),
527        }))
528    }
529
530    #[pyo3(name = "event")]
531    fn py_event(&self, py: Python<'_>, event: Py<PyAny>) -> PyResult<()> {
532        self.exec_sender()?;
533
534        let event = if event.bind(py).is_instance_of::<AccountState>() {
535            ExecutionEvent::Account(event.extract(py)?)
536        } else {
537            ExecutionEvent::Order(pyobject_to_order_event(py, event)?)
538        };
539
540        self.send_exec(event)
541    }
542
543    #[pyo3(name = "report", signature = (report, fills=None))]
544    fn py_report(&self, report: &Bound<'_, PyAny>, fills: Option<Vec<FillReport>>) -> PyResult<()> {
545        self.exec_sender()?;
546
547        let report = if report.is_instance_of::<OrderStatusReport>() {
548            let order = Box::new(report.extract()?);
549
550            match fills {
551                Some(fills) => ExecutionReport::OrderWithFills(order, fills),
552                None => ExecutionReport::Order(order),
553            }
554        } else if fills.is_some() {
555            return Err(to_pytype_err(
556                "Associated fills require an OrderStatusReport",
557            ));
558        } else if report.is_instance_of::<FillReport>() {
559            ExecutionReport::Fill(Box::new(report.extract()?))
560        } else if report.is_instance_of::<PositionStatusReport>() {
561            ExecutionReport::Position(Box::new(report.extract()?))
562        } else if report.is_instance_of::<ExecutionMassStatus>() {
563            ExecutionReport::MassStatus(Box::new(report.extract()?))
564        } else {
565            return Err(to_pytype_err(
566                "Expected a Nautilus execution report from the installed wheel",
567            ));
568        };
569
570        self.send_exec(ExecutionEvent::Report(report))
571    }
572
573    #[pyo3(name = "account_state", signature = (balances, margins, reported, ts_event, ts_init, info=None))]
574    #[expect(
575        clippy::too_many_arguments,
576        clippy::needless_pass_by_value,
577        reason = "typed event fields cross the PyO3 boundary together"
578    )]
579    fn py_account_state(
580        &self,
581        py: Python<'_>,
582        balances: Vec<AccountBalance>,
583        margins: Vec<MarginBalance>,
584        reported: bool,
585        ts_event: u64,
586        ts_init: u64,
587        info: Option<Py<PyDict>>,
588    ) -> PyResult<()> {
589        let factory = self.event_factory()?;
590        let info = info
591            .as_ref()
592            .map(|info| pydict_to_params(py, info))
593            .transpose()?
594            .flatten();
595        let state = factory.generate_account_state(
596            balances,
597            margins,
598            reported,
599            ts_event.into(),
600            ts_init.into(),
601            info,
602        );
603        self.send_exec(ExecutionEvent::Account(state))
604    }
605
606    #[pyo3(name = "order_submitted_batch")]
607    fn py_order_submitted_batch(&self, events: Vec<OrderSubmitted>) -> PyResult<()> {
608        self.send_exec(ExecutionEvent::OrderSubmittedBatch(
609            OrderSubmittedBatch::new(events),
610        ))
611    }
612
613    #[pyo3(name = "order_accepted_batch")]
614    fn py_order_accepted_batch(&self, events: Vec<OrderAccepted>) -> PyResult<()> {
615        self.send_exec(ExecutionEvent::OrderAcceptedBatch(OrderAcceptedBatch::new(
616            events,
617        )))
618    }
619
620    #[pyo3(name = "order_canceled_batch")]
621    fn py_order_canceled_batch(&self, events: Vec<OrderCanceled>) -> PyResult<()> {
622        self.send_exec(ExecutionEvent::OrderCanceledBatch(OrderCanceledBatch::new(
623            events,
624        )))
625    }
626
627    #[pyo3(name = "order_denied", signature = (order, reason, ts_init))]
628    fn py_order_denied(
629        &self,
630        py: Python<'_>,
631        order: Py<PyAny>,
632        reason: &str,
633        ts_init: u64,
634    ) -> PyResult<()> {
635        let factory = self.event_factory()?;
636        let order = pyobject_to_order_any(py, order)?;
637        let event = factory.generate_order_denied(&order, reason, ts_init.into());
638        self.send_exec(ExecutionEvent::Order(event))
639    }
640
641    #[pyo3(name = "order_submitted", signature = (order, ts_init))]
642    fn py_order_submitted(&self, py: Python<'_>, order: Py<PyAny>, ts_init: u64) -> PyResult<()> {
643        let factory = self.event_factory()?;
644        let order = pyobject_to_order_any(py, order)?;
645        let event = factory.generate_order_submitted(&order, ts_init.into());
646        self.send_exec(ExecutionEvent::Order(event))
647    }
648
649    #[pyo3(name = "order_rejected", signature = (order, reason, ts_event, ts_init, due_post_only))]
650    fn py_order_rejected(
651        &self,
652        py: Python<'_>,
653        order: Py<PyAny>,
654        reason: &str,
655        ts_event: u64,
656        ts_init: u64,
657        due_post_only: bool,
658    ) -> PyResult<()> {
659        let factory = self.event_factory()?;
660        let order = pyobject_to_order_any(py, order)?;
661        let event = factory.generate_order_rejected(
662            &order,
663            reason,
664            ts_event.into(),
665            ts_init.into(),
666            due_post_only,
667        );
668        self.send_exec(ExecutionEvent::Order(event))
669    }
670
671    #[pyo3(name = "order_accepted", signature = (order, venue_order_id, ts_event, ts_init))]
672    fn py_order_accepted(
673        &self,
674        py: Python<'_>,
675        order: Py<PyAny>,
676        venue_order_id: VenueOrderId,
677        ts_event: u64,
678        ts_init: u64,
679    ) -> PyResult<()> {
680        let factory = self.event_factory()?;
681        let order = pyobject_to_order_any(py, order)?;
682        let event = factory.generate_order_accepted(
683            &order,
684            venue_order_id,
685            ts_event.into(),
686            ts_init.into(),
687        );
688        self.send_exec(ExecutionEvent::Order(event))
689    }
690
691    #[pyo3(name = "order_modify_denied", signature = (order, reason, ts_event, ts_init, causation_id=None))]
692    fn py_order_modify_denied(
693        &self,
694        py: Python<'_>,
695        order: Py<PyAny>,
696        reason: &str,
697        ts_event: u64,
698        ts_init: u64,
699        causation_id: Option<UUID4>,
700    ) -> PyResult<()> {
701        let factory = self.event_factory()?;
702        let order = pyobject_to_order_any(py, order)?;
703        let event = factory.generate_order_modify_denied(
704            &order,
705            reason,
706            causation_id,
707            ts_event.into(),
708            ts_init.into(),
709        );
710        self.send_exec(ExecutionEvent::Order(event))
711    }
712
713    #[pyo3(name = "order_modify_rejected", signature = (order, venue_order_id, reason, ts_event, ts_init, causation_id=None))]
714    #[expect(
715        clippy::too_many_arguments,
716        reason = "Python event emission retains its optional command correlation"
717    )]
718    fn py_order_modify_rejected(
719        &self,
720        py: Python<'_>,
721        order: Py<PyAny>,
722        venue_order_id: Option<VenueOrderId>,
723        reason: &str,
724        ts_event: u64,
725        ts_init: u64,
726        causation_id: Option<UUID4>,
727    ) -> PyResult<()> {
728        let factory = self.event_factory()?;
729        let order = pyobject_to_order_any(py, order)?;
730        let event = factory.generate_order_modify_rejected(
731            &order,
732            venue_order_id,
733            reason,
734            ts_event.into(),
735            ts_init.into(),
736            causation_id,
737        );
738        self.send_exec(ExecutionEvent::Order(event))
739    }
740
741    #[pyo3(name = "order_cancel_denied", signature = (order, reason, ts_event, ts_init, causation_id=None))]
742    fn py_order_cancel_denied(
743        &self,
744        py: Python<'_>,
745        order: Py<PyAny>,
746        reason: &str,
747        ts_event: u64,
748        ts_init: u64,
749        causation_id: Option<UUID4>,
750    ) -> PyResult<()> {
751        let factory = self.event_factory()?;
752        let order = pyobject_to_order_any(py, order)?;
753        let event = factory.generate_order_cancel_denied(
754            &order,
755            reason,
756            causation_id,
757            ts_event.into(),
758            ts_init.into(),
759        );
760        self.send_exec(ExecutionEvent::Order(event))
761    }
762
763    #[pyo3(name = "order_cancel_rejected", signature = (order, venue_order_id, reason, ts_event, ts_init, causation_id=None))]
764    #[expect(
765        clippy::too_many_arguments,
766        reason = "Python event emission retains its optional command correlation"
767    )]
768    fn py_order_cancel_rejected(
769        &self,
770        py: Python<'_>,
771        order: Py<PyAny>,
772        venue_order_id: Option<VenueOrderId>,
773        reason: &str,
774        ts_event: u64,
775        ts_init: u64,
776        causation_id: Option<UUID4>,
777    ) -> PyResult<()> {
778        let factory = self.event_factory()?;
779        let order = pyobject_to_order_any(py, order)?;
780        let event = factory.generate_order_cancel_rejected(
781            &order,
782            venue_order_id,
783            reason,
784            ts_event.into(),
785            ts_init.into(),
786            causation_id,
787        );
788        self.send_exec(ExecutionEvent::Order(event))
789    }
790
791    #[pyo3(name = "order_updated", signature = (order, venue_order_id, quantity, price, trigger_price, protection_price, ts_event, ts_init))]
792    #[expect(
793        clippy::too_many_arguments,
794        reason = "typed event fields cross the PyO3 boundary together"
795    )]
796    fn py_order_updated(
797        &self,
798        py: Python<'_>,
799        order: Py<PyAny>,
800        venue_order_id: VenueOrderId,
801        quantity: Quantity,
802        price: Option<Price>,
803        trigger_price: Option<Price>,
804        protection_price: Option<Price>,
805        ts_event: u64,
806        ts_init: u64,
807    ) -> PyResult<()> {
808        let factory = self.event_factory()?;
809        let order = pyobject_to_order_any(py, order)?;
810        let event = factory.generate_order_updated(
811            &order,
812            venue_order_id,
813            quantity,
814            price,
815            trigger_price,
816            protection_price,
817            ts_event.into(),
818            ts_init.into(),
819        );
820        self.send_exec(ExecutionEvent::Order(event))
821    }
822
823    #[pyo3(name = "order_canceled", signature = (order, venue_order_id, ts_event, ts_init))]
824    fn py_order_canceled(
825        &self,
826        py: Python<'_>,
827        order: Py<PyAny>,
828        venue_order_id: Option<VenueOrderId>,
829        ts_event: u64,
830        ts_init: u64,
831    ) -> PyResult<()> {
832        let factory = self.event_factory()?;
833        let order = pyobject_to_order_any(py, order)?;
834        let event = factory.generate_order_canceled(
835            &order,
836            venue_order_id,
837            ts_event.into(),
838            ts_init.into(),
839        );
840        self.send_exec(ExecutionEvent::Order(event))
841    }
842
843    #[pyo3(name = "order_triggered", signature = (order, venue_order_id, ts_event, ts_init))]
844    fn py_order_triggered(
845        &self,
846        py: Python<'_>,
847        order: Py<PyAny>,
848        venue_order_id: Option<VenueOrderId>,
849        ts_event: u64,
850        ts_init: u64,
851    ) -> PyResult<()> {
852        let factory = self.event_factory()?;
853        let order = pyobject_to_order_any(py, order)?;
854        let event = factory.generate_order_triggered(
855            &order,
856            venue_order_id,
857            ts_event.into(),
858            ts_init.into(),
859        );
860        self.send_exec(ExecutionEvent::Order(event))
861    }
862
863    #[pyo3(name = "order_expired", signature = (order, venue_order_id, ts_event, ts_init))]
864    fn py_order_expired(
865        &self,
866        py: Python<'_>,
867        order: Py<PyAny>,
868        venue_order_id: Option<VenueOrderId>,
869        ts_event: u64,
870        ts_init: u64,
871    ) -> PyResult<()> {
872        let factory = self.event_factory()?;
873        let order = pyobject_to_order_any(py, order)?;
874        let event =
875            factory.generate_order_expired(&order, venue_order_id, ts_event.into(), ts_init.into());
876        self.send_exec(ExecutionEvent::Order(event))
877    }
878
879    #[pyo3(name = "order_filled", signature = (order, venue_order_id, venue_position_id, trade_id, last_qty, last_px, quote_currency, commission, liquidity_side, ts_event, ts_init))]
880    #[expect(
881        clippy::too_many_arguments,
882        reason = "typed event fields cross the PyO3 boundary together"
883    )]
884    fn py_order_filled(
885        &self,
886        py: Python<'_>,
887        order: Py<PyAny>,
888        venue_order_id: VenueOrderId,
889        venue_position_id: Option<PositionId>,
890        trade_id: TradeId,
891        last_qty: Quantity,
892        last_px: Price,
893        quote_currency: Currency,
894        commission: Option<Money>,
895        liquidity_side: LiquiditySide,
896        ts_event: u64,
897        ts_init: u64,
898    ) -> PyResult<()> {
899        let factory = self.event_factory()?;
900        let order = pyobject_to_order_any(py, order)?;
901        let event = factory.generate_order_filled(
902            &order,
903            venue_order_id,
904            venue_position_id,
905            trade_id,
906            last_qty,
907            last_px,
908            quote_currency,
909            commission,
910            liquidity_side,
911            ts_event.into(),
912            ts_init.into(),
913        );
914        self.send_exec(ExecutionEvent::Order(event))
915    }
916}
917
918impl ClientOutput {
919    fn bind(&self) -> PyResult<()> {
920        if thread::current().id() != self.owner {
921            return Err(to_pyruntime_err("Client output requires its owner thread"));
922        }
923
924        let mut state = self.state.lock();
925        if state.bound || state.disposed {
926            return Err(to_pyruntime_err("Client output cannot be rebound"));
927        }
928
929        state.sender = Some(get_data_event_sender());
930        if state.event_factory.is_some() {
931            state.exec_sender = Some(get_exec_event_sender());
932        }
933
934        state.bound = true;
935        Ok(())
936    }
937
938    fn send(&self, event: DataEvent) -> PyResult<()> {
939        self.sender()?.send(event).map_err(to_pyruntime_err)
940    }
941
942    fn sender(&self) -> PyResult<EventSender<DataEvent>> {
943        if thread::current().id() != self.owner {
944            return Err(to_pyruntime_err("Client output requires its owner thread"));
945        }
946
947        self.state
948            .lock()
949            .sender
950            .clone()
951            .ok_or_else(|| to_pyruntime_err("Client output is not bound to an active node"))
952    }
953
954    fn event_factory(&self) -> PyResult<OrderEventFactory> {
955        self.exec_sender()?;
956        self.state
957            .lock()
958            .event_factory
959            .clone()
960            .ok_or_else(|| to_pyruntime_err("Client has no execution identity"))
961    }
962
963    fn exec_sender(&self) -> PyResult<EventSender<ExecutionEvent>> {
964        if thread::current().id() != self.owner {
965            return Err(to_pyruntime_err("Client output requires its owner thread"));
966        }
967
968        self.state
969            .lock()
970            .exec_sender
971            .clone()
972            .ok_or_else(|| to_pyruntime_err("Execution output is not bound to an active node"))
973    }
974
975    fn send_exec(&self, event: ExecutionEvent) -> PyResult<()> {
976        let factory = self.event_factory()?;
977        let account_id = factory.account_id();
978        let trader_id = factory.trader_id();
979
980        let valid = match &event {
981            ExecutionEvent::Data(_) => true,
982            ExecutionEvent::Account(event) => event.account_id == account_id,
983            ExecutionEvent::Order(event) => {
984                event.trader_id() == trader_id
985                    && event.account_id().is_none_or(|id| id == account_id)
986            }
987            ExecutionEvent::OrderSubmittedBatch(batch) => batch
988                .events
989                .iter()
990                .all(|event| event.trader_id == trader_id && event.account_id == account_id),
991            ExecutionEvent::OrderAcceptedBatch(batch) => batch
992                .events
993                .iter()
994                .all(|event| event.trader_id == trader_id && event.account_id == account_id),
995            ExecutionEvent::OrderCanceledBatch(batch) => batch.events.iter().all(|event| {
996                event.trader_id == trader_id && event.account_id.is_none_or(|id| id == account_id)
997            }),
998            ExecutionEvent::Report(report) => match report {
999                ExecutionReport::Order(report) => report.account_id == account_id,
1000                ExecutionReport::Fill(report) => report.account_id == account_id,
1001                ExecutionReport::Position(report) => report.account_id == account_id,
1002                ExecutionReport::OrderWithFills(report, fills) => {
1003                    report.account_id == account_id
1004                        && fills.iter().all(|fill| fill.account_id == account_id)
1005                }
1006                ExecutionReport::MassStatus(report) => {
1007                    let state = self.state.lock();
1008                    mass_status_matches(report, state.client_id, account_id, state.venue)
1009                }
1010            },
1011        };
1012
1013        if !valid {
1014            return Err(to_pytype_err(
1015                "Execution output identity does not match its owner",
1016            ));
1017        }
1018
1019        self.exec_sender()?.send(event).map_err(to_pyruntime_err)
1020    }
1021
1022    fn invalidate(&self) {
1023        let mut state = self.state.lock();
1024        state.sender = None;
1025        state.exec_sender = None;
1026        state.disposed = true;
1027    }
1028}
1029
1030#[derive(Debug, Default, Clone)]
1031pub(crate) struct PythonClients(Rc<RefCell<Vec<ClientOwner>>>);
1032
1033#[derive(Debug)]
1034struct ClientOwner {
1035    client: Py<PyAny>,
1036    runtime: Py<PyAny>,
1037    output: ClientOutput,
1038    cache_id: u64,
1039}
1040
1041impl Drop for ClientOwner {
1042    fn drop(&mut self) {
1043        self.output.invalidate();
1044        CLIENT_CACHES.with_borrow_mut(|caches| caches.remove(&self.cache_id));
1045        Python::attach(|py| {
1046            if let Err(e) = self.runtime.call_method0(py, "dispose") {
1047                log::error!("Failed to dispose Python client: {e}");
1048            }
1049        });
1050    }
1051}
1052
1053impl PythonClients {
1054    pub(crate) fn take(&self) -> Self {
1055        Self(Rc::new(RefCell::new(self.0.take())))
1056    }
1057
1058    pub(crate) fn is_empty(&self) -> bool {
1059        self.0.borrow().is_empty()
1060    }
1061
1062    pub(crate) fn bind(&self, py: Python<'_>, event_loop: &Bound<'_, PyAny>) -> PyResult<()> {
1063        let runtimes: Vec<_> = self
1064            .0
1065            .borrow()
1066            .iter()
1067            .map(|owner| owner.runtime.clone_ref(py))
1068            .collect();
1069
1070        for runtime in runtimes {
1071            runtime.call_method1(py, "bind", (event_loop,))?;
1072        }
1073
1074        Ok(())
1075    }
1076
1077    pub(crate) fn finish(&self, py: Python<'_>) -> PyResult<()> {
1078        let owners = self.0.take();
1079
1080        let mut incomplete = Vec::new();
1081        let mut retained = Vec::new();
1082        let mut failure = None;
1083
1084        for owner in owners {
1085            owner.output.invalidate();
1086            CLIENT_CACHES.with_borrow_mut(|caches| caches.remove(&owner.cache_id));
1087
1088            let result = (|| {
1089                owner.runtime.call_method0(py, "dispose")?;
1090                if owner.runtime.getattr(py, "complete")?.extract::<bool>(py)? {
1091                    return Ok(true);
1092                }
1093
1094                incomplete.push(
1095                    owner
1096                        .client
1097                        .getattr(py, "client_id")?
1098                        .bind(py)
1099                        .str()?
1100                        .to_string(),
1101                );
1102                Ok::<bool, PyErr>(false)
1103            })();
1104
1105            match result {
1106                Ok(true) => {}
1107                Ok(false) => retained.push(owner),
1108                Err(e) => {
1109                    failure.get_or_insert(e);
1110                    retained.push(owner);
1111                }
1112            }
1113        }
1114
1115        self.0.borrow_mut().extend(retained);
1116
1117        if let Some(e) = failure {
1118            return Err(e);
1119        }
1120
1121        if incomplete.is_empty() {
1122            Ok(())
1123        } else {
1124            Err(to_pyruntime_err(format!(
1125                "Python client cleanup is incomplete: {}",
1126                incomplete.join(", ")
1127            )))
1128        }
1129    }
1130}
1131
1132#[derive(Debug)]
1133pub(crate) struct PythonClientConfig(pub(crate) Py<PyAny>);
1134
1135impl ClientConfig for PythonClientConfig {
1136    fn as_any(&self) -> &dyn Any {
1137        self
1138    }
1139}
1140
1141#[derive(Debug)]
1142pub(crate) struct PythonDataFactory {
1143    pub(crate) factory: Py<PyAny>,
1144    pub(crate) clients: PythonClients,
1145}
1146
1147impl DataClientFactory for PythonDataFactory {
1148    fn name(&self) -> &'static str {
1149        "Python"
1150    }
1151    fn config_type(&self) -> &'static str {
1152        "DataClientConfig"
1153    }
1154
1155    fn create(
1156        &self,
1157        name: &str,
1158        config: &dyn ClientConfig,
1159        cache: CacheView,
1160        clock: Rc<RefCell<dyn Clock>>,
1161    ) -> anyhow::Result<Box<dyn DataClient>> {
1162        Ok(Box::new(self.clients.create(
1163            &self.factory,
1164            name,
1165            config,
1166            cache,
1167            clock,
1168            None,
1169        )?))
1170    }
1171}
1172
1173#[derive(Debug)]
1174pub(crate) struct PythonExecutionFactory {
1175    pub(crate) factory: Py<PyAny>,
1176    pub(crate) clients: PythonClients,
1177}
1178
1179impl ExecutionClientFactory for PythonExecutionFactory {
1180    fn name(&self) -> &'static str {
1181        "Python"
1182    }
1183    fn config_type(&self) -> &'static str {
1184        "ExecutionClientConfig"
1185    }
1186    fn create(
1187        &self,
1188        trader_id: TraderId,
1189        name: &str,
1190        config: &dyn ClientConfig,
1191        cache: CacheView,
1192        clock: Rc<RefCell<dyn Clock>>,
1193    ) -> anyhow::Result<Box<dyn ExecutionClient>> {
1194        let mut client = self.clients.create(
1195            &self.factory,
1196            name,
1197            config,
1198            cache.clone(),
1199            clock,
1200            Some(trader_id),
1201        )?;
1202        let identity = client
1203            .execution
1204            .take()
1205            .ok_or_else(|| anyhow::anyhow!("Missing execution client identity"))?;
1206        Ok(Box::new(PythonExecutionClient {
1207            client,
1208            identity,
1209            cache,
1210        }))
1211    }
1212}
1213
1214impl PythonClients {
1215    fn create(
1216        &self,
1217        factory: &Py<PyAny>,
1218        name: &str,
1219        config: &dyn ClientConfig,
1220        cache: CacheView,
1221        clock: Rc<RefCell<dyn Clock>>,
1222        trader_id: Option<TraderId>,
1223    ) -> anyhow::Result<PythonClient> {
1224        let config = config
1225            .as_any()
1226            .downcast_ref::<PythonClientConfig>()
1227            .ok_or_else(|| anyhow::anyhow!("Expected Python client configuration"))?;
1228        Python::attach(|py| {
1229            let cache_id = CACHE_ID.fetch_add(1, Ordering::Relaxed);
1230            CLIENT_CACHES.with_borrow_mut(|caches| caches.insert(cache_id, cache));
1231
1232            let result = (|| -> PyResult<PythonClient> {
1233                let kwargs = PyDict::new(py);
1234                kwargs.set_item("name", name)?;
1235                kwargs.set_item("config", &config.0)?;
1236                kwargs.set_item("cache", PyClientCache { id: cache_id })?;
1237                kwargs.set_item("clock", PyClock::from_rc(clock.clone()))?;
1238
1239                if let Some(trader_id) = trader_id {
1240                    kwargs.set_item("trader_id", trader_id)?;
1241                }
1242
1243                let client = py
1244                    .import("nautilus_trader.live.clients")?
1245                    .getattr("_create_client")?
1246                    .call1((factory, kwargs))?
1247                    .unbind();
1248
1249                let base_name = if trader_id.is_some() {
1250                    "ExecutionClient"
1251                } else {
1252                    "DataClient"
1253                };
1254
1255                let base = py
1256                    .import("nautilus_trader.live.clients")?
1257                    .getattr(base_name)?;
1258
1259                if !client.bind(py).is_instance(&base)? {
1260                    return Err(to_pytype_err(format!("Factory must return a {base_name}")));
1261                }
1262
1263                let client_id = client.getattr(py, "client_id")?.extract::<ClientId>(py)?;
1264                if client_id.as_str() != name {
1265                    return Err(to_pytype_err(
1266                        "Factory client identity does not match registration name",
1267                    ));
1268                }
1269
1270                if !client.getattr(py, "config")?.is(&config.0) {
1271                    return Err(to_pytype_err(
1272                        "Client must retain the original factory config",
1273                    ));
1274                }
1275
1276                let venue = client.getattr(py, "venue")?.extract::<Option<Venue>>(py)?;
1277                let output = client.getattr(py, "_output")?.extract::<ClientOutput>(py)?;
1278                if client
1279                    .getattr(py, "cache")?
1280                    .extract::<PyRef<'_, PyClientCache>>(py)?
1281                    .id
1282                    != cache_id
1283                {
1284                    return Err(to_pytype_err(
1285                        "Client must retain the owning factory cache view",
1286                    ));
1287                }
1288
1289                let runtime = client.getattr(py, "_runtime")?;
1290
1291                let execution = trader_id
1292                    .map(|trader_id| -> PyResult<ExecutionIdentity> {
1293                        if client.getattr(py, "trader_id")?.extract::<TraderId>(py)? != trader_id {
1294                            return Err(to_pytype_err(
1295                                "Execution client trader identity does not match its node",
1296                            ));
1297                        }
1298
1299                        let tolerance = client
1300                            .getattr(py, "position_reconciliation_tolerance")?
1301                            .extract::<Option<Decimal>>(py)?
1302                            .unwrap_or(DEFAULT_POSITION_RECONCILIATION_TOLERANCE);
1303
1304                        if tolerance.is_sign_negative() {
1305                            return Err(to_pytype_err(
1306                                "Position reconciliation tolerance must be nonnegative",
1307                            ));
1308                        }
1309
1310                        Ok(ExecutionIdentity {
1311                            trader_id,
1312                            tolerance,
1313                            account_id: client.getattr(py, "account_id")?.extract(py)?,
1314                            account_type: client.getattr(py, "account_type")?.extract(py)?,
1315                            base_currency: client.getattr(py, "base_currency")?.extract(py)?,
1316                            oms_type: client.getattr(py, "oms_type")?.extract(py)?,
1317                            venue: venue.ok_or_else(|| {
1318                                to_pytype_err("Execution clients require a venue")
1319                            })?,
1320                        })
1321                    })
1322                    .transpose()?;
1323
1324                {
1325                    let mut state = output.state.lock();
1326                    if state.claimed || state.disposed {
1327                        return Err(to_pytype_err(
1328                            "A client instance cannot be registered twice",
1329                        ));
1330                    }
1331
1332                    state.claimed = true;
1333                    state.client_id = Some(client_id);
1334                    state.venue = venue;
1335                    state.event_factory = execution.as_ref().map(|identity| {
1336                        OrderEventFactory::new(
1337                            identity.trader_id,
1338                            identity.account_id,
1339                            identity.account_type,
1340                            identity.base_currency,
1341                        )
1342                    });
1343                }
1344
1345                self.0.borrow_mut().push(ClientOwner {
1346                    client: client.clone_ref(py),
1347                    runtime: runtime.clone_ref(py),
1348                    output: output.clone(),
1349                    cache_id,
1350                });
1351
1352                Ok(PythonClient {
1353                    client_id,
1354                    venue,
1355                    runtime,
1356                    output,
1357                    instance: client,
1358                    execution,
1359                    clock,
1360                })
1361            })();
1362
1363            if result.is_err() {
1364                CLIENT_CACHES.with_borrow_mut(|caches| caches.remove(&cache_id));
1365            }
1366
1367            result.map_err(Into::into)
1368        })
1369    }
1370}
1371
1372struct ExecutionIdentity {
1373    tolerance: Decimal,
1374    trader_id: TraderId,
1375    account_id: AccountId,
1376    account_type: AccountType,
1377    base_currency: Option<Currency>,
1378    oms_type: OmsType,
1379    venue: Venue,
1380}
1381
1382struct PythonClient {
1383    client_id: ClientId,
1384    venue: Option<Venue>,
1385    runtime: Py<PyAny>,
1386    output: ClientOutput,
1387    instance: Py<PyAny>,
1388    execution: Option<ExecutionIdentity>,
1389    clock: Rc<RefCell<dyn Clock>>,
1390}
1391
1392#[async_trait(?Send)]
1393impl DataClient for PythonClient {
1394    fn client_id(&self) -> ClientId {
1395        self.client_id
1396    }
1397    fn venue(&self) -> Option<Venue> {
1398        self.venue
1399    }
1400    fn start(&mut self) -> anyhow::Result<()> {
1401        self.output.bind().map_err(Into::into)
1402    }
1403    fn stop(&mut self) -> anyhow::Result<()> {
1404        Ok(())
1405    }
1406    fn reset(&mut self) -> anyhow::Result<()> {
1407        anyhow::bail!("Python clients are single-use")
1408    }
1409    fn dispose(&mut self) -> anyhow::Result<()> {
1410        Ok(())
1411    }
1412    fn is_connected(&self) -> bool {
1413        Python::attach(|py| {
1414            self.runtime
1415                .getattr(py, "connected")
1416                .and_then(|v| v.extract(py))
1417                .unwrap_or(false)
1418        })
1419    }
1420    fn is_disconnected(&self) -> bool {
1421        !self.is_connected()
1422    }
1423    async fn connect(&mut self) -> anyhow::Result<()> {
1424        self.lifecycle("connect").await
1425    }
1426    async fn disconnect(&mut self) -> anyhow::Result<()> {
1427        self.lifecycle("disconnect").await
1428    }
1429    fn subscribe(&mut self, command: SubscribeCustomData) -> anyhow::Result<()> {
1430        Python::attach(|py| {
1431            self.runtime
1432                .call_method1(py, "admit", ("_subscribe", (command,)))
1433        })?;
1434
1435        Ok(())
1436    }
1437    fn subscribe_instruments(&mut self, command: SubscribeInstruments) -> anyhow::Result<()> {
1438        Python::attach(|py| {
1439            self.runtime
1440                .call_method1(py, "admit", ("_subscribe_instruments", (command,)))
1441        })?;
1442
1443        Ok(())
1444    }
1445    fn subscribe_instrument(&mut self, command: SubscribeInstrument) -> anyhow::Result<()> {
1446        Python::attach(|py| {
1447            self.runtime
1448                .call_method1(py, "admit", ("_subscribe_instrument", (command,)))
1449        })?;
1450
1451        Ok(())
1452    }
1453    fn subscribe_book_deltas(&mut self, command: SubscribeBookDeltas) -> anyhow::Result<()> {
1454        Python::attach(|py| {
1455            self.runtime
1456                .call_method1(py, "admit", ("_subscribe_book_deltas", (command,)))
1457        })?;
1458
1459        Ok(())
1460    }
1461    fn subscribe_book_depth(&mut self, command: SubscribeBookDepth) -> anyhow::Result<()> {
1462        Python::attach(|py| {
1463            self.runtime
1464                .call_method1(py, "admit", ("_subscribe_book_depth", (command,)))
1465        })?;
1466
1467        Ok(())
1468    }
1469    fn subscribe_quotes(&mut self, command: SubscribeQuotes) -> anyhow::Result<()> {
1470        Python::attach(|py| {
1471            self.runtime
1472                .call_method1(py, "admit", ("_subscribe_quotes", (command,)))
1473        })?;
1474
1475        Ok(())
1476    }
1477    fn subscribe_trades(&mut self, command: SubscribeTrades) -> anyhow::Result<()> {
1478        Python::attach(|py| {
1479            self.runtime
1480                .call_method1(py, "admit", ("_subscribe_trades", (command,)))
1481        })?;
1482
1483        Ok(())
1484    }
1485    fn subscribe_mark_prices(&mut self, command: SubscribeMarkPrices) -> anyhow::Result<()> {
1486        Python::attach(|py| {
1487            self.runtime
1488                .call_method1(py, "admit", ("_subscribe_mark_prices", (command,)))
1489        })?;
1490
1491        Ok(())
1492    }
1493    fn subscribe_index_prices(&mut self, command: SubscribeIndexPrices) -> anyhow::Result<()> {
1494        Python::attach(|py| {
1495            self.runtime
1496                .call_method1(py, "admit", ("_subscribe_index_prices", (command,)))
1497        })?;
1498
1499        Ok(())
1500    }
1501    fn subscribe_funding_rates(&mut self, command: SubscribeFundingRates) -> anyhow::Result<()> {
1502        Python::attach(|py| {
1503            self.runtime
1504                .call_method1(py, "admit", ("_subscribe_funding_rates", (command,)))
1505        })?;
1506
1507        Ok(())
1508    }
1509    fn subscribe_bars(&mut self, command: SubscribeBars) -> anyhow::Result<()> {
1510        Python::attach(|py| {
1511            self.runtime
1512                .call_method1(py, "admit", ("_subscribe_bars", (command,)))
1513        })?;
1514
1515        Ok(())
1516    }
1517    fn subscribe_instrument_status(
1518        &mut self,
1519        command: SubscribeInstrumentStatus,
1520    ) -> anyhow::Result<()> {
1521        Python::attach(|py| {
1522            self.runtime
1523                .call_method1(py, "admit", ("_subscribe_instrument_status", (command,)))
1524        })?;
1525
1526        Ok(())
1527    }
1528    fn subscribe_instrument_close(
1529        &mut self,
1530        command: SubscribeInstrumentClose,
1531    ) -> anyhow::Result<()> {
1532        Python::attach(|py| {
1533            self.runtime
1534                .call_method1(py, "admit", ("_subscribe_instrument_close", (command,)))
1535        })?;
1536
1537        Ok(())
1538    }
1539    fn subscribe_option_greeks(&mut self, command: SubscribeOptionGreeks) -> anyhow::Result<()> {
1540        Python::attach(|py| {
1541            self.runtime
1542                .call_method1(py, "admit", ("_subscribe_option_greeks", (command,)))
1543        })?;
1544
1545        Ok(())
1546    }
1547    fn unsubscribe(&mut self, command: &UnsubscribeCustomData) -> anyhow::Result<()> {
1548        Python::attach(|py| {
1549            self.runtime
1550                .call_method1(py, "admit", ("_unsubscribe", (command.clone(),)))
1551        })?;
1552
1553        Ok(())
1554    }
1555    fn unsubscribe_instruments(&mut self, command: &UnsubscribeInstruments) -> anyhow::Result<()> {
1556        Python::attach(|py| {
1557            self.runtime.call_method1(
1558                py,
1559                "admit",
1560                ("_unsubscribe_instruments", (command.clone(),)),
1561            )
1562        })?;
1563
1564        Ok(())
1565    }
1566    fn unsubscribe_instrument(&mut self, command: &UnsubscribeInstrument) -> anyhow::Result<()> {
1567        Python::attach(|py| {
1568            self.runtime
1569                .call_method1(py, "admit", ("_unsubscribe_instrument", (command.clone(),)))
1570        })?;
1571
1572        Ok(())
1573    }
1574    fn unsubscribe_book_deltas(&mut self, command: &UnsubscribeBookDeltas) -> anyhow::Result<()> {
1575        Python::attach(|py| {
1576            self.runtime.call_method1(
1577                py,
1578                "admit",
1579                ("_unsubscribe_book_deltas", (command.clone(),)),
1580            )
1581        })?;
1582
1583        Ok(())
1584    }
1585    fn unsubscribe_book_depth(&mut self, command: &UnsubscribeBookDepth) -> anyhow::Result<()> {
1586        Python::attach(|py| {
1587            self.runtime
1588                .call_method1(py, "admit", ("_unsubscribe_book_depth", (command.clone(),)))
1589        })?;
1590
1591        Ok(())
1592    }
1593    fn unsubscribe_quotes(&mut self, command: &UnsubscribeQuotes) -> anyhow::Result<()> {
1594        Python::attach(|py| {
1595            self.runtime
1596                .call_method1(py, "admit", ("_unsubscribe_quotes", (command.clone(),)))
1597        })?;
1598
1599        Ok(())
1600    }
1601    fn unsubscribe_trades(&mut self, command: &UnsubscribeTrades) -> anyhow::Result<()> {
1602        Python::attach(|py| {
1603            self.runtime
1604                .call_method1(py, "admit", ("_unsubscribe_trades", (command.clone(),)))
1605        })?;
1606
1607        Ok(())
1608    }
1609    fn unsubscribe_mark_prices(&mut self, command: &UnsubscribeMarkPrices) -> anyhow::Result<()> {
1610        Python::attach(|py| {
1611            self.runtime.call_method1(
1612                py,
1613                "admit",
1614                ("_unsubscribe_mark_prices", (command.clone(),)),
1615            )
1616        })?;
1617
1618        Ok(())
1619    }
1620    fn unsubscribe_index_prices(&mut self, command: &UnsubscribeIndexPrices) -> anyhow::Result<()> {
1621        Python::attach(|py| {
1622            self.runtime.call_method1(
1623                py,
1624                "admit",
1625                ("_unsubscribe_index_prices", (command.clone(),)),
1626            )
1627        })?;
1628
1629        Ok(())
1630    }
1631    fn unsubscribe_funding_rates(
1632        &mut self,
1633        command: &UnsubscribeFundingRates,
1634    ) -> anyhow::Result<()> {
1635        Python::attach(|py| {
1636            self.runtime.call_method1(
1637                py,
1638                "admit",
1639                ("_unsubscribe_funding_rates", (command.clone(),)),
1640            )
1641        })?;
1642
1643        Ok(())
1644    }
1645    fn unsubscribe_bars(&mut self, command: &UnsubscribeBars) -> anyhow::Result<()> {
1646        Python::attach(|py| {
1647            self.runtime
1648                .call_method1(py, "admit", ("_unsubscribe_bars", (command.clone(),)))
1649        })?;
1650
1651        Ok(())
1652    }
1653    fn unsubscribe_instrument_status(
1654        &mut self,
1655        command: &UnsubscribeInstrumentStatus,
1656    ) -> anyhow::Result<()> {
1657        Python::attach(|py| {
1658            self.runtime.call_method1(
1659                py,
1660                "admit",
1661                ("_unsubscribe_instrument_status", (command.clone(),)),
1662            )
1663        })?;
1664
1665        Ok(())
1666    }
1667    fn unsubscribe_instrument_close(
1668        &mut self,
1669        command: &UnsubscribeInstrumentClose,
1670    ) -> anyhow::Result<()> {
1671        Python::attach(|py| {
1672            self.runtime.call_method1(
1673                py,
1674                "admit",
1675                ("_unsubscribe_instrument_close", (command.clone(),)),
1676            )
1677        })?;
1678
1679        Ok(())
1680    }
1681    fn unsubscribe_option_greeks(
1682        &mut self,
1683        command: &UnsubscribeOptionGreeks,
1684    ) -> anyhow::Result<()> {
1685        Python::attach(|py| {
1686            self.runtime.call_method1(
1687                py,
1688                "admit",
1689                ("_unsubscribe_option_greeks", (command.clone(),)),
1690            )
1691        })?;
1692
1693        Ok(())
1694    }
1695
1696    fn request_data(&self, request: RequestCustomData) -> anyhow::Result<()> {
1697        let request_id = request.request_id;
1698        Python::attach(|py| {
1699            let argument = Py::new(py, PyRequestCustomData { request })?.into_any();
1700            self.call_request(py, "_request_data", request_id, argument)
1701        })?;
1702
1703        Ok(())
1704    }
1705
1706    fn request_instruments(&self, request: RequestInstruments) -> anyhow::Result<()> {
1707        let request_id = request.request_id;
1708        Python::attach(|py| {
1709            let argument = Py::new(py, PyRequestInstruments { request })?.into_any();
1710            self.call_request(py, "_request_instruments", request_id, argument)
1711        })?;
1712
1713        Ok(())
1714    }
1715
1716    fn request_instrument(&self, request: RequestInstrument) -> anyhow::Result<()> {
1717        let request_id = request.request_id;
1718        Python::attach(|py| {
1719            let argument = Py::new(py, PyRequestInstrument { request })?.into_any();
1720            self.call_request(py, "_request_instrument", request_id, argument)
1721        })?;
1722
1723        Ok(())
1724    }
1725
1726    fn request_book_snapshot(&self, request: RequestBookSnapshot) -> anyhow::Result<()> {
1727        let request_id = request.request_id;
1728        Python::attach(|py| {
1729            let argument = Py::new(py, PyRequestBookSnapshot { request })?.into_any();
1730            self.call_request(py, "_request_book_snapshot", request_id, argument)
1731        })?;
1732
1733        Ok(())
1734    }
1735
1736    fn request_quotes(&self, request: RequestQuotes) -> anyhow::Result<()> {
1737        let request_id = request.request_id;
1738        Python::attach(|py| {
1739            let argument = Py::new(py, PyRequestQuotes { request })?.into_any();
1740            self.call_request(py, "_request_quotes", request_id, argument)
1741        })?;
1742
1743        Ok(())
1744    }
1745
1746    fn request_trades(&self, request: RequestTrades) -> anyhow::Result<()> {
1747        let request_id = request.request_id;
1748        Python::attach(|py| {
1749            let argument = Py::new(py, PyRequestTrades { request })?.into_any();
1750            self.call_request(py, "_request_trades", request_id, argument)
1751        })?;
1752
1753        Ok(())
1754    }
1755
1756    fn request_funding_rates(&self, request: RequestFundingRates) -> anyhow::Result<()> {
1757        let request_id = request.request_id;
1758        Python::attach(|py| {
1759            let argument = Py::new(py, PyRequestFundingRates { request })?.into_any();
1760            self.call_request(py, "_request_funding_rates", request_id, argument)
1761        })?;
1762
1763        Ok(())
1764    }
1765
1766    fn request_option_chain_reference_price(
1767        &self,
1768        request: RequestOptionChainReferencePrice,
1769    ) -> anyhow::Result<()> {
1770        let request_id = request.request_id;
1771        Python::attach(|py| {
1772            let argument = Py::new(py, PyRequestOptionChainReferencePrice { request })?.into_any();
1773            self.call_request(
1774                py,
1775                "_request_option_chain_reference_price",
1776                request_id,
1777                argument,
1778            )
1779        })?;
1780
1781        Ok(())
1782    }
1783
1784    fn request_bars(&self, request: RequestBars) -> anyhow::Result<()> {
1785        let request_id = request.request_id;
1786        Python::attach(|py| {
1787            let argument = Py::new(py, PyRequestBars { request })?.into_any();
1788            self.call_request(py, "_request_bars", request_id, argument)
1789        })?;
1790
1791        Ok(())
1792    }
1793
1794    fn request_book_depth(&self, request: RequestBookDepth) -> anyhow::Result<()> {
1795        let request_id = request.request_id;
1796        Python::attach(|py| {
1797            let argument = Py::new(py, PyRequestBookDepth { request })?.into_any();
1798            self.call_request(py, "_request_book_depth", request_id, argument)
1799        })?;
1800
1801        Ok(())
1802    }
1803
1804    fn request_book_deltas(&self, request: RequestBookDeltas) -> anyhow::Result<()> {
1805        let request_id = request.request_id;
1806        Python::attach(|py| {
1807            let argument = Py::new(py, PyRequestBookDeltas { request })?.into_any();
1808            self.call_request(py, "_request_book_deltas", request_id, argument)
1809        })?;
1810
1811        Ok(())
1812    }
1813}
1814
1815impl PythonClient {
1816    async fn lifecycle(&self, operation: &str) -> anyhow::Result<()> {
1817        let future = Python::attach(|py| {
1818            let task = self.runtime.call_method1(py, "lifecycle", (operation,))?;
1819
1820            PythonOperation::new(py, task, self.runtime.clone_ref(py))
1821        })?;
1822
1823        future.await.map(|_| ()).map_err(Into::into)
1824    }
1825}
1826
1827fn extract_data(data: &Bound<'_, PyAny>) -> PyResult<Data> {
1828    macro_rules! extract {
1829        ($($ty:ty),+ $(,)?) => {
1830            $(if data.is_instance_of::<$ty>() {
1831                return Ok(data.extract::<$ty>()?.into());
1832            })+
1833        };
1834    }
1835    extract!(
1836        QuoteTick,
1837        TradeTick,
1838        Bar,
1839        OrderBookDelta,
1840        OrderBookDeltas,
1841        OrderBookDepth,
1842        MarkPriceUpdate,
1843        IndexPriceUpdate,
1844        FundingRateUpdate,
1845        OptionGreeks,
1846        InstrumentStatus,
1847        InstrumentClose
1848    );
1849
1850    if data.is_instance_of::<CustomData>() {
1851        return Ok(Data::Custom(data.extract()?));
1852    }
1853
1854    Err(to_pytype_err(
1855        "Expected a Nautilus data object from the installed wheel",
1856    ))
1857}
1858
1859struct PythonExecutionClient {
1860    client: PythonClient,
1861    identity: ExecutionIdentity,
1862    cache: CacheView,
1863}
1864
1865impl PythonClient {
1866    fn call_request(
1867        &self,
1868        py: Python<'_>,
1869        operation: &str,
1870        request_id: nautilus_core::UUID4,
1871        argument: Py<PyAny>,
1872    ) -> PyResult<()> {
1873        let task = self
1874            .runtime
1875            .call_method1(py, "call", (operation, (argument,)))?;
1876        let output = self.output.clone();
1877
1878        let callback = PyCFunction::new_closure(
1879            py,
1880            None,
1881            None,
1882            move |args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>| {
1883                let task = args.get_item(0)?;
1884
1885                let reason = if task.call_method0("cancelled")?.extract::<bool>()? {
1886                    Some("Python data request canceled".to_owned())
1887                } else {
1888                    let exception = task.call_method0("exception")?;
1889                    if exception.is_none() {
1890                        None
1891                    } else {
1892                        Some(exception.str()?.to_str()?.to_owned())
1893                    }
1894                };
1895
1896                if let Some(reason) = reason {
1897                    if output.state.lock().disposed {
1898                        return Ok(());
1899                    }
1900
1901                    if let Err(e) = output.send(DataEvent::RequestFailed(DataRequestFailed {
1902                        request_id,
1903                        reason,
1904                        response: None,
1905                    })) {
1906                        log::error!("Failed to deliver Python data request failure: {e}");
1907                    }
1908                }
1909
1910                Ok::<(), PyErr>(())
1911            },
1912        )?;
1913
1914        task.call_method1(py, "add_done_callback", (callback,))?;
1915        Ok(())
1916    }
1917}
1918
1919#[async_trait(?Send)]
1920impl ExecutionClient for PythonExecutionClient {
1921    fn client_id(&self) -> ClientId {
1922        self.client.client_id
1923    }
1924    fn account_id(&self) -> AccountId {
1925        self.identity.account_id
1926    }
1927    fn venue(&self) -> Venue {
1928        self.identity.venue
1929    }
1930    fn oms_type(&self) -> OmsType {
1931        self.identity.oms_type
1932    }
1933    fn position_reconciliation_tolerance(&self) -> Decimal {
1934        self.identity.tolerance
1935    }
1936    fn handles_order_venue(&self, venue: Venue) -> bool {
1937        Python::attach(|py| {
1938            self.client
1939                .instance
1940                .call_method1(py, "_handles_order_venue", (venue,))?
1941                .extract::<bool>(py)
1942        })
1943        .unwrap_or_else(|e| {
1944            log::error!(
1945                "Client {} venue coverage failed: {e}",
1946                self.client.client_id
1947            );
1948            false
1949        })
1950    }
1951    fn provides_bulk_position_coverage(&self, instrument_id: InstrumentId) -> bool {
1952        Python::attach(|py| {
1953            self.client
1954                .instance
1955                .call_method1(py, "_provides_bulk_position_coverage", (instrument_id,))?
1956                .extract::<bool>(py)
1957        })
1958        .unwrap_or_else(|e| {
1959            log::error!(
1960                "Client {} bulk position coverage failed: {e}",
1961                self.client.client_id
1962            );
1963            false
1964        })
1965    }
1966    fn calculate_commission(
1967        &self,
1968        instrument: &InstrumentAny,
1969        last_qty: Quantity,
1970        last_px: Price,
1971        liquidity_side: LiquiditySide,
1972    ) -> anyhow::Result<Option<Money>> {
1973        Python::attach(|py| -> PyResult<Option<Money>> {
1974            let instrument = instrument_any_to_pyobject(py, instrument.clone())?;
1975            Ok(self
1976                .client
1977                .instance
1978                .call_method1(
1979                    py,
1980                    "_calculate_commission",
1981                    (instrument, last_qty, last_px, liquidity_side),
1982                )?
1983                .extract(py)?)
1984        })
1985        .map_err(Into::into)
1986    }
1987    fn register_external_order(
1988        &self,
1989        client_order_id: ClientOrderId,
1990        venue_order_id: VenueOrderId,
1991        instrument_id: InstrumentId,
1992        strategy_id: StrategyId,
1993        ts_init: UnixNanos,
1994    ) {
1995        if let Err(e) = Python::attach(|py| {
1996            self.client.runtime.call_method1(
1997                py,
1998                "admit",
1999                (
2000                    "_register_external_order",
2001                    (
2002                        client_order_id,
2003                        venue_order_id,
2004                        instrument_id,
2005                        strategy_id,
2006                        ts_init.as_u64(),
2007                    ),
2008                ),
2009            )
2010        }) {
2011            log::error!(
2012                "Client {} external order registration failed: {e}",
2013                self.client.client_id
2014            );
2015        }
2016    }
2017    fn on_instrument(&mut self, instrument: InstrumentAny) {
2018        if let Err(e) = Python::attach(|py| -> PyResult<()> {
2019            let instrument = instrument_any_to_pyobject(py, instrument)?;
2020            self.client
2021                .runtime
2022                .call_method1(py, "admit", ("_on_instrument", (instrument,)))?;
2023            Ok(())
2024        }) {
2025            log::error!(
2026                "Client {} instrument update failed: {e}",
2027                self.client.client_id
2028            );
2029        }
2030    }
2031    fn get_account(&self) -> Option<AccountAny> {
2032        match self.cache.try_borrow() {
2033            Ok(cache) => cache.account_owned(&self.identity.account_id),
2034            Err(e) => {
2035                log::error!("Cannot read Python execution client account: {e}");
2036                None
2037            }
2038        }
2039    }
2040    fn generate_account_state(
2041        &self,
2042        balances: Vec<AccountBalance>,
2043        margins: Vec<MarginBalance>,
2044        reported: bool,
2045        ts_event: UnixNanos,
2046        info: Option<Params>,
2047    ) -> anyhow::Result<()> {
2048        let ts_init = self.client.clock.borrow().timestamp_ns();
2049        let factory = self.client.output.event_factory()?;
2050        let event =
2051            factory.generate_account_state(balances, margins, reported, ts_event, ts_init, info);
2052        self.client
2053            .output
2054            .send_exec(ExecutionEvent::Account(event))
2055            .map_err(Into::into)
2056    }
2057    fn start(&mut self) -> anyhow::Result<()> {
2058        self.client.output.bind().map_err(Into::into)
2059    }
2060    fn stop(&mut self) -> anyhow::Result<()> {
2061        Ok(())
2062    }
2063    fn reset(&mut self) -> anyhow::Result<()> {
2064        anyhow::bail!("Python clients are single-use")
2065    }
2066    fn dispose(&mut self) -> anyhow::Result<()> {
2067        Ok(())
2068    }
2069    fn is_connected(&self) -> bool {
2070        DataClient::is_connected(&self.client)
2071    }
2072    async fn connect(&mut self) -> anyhow::Result<()> {
2073        self.client.lifecycle("connect").await
2074    }
2075    async fn disconnect(&mut self) -> anyhow::Result<()> {
2076        self.client.lifecycle("disconnect").await
2077    }
2078    fn submit_order(&self, command: SubmitOrder) -> anyhow::Result<()> {
2079        Python::attach(|py| {
2080            self.client
2081                .runtime
2082                .call_method1(py, "admit", ("_submit_order", (command,)))
2083        })?;
2084
2085        Ok(())
2086    }
2087    fn submit_order_list(&self, command: SubmitOrderList) -> anyhow::Result<()> {
2088        Python::attach(|py| {
2089            self.client
2090                .runtime
2091                .call_method1(py, "admit", ("_submit_order_list", (command,)))
2092        })?;
2093
2094        Ok(())
2095    }
2096    fn modify_order(&self, command: ModifyOrder) -> anyhow::Result<()> {
2097        Python::attach(|py| {
2098            self.client
2099                .runtime
2100                .call_method1(py, "admit", ("_modify_order", (command,)))
2101        })?;
2102
2103        Ok(())
2104    }
2105    fn batch_modify_orders(&self, command: BatchModifyOrders) -> anyhow::Result<()> {
2106        Python::attach(|py| {
2107            self.client
2108                .runtime
2109                .call_method1(py, "admit", ("_batch_modify_orders", (command,)))
2110        })?;
2111
2112        Ok(())
2113    }
2114    fn cancel_order(&self, command: CancelOrder) -> anyhow::Result<()> {
2115        Python::attach(|py| {
2116            self.client
2117                .runtime
2118                .call_method1(py, "admit", ("_cancel_order", (command,)))
2119        })?;
2120
2121        Ok(())
2122    }
2123    fn cancel_all_orders(&self, command: CancelAllOrders) -> anyhow::Result<()> {
2124        Python::attach(|py| {
2125            self.client
2126                .runtime
2127                .call_method1(py, "admit", ("_cancel_all_orders", (command,)))
2128        })?;
2129
2130        Ok(())
2131    }
2132    fn batch_cancel_orders(&self, command: BatchCancelOrders) -> anyhow::Result<()> {
2133        Python::attach(|py| {
2134            self.client
2135                .runtime
2136                .call_method1(py, "admit", ("_batch_cancel_orders", (command,)))
2137        })?;
2138
2139        Ok(())
2140    }
2141    fn query_account(&self, command: QueryAccount) -> anyhow::Result<()> {
2142        Python::attach(|py| {
2143            self.client
2144                .runtime
2145                .call_method1(py, "admit", ("_query_account", (command,)))
2146        })?;
2147
2148        Ok(())
2149    }
2150    fn query_order(&self, command: QueryOrder) -> anyhow::Result<()> {
2151        Python::attach(|py| {
2152            self.client
2153                .runtime
2154                .call_method1(py, "admit", ("_query_order", (command,)))
2155        })?;
2156
2157        Ok(())
2158    }
2159    async fn generate_mass_status(
2160        &self,
2161        lookback_mins: Option<u64>,
2162    ) -> anyhow::Result<Option<ExecutionMassStatus>> {
2163        let operation = Python::attach(|py| {
2164            let task = self.client.runtime.call_method1(
2165                py,
2166                "call_awaited",
2167                ("_generate_mass_status", (lookback_mins,)),
2168            )?;
2169
2170            PythonOperation::new(py, task, self.client.runtime.clone_ref(py))
2171        })?;
2172
2173        let result = operation.await?;
2174        let default = Python::attach(|py| result.is(py.NotImplemented()));
2175        if default {
2176            let ts_init = self.client.clock.borrow().timestamp_ns();
2177            generate_mass_status(self, lookback_mins, ts_init).await
2178        } else {
2179            let report = Python::attach(|py| -> PyResult<Option<ExecutionMassStatus>> {
2180                Ok(result.extract(py)?)
2181            })?;
2182
2183            if report.as_ref().is_some_and(|report| {
2184                !mass_status_matches(
2185                    report,
2186                    Some(self.client.client_id),
2187                    self.identity.account_id,
2188                    Some(self.identity.venue),
2189                )
2190            }) {
2191                anyhow::bail!("Mass status identity does not match its client");
2192            }
2193
2194            Ok(report)
2195        }
2196    }
2197    async fn generate_order_status_report(
2198        &self,
2199        command: &GenerateOrderStatusReport,
2200    ) -> anyhow::Result<Option<OrderStatusReport>> {
2201        let operation = Python::attach(|py| {
2202            let task = self.client.runtime.call_method1(
2203                py,
2204                "call_awaited",
2205                ("_generate_order_status_report", (command.clone(),)),
2206            )?;
2207
2208            PythonOperation::new(py, task, self.client.runtime.clone_ref(py))
2209        })?;
2210
2211        let result = operation.await?;
2212
2213        let report = Python::attach(|py| -> PyResult<Option<OrderStatusReport>> {
2214            Ok(result.extract(py)?)
2215        })?;
2216
2217        if report
2218            .as_ref()
2219            .is_some_and(|report| report.account_id != self.identity.account_id)
2220        {
2221            anyhow::bail!("Report account identity does not match its client");
2222        }
2223
2224        Ok(report)
2225    }
2226    async fn generate_order_status_reports(
2227        &self,
2228        command: &GenerateOrderStatusReports,
2229    ) -> anyhow::Result<Vec<OrderStatusReport>> {
2230        let operation = Python::attach(|py| {
2231            let task = self.client.runtime.call_method1(
2232                py,
2233                "call_awaited",
2234                ("_generate_order_status_reports", (command.clone(),)),
2235            )?;
2236
2237            PythonOperation::new(py, task, self.client.runtime.clone_ref(py))
2238        })?;
2239
2240        let result = operation.await?;
2241        let reports = Python::attach(|py| result.extract::<Vec<OrderStatusReport>>(py))?;
2242        if reports
2243            .iter()
2244            .any(|report| report.account_id != self.identity.account_id)
2245        {
2246            anyhow::bail!("Report account identity does not match its client");
2247        }
2248
2249        Ok(reports)
2250    }
2251    async fn generate_fill_reports(
2252        &self,
2253        command: GenerateFillReports,
2254    ) -> anyhow::Result<Vec<FillReport>> {
2255        let operation = Python::attach(|py| {
2256            let task = self.client.runtime.call_method1(
2257                py,
2258                "call_awaited",
2259                ("_generate_fill_reports", (command,)),
2260            )?;
2261
2262            PythonOperation::new(py, task, self.client.runtime.clone_ref(py))
2263        })?;
2264
2265        let result = operation.await?;
2266        let reports = Python::attach(|py| result.extract::<Vec<FillReport>>(py))?;
2267        if reports
2268            .iter()
2269            .any(|report| report.account_id != self.identity.account_id)
2270        {
2271            anyhow::bail!("Report account identity does not match its client");
2272        }
2273
2274        Ok(reports)
2275    }
2276    async fn generate_position_status_reports(
2277        &self,
2278        command: &GeneratePositionStatusReports,
2279    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2280        let operation = Python::attach(|py| {
2281            let task = self.client.runtime.call_method1(
2282                py,
2283                "call_awaited",
2284                ("_generate_position_status_reports", (command.clone(),)),
2285            )?;
2286
2287            PythonOperation::new(py, task, self.client.runtime.clone_ref(py))
2288        })?;
2289
2290        let result = operation.await?;
2291        let reports = Python::attach(|py| result.extract::<Vec<PositionStatusReport>>(py))?;
2292        if reports
2293            .iter()
2294            .any(|report| report.account_id != self.identity.account_id)
2295        {
2296            anyhow::bail!("Report account identity does not match its client");
2297        }
2298
2299        Ok(reports)
2300    }
2301}
2302
2303fn mass_status_matches(
2304    report: &ExecutionMassStatus,
2305    client_id: Option<ClientId>,
2306    account_id: AccountId,
2307    venue: Option<Venue>,
2308) -> bool {
2309    report.account_id == account_id
2310        && Some(report.client_id) == client_id
2311        && Some(report.venue) == venue
2312        && report
2313            .order_reports()
2314            .values()
2315            .all(|report| report.account_id == account_id)
2316        && report
2317            .fill_reports()
2318            .values()
2319            .flatten()
2320            .all(|report| report.account_id == account_id)
2321        && report
2322            .position_reports()
2323            .values()
2324            .flatten()
2325            .all(|report| report.account_id == account_id)
2326}
2327
2328#[cfg(test)]
2329mod tests {
2330    use nautilus_common::{clock::VirtualClock, enums::LogLevel, messages::data::DataResponse};
2331    use nautilus_core::python::to_pyvalue_err;
2332    use nautilus_model::{
2333        enums::{OrderStatus, OrderType, TimeInForce},
2334        events::OrderEventAny,
2335    };
2336    use rstest::{fixture, rstest};
2337
2338    use super::*;
2339
2340    #[fixture]
2341    fn execution_output() -> (
2342        ClientOutput,
2343        tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
2344    ) {
2345        Python::initialize();
2346        let output = ClientOutput::py_new();
2347        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
2348        {
2349            let mut state = output.state.lock();
2350            state.exec_sender = Some(sender.into());
2351            state.bound = true;
2352            state.event_factory = Some(OrderEventFactory::new(
2353                TraderId::from("TESTER-001"),
2354                AccountId::from("SIM-001"),
2355                AccountType::Cash,
2356                None,
2357            ));
2358        }
2359
2360        (output, receiver)
2361    }
2362
2363    #[fixture]
2364    fn native_execution_client() -> PythonExecutionClient {
2365        Python::initialize();
2366        Python::attach(|py| {
2367            let module = PyModule::from_code(
2368                py,
2369                c"import asyncio
2370class Runtime:
2371    def __init__(self):
2372        self.loop = asyncio.new_event_loop()
2373        self.result = None
2374        self.failure = None
2375        self.cancelled = False
2376        self.calls = []
2377    def call_awaited(self, operation, args):
2378        self.calls.append((operation, args))
2379        task = self.loop.create_future()
2380        if self.cancelled:
2381            task.cancel()
2382        elif self.failure is not None:
2383            task.set_exception(self.failure)
2384        else:
2385            task.set_result(self.result)
2386        return task
2387    def call(self, operation, args):
2388        return self.call_awaited(operation, args)
2389    def _handles_order_venue(self, venue):
2390        self.calls.append(('venue', venue))
2391        if self.failure is not None:
2392            raise self.failure
2393        return self.result
2394    def _provides_bulk_position_coverage(self, instrument_id):
2395        self.calls.append(('positions', instrument_id))
2396        if self.failure is not None:
2397            raise self.failure
2398        return self.result
2399    def _calculate_commission(self, *args):
2400        self.calls.append(('commission', args))
2401        if self.failure is not None:
2402            raise self.failure
2403        return self.result
2404    def abandon(self, task):
2405        task.cancel()
2406    def __del__(self):
2407        self.loop.close()
2408",
2409                c"adapter_native_tests.py",
2410                c"adapter_native_tests",
2411            )
2412            .unwrap();
2413            let runtime = module.getattr("Runtime").unwrap().call0().unwrap().unbind();
2414
2415            let cache = CacheView::new(Rc::new(RefCell::new(Cache::default())));
2416
2417            PythonExecutionClient {
2418                client: PythonClient {
2419                    client_id: ClientId::from("SIM"),
2420                    venue: Some(Venue::from("SIM")),
2421                    instance: runtime.clone_ref(py),
2422                    runtime,
2423                    output: ClientOutput::py_new(),
2424                    execution: None,
2425                    clock: Rc::new(RefCell::new(VirtualClock::default())),
2426                },
2427                identity: ExecutionIdentity {
2428                    tolerance: Decimal::ZERO,
2429                    trader_id: TraderId::from("TESTER-001"),
2430                    account_id: AccountId::from("SIM-001"),
2431                    account_type: AccountType::Cash,
2432                    base_currency: None,
2433                    oms_type: OmsType::Netting,
2434                    venue: Venue::from("SIM"),
2435                },
2436                cache,
2437            }
2438        })
2439    }
2440
2441    #[rstest]
2442    #[case("missing")]
2443    #[case("valid")]
2444    #[case("foreign")]
2445    #[case("wrong_type")]
2446    #[case("exception")]
2447    #[case("cancelled")]
2448    #[tokio::test]
2449    async fn test_single_order_report_validates_result_and_preserves_command(
2450        native_execution_client: PythonExecutionClient,
2451        #[case] result_kind: &str,
2452    ) {
2453        let client = native_execution_client;
2454        let mut expected = order_report();
2455
2456        if result_kind == "foreign" {
2457            expected.account_id = AccountId::from("OTHER-001");
2458        }
2459
2460        let command = GenerateOrderStatusReport::new(
2461            nautilus_core::UUID4::new(),
2462            163.into(),
2463            Some(InstrumentId::from("AUD/USD.SIM")),
2464            Some(ClientOrderId::from("ORDER-167")),
2465            Some(VenueOrderId::from("VENUE-173")),
2466            None,
2467            Some(nautilus_core::UUID4::new()),
2468        );
2469        Python::attach(|py| {
2470            let runtime = client.client.runtime.bind(py);
2471
2472            match result_kind {
2473                "valid" | "foreign" => runtime
2474                    .setattr("result", Py::new(py, expected.clone()).unwrap())
2475                    .unwrap(),
2476                "wrong_type" => runtime.setattr("result", "not a report").unwrap(),
2477                "exception" => runtime
2478                    .setattr("failure", to_pyvalue_err("Report rejected").value(py))
2479                    .unwrap(),
2480                "cancelled" => runtime.setattr("cancelled", true).unwrap(),
2481                _ => {}
2482            }
2483        });
2484
2485        let result = client.generate_order_status_report(&command).await;
2486
2487        match result_kind {
2488            "missing" => assert_eq!(result.unwrap(), None),
2489            "valid" => assert_eq!(result.unwrap(), Some(expected)),
2490            "foreign" => assert_eq!(
2491                result.unwrap_err().to_string(),
2492                "Report account identity does not match its client"
2493            ),
2494            "wrong_type" => assert!(
2495                result
2496                    .unwrap_err()
2497                    .to_string()
2498                    .contains("OrderStatusReport")
2499            ),
2500            "exception" => assert_eq!(
2501                result.unwrap_err().to_string(),
2502                "ValueError: Report rejected"
2503            ),
2504            "cancelled" => assert!(result.unwrap_err().to_string().contains("CancelledError")),
2505            _ => unreachable!(),
2506        }
2507
2508        Python::attach(|py| {
2509            let calls = client.client.runtime.getattr(py, "calls").unwrap();
2510            assert_eq!(calls.bind(py).len().unwrap(), 1);
2511            let call = calls.bind(py).get_item(0).unwrap();
2512            assert_eq!(
2513                call.get_item(0).unwrap().extract::<String>().unwrap(),
2514                "_generate_order_status_report"
2515            );
2516            let args = call.get_item(1).unwrap();
2517            assert_eq!(args.len().unwrap(), 1);
2518            let forwarded = args
2519                .get_item(0)
2520                .unwrap()
2521                .extract::<PyRef<'_, GenerateOrderStatusReport>>()
2522                .unwrap();
2523            assert_eq!(*forwarded, command);
2524        });
2525    }
2526
2527    #[rstest]
2528    #[case::success(false, false, false, None)]
2529    #[case::failure(true, false, false, Some("History unavailable"))]
2530    #[case::canceled(false, true, false, Some("Python data request canceled"))]
2531    #[case::disposed(true, false, true, None)]
2532    fn test_data_request_task_delivers_terminal_failure(
2533        native_execution_client: PythonExecutionClient,
2534        #[case] failed: bool,
2535        #[case] canceled: bool,
2536        #[case] disposed: bool,
2537        #[case] expected_reason: Option<&str>,
2538    ) {
2539        let client = native_execution_client.client;
2540        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
2541        client.output.state.lock().sender = Some(sender.into());
2542        let request_id = nautilus_core::UUID4::new();
2543        Python::attach(|py| {
2544            let runtime = client.runtime.bind(py);
2545            if failed {
2546                runtime
2547                    .setattr("failure", to_pyvalue_err("History unavailable").value(py))
2548                    .unwrap();
2549            }
2550
2551            runtime.setattr("cancelled", canceled).unwrap();
2552
2553            let request = RequestQuotes::new(
2554                InstrumentId::from("AUD/USD.SIM"),
2555                None,
2556                None,
2557                None,
2558                Some(client.client_id),
2559                request_id,
2560                UnixNanos::from(179),
2561                None,
2562            );
2563            client.request_quotes(request).unwrap();
2564            if disposed {
2565                client.output.invalidate();
2566            }
2567
2568            let event_loop = runtime.getattr("loop").unwrap();
2569            let tick = py
2570                .import("asyncio")
2571                .unwrap()
2572                .call_method1("sleep", (0,))
2573                .unwrap();
2574            event_loop
2575                .call_method1("run_until_complete", (tick,))
2576                .unwrap();
2577        });
2578
2579        if let Some(reason) = expected_reason {
2580            let DataEvent::RequestFailed(failure) = receiver.try_recv().unwrap() else {
2581                panic!("expected request failure");
2582            };
2583
2584            assert_eq!(failure.request_id, request_id);
2585            assert_eq!(failure.reason, reason);
2586            assert!(failure.response.is_none());
2587        }
2588
2589        assert!(matches!(
2590            receiver.try_recv(),
2591            Err(tokio::sync::mpsc::error::TryRecvError::Empty
2592                | tokio::sync::mpsc::error::TryRecvError::Disconnected)
2593        ));
2594    }
2595
2596    #[rstest]
2597    #[case(false)]
2598    #[case(true)]
2599    fn test_output_rebinding_is_rejected(#[case] disposed: bool) {
2600        Python::initialize();
2601        let output = ClientOutput::py_new();
2602
2603        if disposed {
2604            output.invalidate();
2605        } else {
2606            output.state.lock().bound = true;
2607        }
2608
2609        assert_eq!(
2610            output.bind().unwrap_err().to_string(),
2611            "RuntimeError: Client output cannot be rebound"
2612        );
2613    }
2614
2615    #[rstest]
2616    fn test_output_owner_thread_guards(
2617        execution_output: (
2618            ClientOutput,
2619            tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
2620        ),
2621    ) {
2622        let (output, _) = execution_output;
2623        let other = output.clone();
2624        let unbound = ClientOutput::py_new();
2625
2626        let errors = std::thread::spawn(move || {
2627            [
2628                other.sender().unwrap_err().to_string(),
2629                other.exec_sender().unwrap_err().to_string(),
2630                other.bind().unwrap_err().to_string(),
2631                unbound.bind().unwrap_err().to_string(),
2632            ]
2633        })
2634        .join()
2635        .unwrap();
2636
2637        assert_eq!(
2638            errors,
2639            [
2640                "RuntimeError: Client output requires its owner thread",
2641                "RuntimeError: Client output requires its owner thread",
2642                "RuntimeError: Client output requires its owner thread",
2643                "RuntimeError: Client output requires its owner thread",
2644            ]
2645        );
2646        assert!(output.exec_sender().is_ok());
2647    }
2648
2649    #[rstest]
2650    fn test_output_invalidation_removes_both_senders(
2651        execution_output: (
2652            ClientOutput,
2653            tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
2654        ),
2655    ) {
2656        let (output, _) = execution_output;
2657        let (sender, _) = tokio::sync::mpsc::unbounded_channel();
2658        output.state.lock().sender = Some(sender.into());
2659        output.invalidate();
2660        output.invalidate();
2661        assert_eq!(
2662            output.sender().unwrap_err().to_string(),
2663            "RuntimeError: Client output is not bound to an active node"
2664        );
2665        assert_eq!(
2666            output.exec_sender().unwrap_err().to_string(),
2667            "RuntimeError: Execution output is not bound to an active node"
2668        );
2669    }
2670
2671    #[rstest]
2672    #[case("submitted")]
2673    #[case("accepted")]
2674    #[case("canceled")]
2675    fn test_output_batches_preserve_events_and_reject_foreign_identity(
2676        execution_output: (
2677            ClientOutput,
2678            tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
2679        ),
2680        #[case] kind: &str,
2681    ) {
2682        let (output, mut receiver) = execution_output;
2683
2684        match kind {
2685            "submitted" => {
2686                let first = OrderSubmitted {
2687                    trader_id: TraderId::from("TESTER-001"),
2688                    account_id: AccountId::from("SIM-001"),
2689                    ..Default::default()
2690                };
2691
2692                let mut second = first.clone();
2693                second.client_order_id = ClientOrderId::from("SECOND");
2694                second.ts_event = 113.into();
2695                let events = vec![first, second];
2696                output.py_order_submitted_batch(events.clone()).unwrap();
2697
2698                let ExecutionEvent::OrderSubmittedBatch(batch) = receiver.try_recv().unwrap()
2699                else {
2700                    panic!("Expected submitted batch");
2701                };
2702
2703                assert_eq!(batch.events, events);
2704                let mut foreign = events[0].clone();
2705                foreign.account_id = AccountId::from("OTHER-001");
2706                assert_eq!(
2707                    output
2708                        .py_order_submitted_batch(vec![events[0].clone(), foreign])
2709                        .unwrap_err()
2710                        .to_string(),
2711                    "TypeError: Execution output identity does not match its owner"
2712                );
2713            }
2714            "accepted" => {
2715                let first = OrderAccepted {
2716                    trader_id: TraderId::from("TESTER-001"),
2717                    account_id: AccountId::from("SIM-001"),
2718                    ..Default::default()
2719                };
2720
2721                let mut second = first.clone();
2722                second.client_order_id = ClientOrderId::from("SECOND");
2723                second.ts_event = 127.into();
2724                let events = vec![first, second];
2725                output.py_order_accepted_batch(events.clone()).unwrap();
2726
2727                let ExecutionEvent::OrderAcceptedBatch(batch) = receiver.try_recv().unwrap() else {
2728                    panic!("Expected accepted batch");
2729                };
2730
2731                assert_eq!(batch.events, events);
2732                let mut foreign = events[0].clone();
2733                foreign.trader_id = TraderId::from("OTHER-001");
2734                assert_eq!(
2735                    output
2736                        .py_order_accepted_batch(vec![events[0].clone(), foreign])
2737                        .unwrap_err()
2738                        .to_string(),
2739                    "TypeError: Execution output identity does not match its owner"
2740                );
2741            }
2742            "canceled" => {
2743                let first = OrderCanceled {
2744                    trader_id: TraderId::from("TESTER-001"),
2745                    account_id: Some(AccountId::from("SIM-001")),
2746                    ..Default::default()
2747                };
2748
2749                let mut second = first.clone();
2750                second.client_order_id = ClientOrderId::from("SECOND");
2751                second.account_id = None;
2752                second.ts_event = 131.into();
2753                let events = vec![first, second];
2754                output.py_order_canceled_batch(events.clone()).unwrap();
2755
2756                let ExecutionEvent::OrderCanceledBatch(batch) = receiver.try_recv().unwrap() else {
2757                    panic!("Expected canceled batch");
2758                };
2759
2760                assert_eq!(batch.events, events);
2761                let mut foreign = events[0].clone();
2762                foreign.account_id = Some(AccountId::from("OTHER-001"));
2763                assert_eq!(
2764                    output
2765                        .py_order_canceled_batch(vec![events[0].clone(), foreign])
2766                        .unwrap_err()
2767                        .to_string(),
2768                    "TypeError: Execution output identity does not match its owner"
2769                );
2770            }
2771            _ => unreachable!(),
2772        }
2773
2774        assert!(matches!(
2775            receiver.try_recv(),
2776            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
2777        ));
2778    }
2779
2780    #[rstest]
2781    #[case("order_modify_denied", "OrderModifyDenied", false)]
2782    #[case("order_cancel_denied", "OrderCancelDenied", false)]
2783    #[case("order_modify_rejected", "OrderModifyRejected", true)]
2784    #[case("order_cancel_rejected", "OrderCancelRejected", true)]
2785    fn test_python_command_refusal_emission_preserves_fields(
2786        execution_output: (
2787            ClientOutput,
2788            tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
2789        ),
2790        #[case] method: &str,
2791        #[case] event_type: &str,
2792        #[case] rejected: bool,
2793        #[values(false, true)] with_cause: bool,
2794    ) {
2795        use nautilus_model::orders::{Order, OrderTestBuilder, stubs::TestOrderEventStubs};
2796        let (output, mut receiver) = execution_output;
2797        let mut order = OrderTestBuilder::new(OrderType::Limit)
2798            .trader_id(TraderId::from("TESTER-001"))
2799            .strategy_id(StrategyId::from("S-PY-019"))
2800            .client_order_id(ClientOrderId::from("O-PY-023"))
2801            .instrument_id(InstrumentId::from("AUD/USD.SIM"))
2802            .quantity(Quantity::from(17))
2803            .price(Price::from("0.71231"))
2804            .build();
2805        let account = AccountId::from("SIM-001");
2806        let cached_venue = VenueOrderId::from("V-CACHED-029");
2807        let explicit_venue = VenueOrderId::from("V-OVERRIDE-031");
2808        order
2809            .apply(TestOrderEventStubs::accepted(&order, account, cached_venue))
2810            .unwrap();
2811        let cause = UUID4::new();
2812        let reason = "refusal for Python caller";
2813
2814        let output = Python::attach(|py| {
2815            let py_order = order_any_to_pyobject(py, order.clone()).unwrap();
2816            let output = Py::new(py, output).unwrap();
2817
2818            let result = if rejected {
2819                if with_cause {
2820                    output.call_method1(
2821                        py,
2822                        method,
2823                        (py_order, explicit_venue, reason, 73u64, 79u64, cause),
2824                    )
2825                } else {
2826                    output.call_method1(
2827                        py,
2828                        method,
2829                        (py_order, explicit_venue, reason, 73u64, 79u64),
2830                    )
2831                }
2832            } else if with_cause {
2833                output.call_method1(py, method, (py_order, reason, 73u64, 79u64, cause))
2834            } else {
2835                output.call_method1(py, method, (py_order, reason, 73u64, 79u64))
2836            };
2837
2838            assert!(result.unwrap().is_none(py));
2839            output
2840        });
2841
2842        let ExecutionEvent::Order(event) = receiver.try_recv().unwrap() else {
2843            panic!("expected command refusal");
2844        };
2845
2846        let value = serde_json::to_value(&event).unwrap();
2847        let value = value
2848            .get(event_type.strip_prefix("Order").unwrap())
2849            .unwrap()
2850            .clone();
2851        let event_id = value.get("event_id").unwrap().as_str().unwrap();
2852        assert_ne!(UUID4::from(event_id), order.init_event().event_id);
2853        let mut expected = serde_json::json!({
2854            "type":event_type, "trader_id":order.trader_id(), "strategy_id":order.strategy_id(),
2855            "instrument_id":order.instrument_id(), "client_order_id":order.client_order_id(),
2856            "reason":reason, "event_id":event_id, "ts_event":UnixNanos::from(73), "ts_init":UnixNanos::from(79),
2857            "venue_order_id": if rejected { explicit_venue } else { cached_venue }, "account_id":account,
2858        });
2859
2860        if rejected {
2861            expected["reconciliation"] = serde_json::json!(false);
2862        }
2863
2864        if with_cause {
2865            expected["causation_id"] = serde_json::json!(cause);
2866        }
2867
2868        assert_eq!(value, expected);
2869        assert!(matches!(
2870            receiver.try_recv(),
2871            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
2872        ));
2873        drop(output);
2874    }
2875
2876    #[rstest]
2877    fn test_closed_execution_channel_reports_failure(
2878        execution_output: (
2879            ClientOutput,
2880            tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
2881        ),
2882    ) {
2883        let (output, receiver) = execution_output;
2884        drop(receiver);
2885
2886        let event = OrderSubmitted {
2887            trader_id: TraderId::from("TESTER-001"),
2888            account_id: AccountId::from("SIM-001"),
2889            ..Default::default()
2890        };
2891
2892        let error = output
2893            .send_exec(ExecutionEvent::Order(OrderEventAny::Submitted(event)))
2894            .unwrap_err();
2895        assert_eq!(error.to_string(), "RuntimeError: channel closed");
2896    }
2897
2898    #[rstest]
2899    fn test_cache_view_rejects_incompatible_borrow_and_recovers() {
2900        Python::initialize();
2901
2902        let cache = Rc::new(RefCell::new(Cache::default()));
2903        let id = CACHE_ID.fetch_add(1, Ordering::Relaxed);
2904        CLIENT_CACHES.with_borrow_mut(|caches| caches.insert(id, CacheView::new(cache.clone())));
2905
2906        let view = PyClientCache { id };
2907        let held = cache.borrow_mut();
2908        assert!(view.py_instrument_ids(None).is_err());
2909        drop(held);
2910        assert_eq!(
2911            view.py_instrument_ids(None).unwrap(),
2912            Vec::<InstrumentId>::new()
2913        );
2914        CLIENT_CACHES.with_borrow_mut(|caches| caches.remove(&id));
2915        assert_eq!(
2916            view.py_instrument_ids(None).unwrap_err().to_string(),
2917            "RuntimeError: Client cache is disposed or accessed from a foreign thread"
2918        );
2919    }
2920    #[rstest]
2921    #[case(None)]
2922    #[case(Some(Price::from("123.456")))]
2923    fn test_option_reference_request_and_response_preserve_identity(
2924        native_execution_client: PythonExecutionClient,
2925        #[case] price: Option<Price>,
2926    ) {
2927        use nautilus_common::messages::data::DataResponse;
2928        use nautilus_model::identifiers::OptionSeriesId;
2929
2930        use crate::python::client::responses::PyOptionChainReferencePriceResponse;
2931
2932        let client = native_execution_client.client;
2933
2934        let series =
2935            OptionSeriesId::new_derived(Venue::from("SIM"), "BTC".into(), "USD".into(), 197.into());
2936
2937        let request = RequestOptionChainReferencePrice::new(
2938            series,
2939            InstrumentId::from("BTC/USD.SIM"),
2940            Some(ClientId::from("SIM")),
2941            nautilus_core::UUID4::new(),
2942            199.into(),
2943            None,
2944        );
2945        client
2946            .request_option_chain_reference_price(request.clone())
2947            .unwrap();
2948        Python::attach(|py| {
2949            let calls = client.runtime.getattr(py, "calls").unwrap();
2950            assert_eq!(calls.bind(py).len().unwrap(), 1);
2951            let call = calls.bind(py).get_item(0).unwrap();
2952            assert_eq!(
2953                call.get_item(0).unwrap().extract::<String>().unwrap(),
2954                "_request_option_chain_reference_price"
2955            );
2956            let args = call.get_item(1).unwrap();
2957            assert_eq!(args.len().unwrap(), 1);
2958            let forwarded = args
2959                .get_item(0)
2960                .unwrap()
2961                .extract::<PyRef<'_, PyRequestOptionChainReferencePrice>>()
2962                .unwrap();
2963            assert_eq!(
2964                args.get_item(0)
2965                    .unwrap()
2966                    .getattr("ts_init")
2967                    .unwrap()
2968                    .extract::<u64>()
2969                    .unwrap(),
2970                199
2971            );
2972            assert_eq!(forwarded.request.series_id, request.series_id);
2973            assert_eq!(forwarded.request.instrument_id, request.instrument_id);
2974            assert_eq!(forwarded.request.client_id, request.client_id);
2975            assert_eq!(forwarded.request.request_id, request.request_id);
2976            assert_eq!(forwarded.request.ts_init, request.ts_init);
2977            assert_eq!(forwarded.request.params, request.params);
2978
2979            let output = ClientOutput::py_new();
2980            let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
2981            {
2982                let mut state = output.state.lock();
2983                state.sender = Some(sender.into());
2984                state.client_id = Some(ClientId::from("SIM"));
2985            }
2986
2987            let response = py
2988                .get_type::<PyOptionChainReferencePriceResponse>()
2989                .call1((
2990                    ClientId::from("SIM"),
2991                    series,
2992                    price,
2993                    request.request_id,
2994                    211_u64,
2995                ))
2996                .unwrap();
2997            output.py_response(&response, None, None).unwrap();
2998
2999            let DataEvent::ResponseEnvelope(envelope) = receiver.try_recv().unwrap() else {
3000                panic!("Expected completed response");
3001            };
3002
3003            assert!(envelope.completed());
3004            assert_eq!(envelope.failure_reason(), None);
3005
3006            let Some(DataResponse::OptionChainReferencePrice(response)) = envelope.response()
3007            else {
3008                panic!("Expected option reference response");
3009            };
3010
3011            assert_eq!(response.client_id, ClientId::from("SIM"));
3012            assert_eq!(response.series_id, series);
3013            assert_eq!(response.price, price);
3014            assert_eq!(response.correlation_id, request.request_id);
3015            assert_eq!(response.ts_init, UnixNanos::from(211));
3016            assert_eq!(response.params, None);
3017            let foreign = py
3018                .get_type::<PyOptionChainReferencePriceResponse>()
3019                .call1((
3020                    ClientId::from("OTHER"),
3021                    series,
3022                    price,
3023                    request.request_id,
3024                    223_u64,
3025                ))
3026                .unwrap();
3027            assert_eq!(
3028                output
3029                    .py_response(&foreign, None, None)
3030                    .unwrap_err()
3031                    .to_string(),
3032                "TypeError: Response client identity does not match its owner"
3033            );
3034            assert!(matches!(
3035                receiver.try_recv(),
3036                Err(tokio::sync::mpsc::error::TryRecvError::Empty)
3037            ));
3038        });
3039    }
3040
3041    #[rstest]
3042    #[case::intermediate(Some(false), false, false)]
3043    #[case::completed(Some(true), false, false)]
3044    #[case::provenance(None, true, false)]
3045    #[case::partial_failure(None, false, true)]
3046    fn test_data_output_preserves_completion_and_partial_payload(
3047        #[case] completed: Option<bool>,
3048        #[case] provenance: bool,
3049        #[case] failed: bool,
3050    ) {
3051        use crate::python::client::responses::PyQuotesResponse;
3052        Python::initialize();
3053        let output = ClientOutput::py_new();
3054        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
3055        let client_id = ClientId::from("HISTORY");
3056        let root = nautilus_core::UUID4::new();
3057        let source = provenance.then(nautilus_core::UUID4::new);
3058        let instrument_id = InstrumentId::from("AUD/USD.SIM");
3059
3060        let quote = QuoteTick::new(
3061            instrument_id,
3062            Price::from("1.00000"),
3063            Price::from("1.00010"),
3064            Quantity::from("13"),
3065            Quantity::from("17"),
3066            UnixNanos::from(19),
3067            UnixNanos::from(23),
3068        );
3069        {
3070            let mut state = output.state.lock();
3071            state.sender = Some(sender.into());
3072            state.client_id = Some(client_id);
3073        }
3074
3075        Python::attach(|py| {
3076            let response = py
3077                .get_type::<PyQuotesResponse>()
3078                .call1((client_id, instrument_id, vec![quote], root, 227_u64))
3079                .unwrap();
3080
3081            if failed {
3082                output
3083                    .py_request_failed(root, "Missing sibling".to_owned(), Some(&response))
3084                    .unwrap();
3085            } else {
3086                output.py_response(&response, completed, source).unwrap();
3087            }
3088        });
3089
3090        let event = receiver.try_recv().unwrap();
3091
3092        let response = match event {
3093            DataEvent::ResponseEnvelope(envelope) => {
3094                assert_eq!(envelope.correlation_id(), &root);
3095                assert_eq!(envelope.completed(), completed.unwrap_or(true));
3096                assert_eq!(envelope.sub_correlation_id(), source);
3097                assert_eq!(envelope.failure_reason(), None);
3098                envelope.response().unwrap().clone()
3099            }
3100            DataEvent::RequestFailed(failure) if failed => {
3101                assert_eq!(failure.request_id, root);
3102                assert_eq!(failure.reason, "Missing sibling");
3103                failure.response.unwrap()
3104            }
3105            _ => panic!("expected envelope or partial failure"),
3106        };
3107
3108        let DataResponse::Quotes(response) = response else {
3109            panic!("expected quotes");
3110        };
3111
3112        assert_eq!(response.correlation_id, root);
3113        assert_eq!(response.client_id, client_id);
3114        assert_eq!(response.instrument_ids, vec![instrument_id]);
3115        assert_eq!(response.data.as_ref(), &vec![quote]);
3116        assert_eq!(response.start, None);
3117        assert_eq!(response.end, None);
3118        assert_eq!(response.ts_init, UnixNanos::from(227));
3119        assert_eq!(response.params, None);
3120        assert_eq!(
3121            receiver.try_recv().unwrap_err(),
3122            tokio::sync::mpsc::error::TryRecvError::Empty
3123        );
3124    }
3125
3126    #[rstest]
3127    #[case::foreign_client(true)]
3128    #[case::foreign_request(false)]
3129    fn test_data_output_rejects_foreign_partial_response(#[case] foreign_client: bool) {
3130        use crate::python::client::responses::PyQuotesResponse;
3131        Python::initialize();
3132        let output = ClientOutput::py_new();
3133        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
3134        let root = nautilus_core::UUID4::new();
3135        {
3136            let mut state = output.state.lock();
3137            state.sender = Some(sender.into());
3138            state.client_id = Some(ClientId::from("HISTORY"));
3139        }
3140
3141        Python::attach(|py| {
3142            let client_id = ClientId::from(if foreign_client { "OTHER" } else { "HISTORY" });
3143
3144            let correlation_id = if foreign_client {
3145                root
3146            } else {
3147                nautilus_core::UUID4::new()
3148            };
3149
3150            let response = py
3151                .get_type::<PyQuotesResponse>()
3152                .call1((
3153                    client_id,
3154                    InstrumentId::from("AUD/USD.SIM"),
3155                    Vec::<QuoteTick>::new(),
3156                    correlation_id,
3157                    229_u64,
3158                ))
3159                .unwrap();
3160            assert_eq!(
3161                output
3162                    .py_request_failed(root, "History failed".to_owned(), Some(&response))
3163                    .unwrap_err()
3164                    .to_string(),
3165                "TypeError: Partial response identity does not match the failed request"
3166            );
3167        });
3168
3169        assert_eq!(
3170            receiver.try_recv().unwrap_err(),
3171            tokio::sync::mpsc::error::TryRecvError::Empty
3172        );
3173    }
3174
3175    #[rstest]
3176    fn test_native_account_output_preserves_fields_and_owner_clock(
3177        mut native_execution_client: PythonExecutionClient,
3178        execution_output: (
3179            ClientOutput,
3180            tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
3181        ),
3182    ) {
3183        let (output, mut receiver) = execution_output;
3184        native_execution_client.client.output = output;
3185        let balances = vec![AccountBalance::new(
3186            Money::from("1000 USD"),
3187            Money::from("17 USD"),
3188            Money::from("983 USD"),
3189        )];
3190        native_execution_client
3191            .generate_account_state(balances.clone(), vec![], false, 233.into(), None)
3192            .unwrap();
3193
3194        let ExecutionEvent::Account(event) = receiver.try_recv().unwrap() else {
3195            panic!("Expected account state");
3196        };
3197
3198        assert_eq!(event.account_id, AccountId::from("SIM-001"));
3199        assert_eq!(event.account_type, AccountType::Cash);
3200        assert_eq!(event.base_currency, None);
3201        assert_eq!(event.balances, balances);
3202        assert_eq!(event.margins, vec![]);
3203        assert!(!event.is_reported);
3204        assert_eq!(event.ts_event, UnixNanos::from(233));
3205        assert_eq!(event.ts_init, UnixNanos::from(0));
3206        assert_eq!(event.info, None);
3207        Python::attach(|py| {
3208            let owned = Py::new(py, event.clone()).unwrap().into_any();
3209            native_execution_client
3210                .client
3211                .output
3212                .py_event(py, owned)
3213                .unwrap();
3214        });
3215
3216        let ExecutionEvent::Account(forwarded) = receiver.try_recv().unwrap() else {
3217            panic!("Expected forwarded account state");
3218        };
3219
3220        assert_eq!(forwarded, event);
3221    }
3222
3223    #[rstest]
3224    fn test_native_client_identity_and_single_use_lifecycle(
3225        mut native_execution_client: PythonExecutionClient,
3226    ) {
3227        let client = &mut native_execution_client;
3228        assert_eq!(client.client_id(), ClientId::from("SIM"));
3229        assert_eq!(client.account_id(), AccountId::from("SIM-001"));
3230        assert_eq!(client.venue(), Venue::from("SIM"));
3231        assert_eq!(client.oms_type(), OmsType::Netting);
3232        assert_eq!(client.position_reconciliation_tolerance(), Decimal::ZERO);
3233        assert_eq!(
3234            client.reset().unwrap_err().to_string(),
3235            "Python clients are single-use"
3236        );
3237        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
3238        nautilus_common::live::runner::replace_data_event_sender(sender);
3239        assert!(client.start().is_ok());
3240        assert!(client.stop().is_ok());
3241        assert!(client.dispose().is_ok());
3242        assert_eq!(
3243            client.client.reset().unwrap_err().to_string(),
3244            "Python clients are single-use"
3245        );
3246        assert_eq!(
3247            client.client.start().unwrap_err().to_string(),
3248            "RuntimeError: Client output cannot be rebound"
3249        );
3250        assert!(client.client.stop().is_ok());
3251        assert!(client.client.dispose().is_ok());
3252        assert_eq!(client.client.venue(), Some(Venue::from("SIM")));
3253        assert!(client.client.is_disconnected());
3254
3255        let cache = Rc::new(RefCell::new(Cache::default()));
3256
3257        client.cache = CacheView::new(cache.clone());
3258        assert_eq!(client.get_account(), None);
3259        let held = cache.borrow_mut();
3260        assert_eq!(client.get_account(), None);
3261        drop(held);
3262        let account = AccountAny::default();
3263        client.identity.account_id = account.id();
3264        cache.borrow_mut().add_account(account.clone()).unwrap();
3265        assert_eq!(client.get_account(), Some(account));
3266    }
3267
3268    #[rstest]
3269    #[case("true")]
3270    #[case("false")]
3271    #[case("wrong_type")]
3272    #[case("exception")]
3273    fn test_native_coverage_hooks_fail_closed_and_preserve_arguments(
3274        native_execution_client: PythonExecutionClient,
3275        #[case] mode: &str,
3276    ) {
3277        let client = native_execution_client;
3278        Python::attach(|py| {
3279            let runtime = client.client.runtime.bind(py);
3280
3281            match mode {
3282                "true" => runtime.setattr("result", true).unwrap(),
3283                "false" => runtime.setattr("result", false).unwrap(),
3284                "wrong_type" => runtime.setattr("result", "invalid").unwrap(),
3285                "exception" => runtime
3286                    .setattr("failure", to_pyvalue_err("Coverage unavailable").value(py))
3287                    .unwrap(),
3288                _ => unreachable!(),
3289            }
3290        });
3291
3292        let venue = Venue::from("OTHER");
3293        let instrument_id = InstrumentId::from("AUD/USD.SIM");
3294        assert_eq!(client.handles_order_venue(venue), mode == "true");
3295        assert_eq!(
3296            client.provides_bulk_position_coverage(instrument_id),
3297            mode == "true"
3298        );
3299        Python::attach(|py| {
3300            let calls = client.client.runtime.getattr(py, "calls").unwrap();
3301            assert_eq!(calls.bind(py).len().unwrap(), 2);
3302            let first = calls.bind(py).get_item(0).unwrap();
3303            assert_eq!(
3304                first.get_item(0).unwrap().extract::<String>().unwrap(),
3305                "venue"
3306            );
3307            assert_eq!(
3308                first.get_item(1).unwrap().extract::<Venue>().unwrap(),
3309                venue
3310            );
3311            let second = calls.bind(py).get_item(1).unwrap();
3312            assert_eq!(
3313                second.get_item(0).unwrap().extract::<String>().unwrap(),
3314                "positions"
3315            );
3316            assert_eq!(
3317                second
3318                    .get_item(1)
3319                    .unwrap()
3320                    .extract::<InstrumentId>()
3321                    .unwrap(),
3322                instrument_id
3323            );
3324        });
3325    }
3326
3327    #[rstest]
3328    #[case("none")]
3329    #[case("money")]
3330    #[case("exception")]
3331    fn test_native_commission_hook_preserves_inputs_and_propagates_failure(
3332        native_execution_client: PythonExecutionClient,
3333        #[case] mode: &str,
3334    ) {
3335        let client = native_execution_client;
3336        let commission = Money::from("0.17 USD");
3337        Python::attach(|py| {
3338            let runtime = client.client.runtime.bind(py);
3339
3340            if mode == "money" {
3341                runtime.setattr("result", commission).unwrap();
3342            } else if mode == "exception" {
3343                runtime
3344                    .setattr("failure", to_pyvalue_err("Fee unavailable").value(py))
3345                    .unwrap();
3346            }
3347        });
3348
3349        let instrument =
3350            InstrumentAny::CurrencyPair(nautilus_model::instruments::stubs::audusd_sim());
3351        let quantity = Quantity::from("17");
3352        let price = Price::from("0.71231");
3353        let result =
3354            client.calculate_commission(&instrument, quantity, price, LiquiditySide::Maker);
3355
3356        if mode == "exception" {
3357            assert_eq!(
3358                result.unwrap_err().to_string(),
3359                "ValueError: Fee unavailable"
3360            );
3361        } else {
3362            assert_eq!(
3363                result.unwrap(),
3364                if mode == "money" {
3365                    Some(commission)
3366                } else {
3367                    None
3368                }
3369            );
3370        }
3371
3372        Python::attach(|py| {
3373            let calls = client.client.runtime.getattr(py, "calls").unwrap();
3374            assert_eq!(calls.bind(py).len().unwrap(), 1);
3375            let call = calls.bind(py).get_item(0).unwrap();
3376            assert_eq!(
3377                call.get_item(0).unwrap().extract::<String>().unwrap(),
3378                "commission"
3379            );
3380            let args = call.get_item(1).unwrap();
3381            assert_eq!(args.len().unwrap(), 4);
3382            assert_eq!(
3383                pyobject_to_instrument_any(py, args.get_item(0).unwrap().unbind()).unwrap(),
3384                instrument
3385            );
3386            assert_eq!(
3387                args.get_item(1).unwrap().extract::<Quantity>().unwrap(),
3388                quantity
3389            );
3390            assert_eq!(args.get_item(2).unwrap().extract::<Price>().unwrap(), price);
3391            assert_eq!(
3392                args.get_item(3)
3393                    .unwrap()
3394                    .extract::<LiquiditySide>()
3395                    .unwrap(),
3396                LiquiditySide::Maker
3397            );
3398        });
3399    }
3400    macro_rules! report_sequence_test {
3401        ($name:ident, $method:ident, $command_type:ty, [$($borrow:tt)*], $command:expr, $report:expr) => {
3402            #[rstest]
3403            #[case("empty")]
3404            #[case("valid")]
3405            #[case("foreign")]
3406            #[case("wrong_type")]
3407            #[tokio::test]
3408            async fn $name(native_execution_client: PythonExecutionClient, #[case] mode: &str) {
3409                let client = native_execution_client;
3410                let mut command = $command;
3411                command.correlation_id = Some(nautilus_core::UUID4::new());
3412                command.causation_id = Some(nautilus_core::UUID4::new());
3413                command.log_receipt_level = LogLevel::Debug;
3414                let params = Params::new([("probe".to_owned(), serde_json::Value::from(17))].into());
3415                command.params = Some(params);
3416                let first = $report;
3417                let mut second = first.clone();
3418                second.ts_init = 251.into();
3419                let expected = if mode == "empty" { vec![] } else { vec![first, second] };
3420                Python::attach(|py| {
3421                    if mode != "wrong_type" {
3422                        let mut reports = expected.clone();
3423                        if mode == "foreign" {
3424                            reports[1].account_id = AccountId::from("OTHER-001");
3425                        }
3426                        let reports = reports.into_iter().map(|report| Py::new(py, report).unwrap()).collect::<Vec<_>>();
3427                        client.client.runtime.bind(py).setattr("result", reports).unwrap();
3428                    }
3429                });
3430                let result = client.$method($($borrow)* command.clone()).await;
3431                if mode == "foreign" {
3432                    assert_eq!(result.unwrap_err().to_string(), "Report account identity does not match its client");
3433                } else if mode == "wrong_type" {
3434                    assert!(result.unwrap_err().to_string().starts_with("TypeError:"));
3435                } else {
3436                    assert_eq!(result.unwrap(), expected);
3437                }
3438                Python::attach(|py| {
3439                    let calls = client.client.runtime.getattr(py, "calls").unwrap();
3440                    assert_eq!(calls.bind(py).len().unwrap(), 1);
3441                    let call = calls.bind(py).get_item(0).unwrap();
3442                    assert_eq!(call.get_item(0).unwrap().extract::<String>().unwrap(), concat!("_", stringify!($method)));
3443                    let args = call.get_item(1).unwrap();
3444                    assert_eq!(args.len().unwrap(), 1);
3445                    let argument = args.get_item(0).unwrap();
3446                    let forwarded = argument.extract::<PyRef<'_, $command_type>>().unwrap();
3447                    assert_eq!(*forwarded, command);
3448                    assert_eq!(argument.getattr("command_id").unwrap().extract::<nautilus_core::UUID4>().unwrap(), command.command_id);
3449                    assert_eq!(argument.getattr("ts_init").unwrap().extract::<u64>().unwrap(), 241);
3450                    assert_eq!(argument.getattr("correlation_id").unwrap().extract::<Option<nautilus_core::UUID4>>().unwrap(), command.correlation_id);
3451                    assert_eq!(argument.getattr("causation_id").unwrap().extract::<Option<nautilus_core::UUID4>>().unwrap(), command.causation_id);
3452                    assert_eq!(argument.getattr("instrument_id").unwrap().extract::<Option<InstrumentId>>().unwrap(), command.instrument_id);
3453                    assert_eq!(argument.getattr("start").unwrap().extract::<u64>().unwrap(), 229);
3454                    assert_eq!(argument.getattr("end").unwrap().extract::<u64>().unwrap(), 239);
3455                    assert_eq!(argument.getattr("log_receipt_level").unwrap().extract::<LogLevel>().unwrap(), command.log_receipt_level);
3456                    let params = argument.getattr("params").unwrap();
3457                    assert_eq!(params.len().unwrap(), 1);
3458                    assert_eq!(params.get_item("probe").unwrap().extract::<i64>().unwrap(), 17);
3459                });
3460            }
3461        };
3462    }
3463
3464    report_sequence_test!(
3465        test_order_report_sequences_validate_every_member,
3466        generate_order_status_reports, GenerateOrderStatusReports, [&],
3467        GenerateOrderStatusReports::new(nautilus_core::UUID4::new(), 241.into(), true,
3468            Some(InstrumentId::from("AUD/USD.SIM")), Some(229.into()), Some(239.into()), None, None),
3469        order_report()
3470    );
3471
3472    report_sequence_test!(
3473        test_fill_report_sequences_validate_every_member,
3474        generate_fill_reports,
3475        GenerateFillReports,
3476        [],
3477        GenerateFillReports::new(
3478            nautilus_core::UUID4::new(),
3479            241.into(),
3480            Some(InstrumentId::from("AUD/USD.SIM")),
3481            Some(VenueOrderId::from("VENUE-173")),
3482            Some(229.into()),
3483            Some(239.into()),
3484            None,
3485            None
3486        ),
3487        fill_report()
3488    );
3489
3490    report_sequence_test!(
3491        test_position_report_sequences_validate_every_member,
3492        generate_position_status_reports, GeneratePositionStatusReports, [&],
3493        GeneratePositionStatusReports::new(nautilus_core::UUID4::new(), 241.into(),
3494            Some(InstrumentId::from("AUD/USD.SIM")), Some(229.into()), Some(239.into()), None, None),
3495        position_report()
3496    );
3497    #[rstest]
3498    #[case("order")]
3499    #[case("fill")]
3500    #[case("position")]
3501    #[case("mass")]
3502    #[case("order_with_fills")]
3503    fn test_report_output_preserves_each_payload_family(
3504        execution_output: (
3505            ClientOutput,
3506            tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
3507        ),
3508        order_report: OrderStatusReport,
3509        fill_report: FillReport,
3510        position_report: PositionStatusReport,
3511        #[case] kind: &str,
3512    ) {
3513        let (output, mut receiver) = execution_output;
3514        {
3515            let mut state = output.state.lock();
3516            state.client_id = Some(ClientId::from("SIM"));
3517            state.venue = Some(Venue::from("SIM"));
3518        }
3519
3520        let mut mass = ExecutionMassStatus::new(
3521            ClientId::from("SIM"),
3522            AccountId::from("SIM-001"),
3523            Venue::from("SIM"),
3524            257.into(),
3525            None,
3526        );
3527        mass.add_order_reports(vec![order_report.clone()]);
3528        mass.add_fill_reports(vec![fill_report.clone()]);
3529        mass.add_position_reports(vec![position_report.clone()]);
3530        Python::attach(|py| {
3531            let report = match kind {
3532                "order" | "order_with_fills" => {
3533                    Py::new(py, order_report.clone()).unwrap().into_any()
3534                }
3535                "fill" => Py::new(py, fill_report.clone()).unwrap().into_any(),
3536                "position" => Py::new(py, position_report.clone()).unwrap().into_any(),
3537                "mass" => Py::new(py, mass.clone()).unwrap().into_any(),
3538                _ => unreachable!(),
3539            };
3540
3541            output
3542                .py_report(
3543                    report.bind(py),
3544                    if kind == "order_with_fills" {
3545                        Some(vec![fill_report.clone()])
3546                    } else {
3547                        None
3548                    },
3549                )
3550                .unwrap();
3551        });
3552
3553        let ExecutionEvent::Report(report) = receiver.try_recv().unwrap() else {
3554            panic!("Expected execution report");
3555        };
3556
3557        match (kind, report) {
3558            ("order", ExecutionReport::Order(report)) => assert_eq!(*report, order_report),
3559            ("fill", ExecutionReport::Fill(report)) => assert_eq!(*report, fill_report),
3560            ("position", ExecutionReport::Position(report)) => assert_eq!(*report, position_report),
3561            ("mass", ExecutionReport::MassStatus(report)) => assert_eq!(*report, mass),
3562            ("order_with_fills", ExecutionReport::OrderWithFills(report, fills)) => {
3563                assert_eq!(*report, order_report);
3564                assert_eq!(fills, vec![fill_report]);
3565            }
3566            _ => panic!("Wrong execution report variant"),
3567        }
3568    }
3569
3570    #[fixture]
3571    fn order_report() -> OrderStatusReport {
3572        OrderStatusReport::new(
3573            AccountId::from("SIM-001"),
3574            InstrumentId::from("AUD/USD.SIM"),
3575            Some(ClientOrderId::from("ORDER-167")),
3576            VenueOrderId::from("VENUE-173"),
3577            Some(OrderSide::Buy),
3578            OrderType::Limit,
3579            TimeInForce::Gtc,
3580            OrderStatus::Accepted,
3581            Quantity::from("17"),
3582            Quantity::from("3"),
3583            149.into(),
3584            151.into(),
3585            157.into(),
3586            None,
3587        )
3588    }
3589
3590    #[fixture]
3591    fn fill_report() -> FillReport {
3592        FillReport::new(
3593            AccountId::from("SIM-001"),
3594            InstrumentId::from("AUD/USD.SIM"),
3595            VenueOrderId::from("VENUE-173"),
3596            TradeId::from("TRADE-179"),
3597            OrderSide::Buy,
3598            Quantity::from("3"),
3599            Price::from("0.71231"),
3600            Money::from("0.17 USD"),
3601            LiquiditySide::Maker,
3602            Some(ClientOrderId::from("ORDER-167")),
3603            Some(PositionId::from("POSITION-181")),
3604            191.into(),
3605            193.into(),
3606            None,
3607        )
3608    }
3609
3610    #[fixture]
3611    fn position_report() -> PositionStatusReport {
3612        PositionStatusReport::new(
3613            AccountId::from("SIM-001"),
3614            InstrumentId::from("AUD/USD.SIM"),
3615            PositionSide::Short,
3616            Quantity::from("17"),
3617            191.into(),
3618            193.into(),
3619            None,
3620            Some(PositionId::from("POSITION-181")),
3621            Some(Decimal::new(71231, 5)),
3622        )
3623    }
3624    #[rstest]
3625    #[case("none")]
3626    #[case("valid")]
3627    #[case("client")]
3628    #[case("account")]
3629    #[case("venue")]
3630    #[case("order")]
3631    #[case("fill")]
3632    #[case("position")]
3633    #[case("wrong_type")]
3634    #[tokio::test]
3635    async fn test_mass_report_checks_outer_and_nested_identity(
3636        native_execution_client: PythonExecutionClient,
3637        mut order_report: OrderStatusReport,
3638        mut fill_report: FillReport,
3639        mut position_report: PositionStatusReport,
3640        #[case] kind: &str,
3641    ) {
3642        let client = native_execution_client;
3643        let account = AccountId::from("OTHER-001");
3644
3645        if kind == "order" {
3646            order_report.account_id = account;
3647        }
3648
3649        if kind == "fill" {
3650            fill_report.account_id = account;
3651        }
3652
3653        if kind == "position" {
3654            position_report.account_id = account;
3655        }
3656
3657        let mut mass = ExecutionMassStatus::new(
3658            ClientId::from(if kind == "client" { "OTHER" } else { "SIM" }),
3659            if kind == "account" {
3660                account
3661            } else {
3662                AccountId::from("SIM-001")
3663            },
3664            Venue::from(if kind == "venue" { "OTHER" } else { "SIM" }),
3665            263.into(),
3666            None,
3667        );
3668
3669        mass.add_order_reports(vec![order_report]);
3670        mass.add_fill_reports(vec![fill_report]);
3671        mass.add_position_reports(vec![position_report]);
3672        Python::attach(|py| {
3673            if kind == "wrong_type" {
3674                client
3675                    .client
3676                    .runtime
3677                    .bind(py)
3678                    .setattr("result", 17)
3679                    .unwrap();
3680            } else if kind != "none" {
3681                client
3682                    .client
3683                    .runtime
3684                    .bind(py)
3685                    .setattr("result", Py::new(py, mass.clone()).unwrap())
3686                    .unwrap();
3687            }
3688        });
3689
3690        let result = client.generate_mass_status(Some(23)).await;
3691
3692        match kind {
3693            "none" => assert_eq!(result.unwrap(), None),
3694            "valid" => assert_eq!(result.unwrap(), Some(mass)),
3695            "wrong_type" => assert!(result.unwrap_err().to_string().starts_with("TypeError:")),
3696            _ => assert_eq!(
3697                result.unwrap_err().to_string(),
3698                "Mass status identity does not match its client"
3699            ),
3700        }
3701
3702        Python::attach(|py| {
3703            let calls = client.client.runtime.getattr(py, "calls").unwrap();
3704            assert_eq!(calls.bind(py).len().unwrap(), 1);
3705            let call = calls.bind(py).get_item(0).unwrap();
3706            assert_eq!(
3707                call.get_item(0).unwrap().extract::<String>().unwrap(),
3708                "_generate_mass_status"
3709            );
3710            assert_eq!(
3711                call.get_item(1).unwrap().extract::<(u64,)>().unwrap(),
3712                (23,)
3713            );
3714        });
3715    }
3716    #[rstest]
3717    fn test_cache_bytes_and_order_lists_are_owned_snapshots() {
3718        Python::initialize();
3719
3720        let cache = Rc::new(RefCell::new(Cache::default()));
3721        let id = CACHE_ID.fetch_add(1, Ordering::Relaxed);
3722        CLIENT_CACHES.with_borrow_mut(|caches| caches.insert(id, CacheView::new(cache.clone())));
3723
3724        let view = PyClientCache { id };
3725
3726        let list = OrderList::new(
3727            OrderListId::from("OL-SNAPSHOT"),
3728            InstrumentId::from("AUD/USD.SIM"),
3729            StrategyId::from("S-SNAPSHOT"),
3730            vec![
3731                ClientOrderId::from("O-FIRST"),
3732                ClientOrderId::from("O-SECOND"),
3733            ],
3734            UnixNanos::from(173),
3735        );
3736        cache
3737            .borrow_mut()
3738            .add("probe", vec![0, 17, 255].into())
3739            .unwrap();
3740        cache.borrow_mut().add_order_list(list.clone()).unwrap();
3741        let mut bytes = view.py_get("probe").unwrap().unwrap();
3742        let snapshot = view.py_order_list(list.id).unwrap().unwrap();
3743        bytes[1] = 29;
3744        cache
3745            .borrow_mut()
3746            .add("probe", vec![31, 0, 127].into())
3747            .unwrap();
3748        assert_eq!(bytes, vec![0, 29, 255]);
3749        assert_eq!(view.py_get("probe").unwrap(), Some(vec![31, 0, 127]));
3750        assert_eq!(snapshot, list);
3751        assert_eq!(view.py_order_list(list.id).unwrap(), Some(list));
3752        assert_eq!(view.py_get("missing").unwrap(), None);
3753        assert_eq!(
3754            view.py_order_list(OrderListId::from("OL-MISSING")).unwrap(),
3755            None
3756        );
3757        CLIENT_CACHES.with_borrow_mut(|caches| caches.remove(&id));
3758    }
3759    #[rstest]
3760    fn test_factory_metadata() {
3761        Python::initialize();
3762        Python::attach(|py| {
3763            let data = PythonDataFactory {
3764                factory: py.None(),
3765                clients: PythonClients::default(),
3766            };
3767
3768            let execution = PythonExecutionFactory {
3769                factory: py.None(),
3770                clients: PythonClients::default(),
3771            };
3772
3773            assert_eq!(data.name(), "Python");
3774            assert_eq!(data.config_type(), "DataClientConfig");
3775            assert_eq!(execution.name(), "Python");
3776            assert_eq!(execution.config_type(), "ExecutionClientConfig");
3777        });
3778    }
3779
3780    #[rstest]
3781    #[case(None)]
3782    #[case(Some(nautilus_core::UUID4::new()))]
3783    fn test_subscription_metadata_preserves_timestamp_and_correlation(
3784        #[case] correlation_id: Option<nautilus_core::UUID4>,
3785    ) {
3786        Python::initialize();
3787        Python::attach(|py| {
3788            let command_id = nautilus_core::UUID4::new();
3789
3790            let command = SubscribeQuotes::new(
3791                InstrumentId::from("AUD/USD.SIM"),
3792                Some(ClientId::from("SIM")),
3793                Some(Venue::from("SIM")),
3794                command_id,
3795                283.into(),
3796                correlation_id,
3797                None,
3798            );
3799            let command_py = Py::new(py, command).unwrap();
3800            assert_eq!(
3801                command_py
3802                    .getattr(py, "command_id")
3803                    .unwrap()
3804                    .extract::<nautilus_core::UUID4>(py)
3805                    .unwrap(),
3806                command_id
3807            );
3808            assert_eq!(
3809                command_py
3810                    .getattr(py, "ts_init")
3811                    .unwrap()
3812                    .extract::<u64>(py)
3813                    .unwrap(),
3814                283
3815            );
3816            assert_eq!(
3817                command_py
3818                    .getattr(py, "correlation_id")
3819                    .unwrap()
3820                    .extract::<Option<nautilus_core::UUID4>>(py)
3821                    .unwrap(),
3822                correlation_id
3823            );
3824        });
3825    }
3826}