Skip to main content

nautilus_trading/strategy/
api.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//! User-facing strategy APIs.
17
18use std::cell::RefCell;
19
20use ahash::AHashMap;
21use indexmap::IndexMap;
22use nautilus_analysis::snapshot::PortfolioStatistics;
23use nautilus_common::factories::OrderFactory;
24use nautilus_core::UnixNanos;
25use nautilus_model::{
26    enums::{ContingencyType, OrderSide, OrderType, TimeInForce, TrailingOffsetType, TriggerType},
27    events::PortfolioSnapshot,
28    identifiers::{
29        AccountId, ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId, PositionId, Venue,
30    },
31    orders::{OrderAny, OrderList},
32    types::{Currency, Money, Price, Quantity},
33};
34use nautilus_portfolio::Portfolio;
35use rust_decimal::Decimal;
36use ustr::Ustr;
37
38/// User-facing order creation API.
39#[derive(Debug)]
40pub struct OrderApi<'a> {
41    order_factory: &'a RefCell<OrderFactory>,
42}
43
44#[bon::bon]
45impl<'a> OrderApi<'a> {
46    pub(crate) const fn new(order_factory: &'a RefCell<OrderFactory>) -> Self {
47        Self { order_factory }
48    }
49
50    /// Generates a new client order ID.
51    ///
52    /// # Panics
53    ///
54    /// Panics if the order factory is already mutably borrowed.
55    #[must_use]
56    pub fn generate_client_order_id(&self) -> ClientOrderId {
57        self.order_factory.borrow_mut().generate_client_order_id()
58    }
59
60    /// Generates a new order list ID.
61    ///
62    /// # Panics
63    ///
64    /// Panics if the order factory is already mutably borrowed.
65    #[must_use]
66    pub fn generate_order_list_id(&self) -> OrderListId {
67        self.order_factory.borrow_mut().generate_order_list_id()
68    }
69
70    /// Creates a new market order.
71    ///
72    /// # Panics
73    ///
74    /// Panics if the order parameters fail validation or the order factory is already mutably
75    /// borrowed.
76    #[must_use]
77    #[expect(clippy::too_many_arguments)]
78    pub fn market(
79        &self,
80        instrument_id: InstrumentId,
81        order_side: OrderSide,
82        quantity: Quantity,
83        time_in_force: Option<TimeInForce>,
84        reduce_only: Option<bool>,
85        quote_quantity: Option<bool>,
86        exec_algorithm_id: Option<ExecAlgorithmId>,
87        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
88        tags: Option<Vec<Ustr>>,
89        client_order_id: Option<ClientOrderId>,
90    ) -> OrderAny {
91        self.order_factory.borrow_mut().market(
92            instrument_id,
93            order_side,
94            quantity,
95            time_in_force,
96            reduce_only,
97            quote_quantity,
98            exec_algorithm_id,
99            exec_algorithm_params,
100            tags,
101            client_order_id,
102        )
103    }
104
105    /// Creates a new limit order.
106    ///
107    /// # Panics
108    ///
109    /// Panics if the order parameters fail validation or the order factory is already mutably
110    /// borrowed.
111    #[must_use]
112    #[expect(clippy::too_many_arguments)]
113    pub fn limit(
114        &self,
115        instrument_id: InstrumentId,
116        order_side: OrderSide,
117        quantity: Quantity,
118        price: Price,
119        time_in_force: Option<TimeInForce>,
120        expire_time: Option<UnixNanos>,
121        post_only: Option<bool>,
122        reduce_only: Option<bool>,
123        quote_quantity: Option<bool>,
124        display_qty: Option<Quantity>,
125        emulation_trigger: Option<TriggerType>,
126        trigger_instrument_id: Option<InstrumentId>,
127        exec_algorithm_id: Option<ExecAlgorithmId>,
128        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
129        tags: Option<Vec<Ustr>>,
130        client_order_id: Option<ClientOrderId>,
131    ) -> OrderAny {
132        self.order_factory.borrow_mut().limit(
133            instrument_id,
134            order_side,
135            quantity,
136            price,
137            time_in_force,
138            expire_time,
139            post_only,
140            reduce_only,
141            quote_quantity,
142            display_qty,
143            emulation_trigger,
144            trigger_instrument_id,
145            exec_algorithm_id,
146            exec_algorithm_params,
147            tags,
148            client_order_id,
149        )
150    }
151
152    /// Creates a new stop-market order.
153    ///
154    /// # Panics
155    ///
156    /// Panics if the order parameters fail validation or the order factory is already mutably
157    /// borrowed.
158    #[must_use]
159    #[expect(clippy::too_many_arguments)]
160    pub fn stop_market(
161        &self,
162        instrument_id: InstrumentId,
163        order_side: OrderSide,
164        quantity: Quantity,
165        trigger_price: Price,
166        trigger_type: Option<TriggerType>,
167        time_in_force: Option<TimeInForce>,
168        expire_time: Option<UnixNanos>,
169        reduce_only: Option<bool>,
170        quote_quantity: Option<bool>,
171        display_qty: Option<Quantity>,
172        emulation_trigger: Option<TriggerType>,
173        trigger_instrument_id: Option<InstrumentId>,
174        exec_algorithm_id: Option<ExecAlgorithmId>,
175        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
176        tags: Option<Vec<Ustr>>,
177        client_order_id: Option<ClientOrderId>,
178    ) -> OrderAny {
179        self.order_factory.borrow_mut().stop_market(
180            instrument_id,
181            order_side,
182            quantity,
183            trigger_price,
184            trigger_type,
185            time_in_force,
186            expire_time,
187            reduce_only,
188            quote_quantity,
189            display_qty,
190            emulation_trigger,
191            trigger_instrument_id,
192            exec_algorithm_id,
193            exec_algorithm_params,
194            tags,
195            client_order_id,
196        )
197    }
198
199    /// Creates a new stop-limit order.
200    ///
201    /// # Panics
202    ///
203    /// Panics if the order parameters fail validation or the order factory is already mutably
204    /// borrowed.
205    #[must_use]
206    #[expect(clippy::too_many_arguments)]
207    pub fn stop_limit(
208        &self,
209        instrument_id: InstrumentId,
210        order_side: OrderSide,
211        quantity: Quantity,
212        price: Price,
213        trigger_price: Price,
214        trigger_type: Option<TriggerType>,
215        time_in_force: Option<TimeInForce>,
216        expire_time: Option<UnixNanos>,
217        post_only: Option<bool>,
218        reduce_only: Option<bool>,
219        quote_quantity: Option<bool>,
220        display_qty: Option<Quantity>,
221        emulation_trigger: Option<TriggerType>,
222        trigger_instrument_id: Option<InstrumentId>,
223        exec_algorithm_id: Option<ExecAlgorithmId>,
224        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
225        tags: Option<Vec<Ustr>>,
226        client_order_id: Option<ClientOrderId>,
227    ) -> OrderAny {
228        self.order_factory.borrow_mut().stop_limit(
229            instrument_id,
230            order_side,
231            quantity,
232            price,
233            trigger_price,
234            trigger_type,
235            time_in_force,
236            expire_time,
237            post_only,
238            reduce_only,
239            quote_quantity,
240            display_qty,
241            emulation_trigger,
242            trigger_instrument_id,
243            exec_algorithm_id,
244            exec_algorithm_params,
245            tags,
246            client_order_id,
247        )
248    }
249
250    /// Creates a new market-to-limit order.
251    ///
252    /// # Panics
253    ///
254    /// Panics if the order parameters fail validation or the order factory is already mutably
255    /// borrowed.
256    #[must_use]
257    #[expect(clippy::too_many_arguments)]
258    pub fn market_to_limit(
259        &self,
260        instrument_id: InstrumentId,
261        order_side: OrderSide,
262        quantity: Quantity,
263        time_in_force: Option<TimeInForce>,
264        expire_time: Option<UnixNanos>,
265        reduce_only: Option<bool>,
266        quote_quantity: Option<bool>,
267        display_qty: Option<Quantity>,
268        exec_algorithm_id: Option<ExecAlgorithmId>,
269        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
270        tags: Option<Vec<Ustr>>,
271        client_order_id: Option<ClientOrderId>,
272    ) -> OrderAny {
273        self.order_factory.borrow_mut().market_to_limit(
274            instrument_id,
275            order_side,
276            quantity,
277            time_in_force,
278            expire_time,
279            reduce_only,
280            quote_quantity,
281            display_qty,
282            exec_algorithm_id,
283            exec_algorithm_params,
284            tags,
285            client_order_id,
286        )
287    }
288
289    /// Creates a new market-if-touched order.
290    ///
291    /// # Panics
292    ///
293    /// Panics if the order parameters fail validation or the order factory is already mutably
294    /// borrowed.
295    #[must_use]
296    #[expect(clippy::too_many_arguments)]
297    pub fn market_if_touched(
298        &self,
299        instrument_id: InstrumentId,
300        order_side: OrderSide,
301        quantity: Quantity,
302        trigger_price: Price,
303        trigger_type: Option<TriggerType>,
304        time_in_force: Option<TimeInForce>,
305        expire_time: Option<UnixNanos>,
306        reduce_only: Option<bool>,
307        quote_quantity: Option<bool>,
308        emulation_trigger: Option<TriggerType>,
309        trigger_instrument_id: Option<InstrumentId>,
310        exec_algorithm_id: Option<ExecAlgorithmId>,
311        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
312        tags: Option<Vec<Ustr>>,
313        client_order_id: Option<ClientOrderId>,
314    ) -> OrderAny {
315        self.order_factory.borrow_mut().market_if_touched(
316            instrument_id,
317            order_side,
318            quantity,
319            trigger_price,
320            trigger_type,
321            time_in_force,
322            expire_time,
323            reduce_only,
324            quote_quantity,
325            emulation_trigger,
326            trigger_instrument_id,
327            exec_algorithm_id,
328            exec_algorithm_params,
329            tags,
330            client_order_id,
331        )
332    }
333
334    /// Creates a new limit-if-touched order.
335    ///
336    /// # Panics
337    ///
338    /// Panics if the order parameters fail validation or the order factory is already mutably
339    /// borrowed.
340    #[must_use]
341    #[expect(clippy::too_many_arguments)]
342    pub fn limit_if_touched(
343        &self,
344        instrument_id: InstrumentId,
345        order_side: OrderSide,
346        quantity: Quantity,
347        price: Price,
348        trigger_price: Price,
349        trigger_type: Option<TriggerType>,
350        time_in_force: Option<TimeInForce>,
351        expire_time: Option<UnixNanos>,
352        post_only: Option<bool>,
353        reduce_only: Option<bool>,
354        quote_quantity: Option<bool>,
355        display_qty: Option<Quantity>,
356        emulation_trigger: Option<TriggerType>,
357        trigger_instrument_id: Option<InstrumentId>,
358        exec_algorithm_id: Option<ExecAlgorithmId>,
359        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
360        tags: Option<Vec<Ustr>>,
361        client_order_id: Option<ClientOrderId>,
362    ) -> OrderAny {
363        self.order_factory.borrow_mut().limit_if_touched(
364            instrument_id,
365            order_side,
366            quantity,
367            price,
368            trigger_price,
369            trigger_type,
370            time_in_force,
371            expire_time,
372            post_only,
373            reduce_only,
374            quote_quantity,
375            display_qty,
376            emulation_trigger,
377            trigger_instrument_id,
378            exec_algorithm_id,
379            exec_algorithm_params,
380            tags,
381            client_order_id,
382        )
383    }
384
385    /// Creates a new trailing-stop-market order.
386    ///
387    /// # Panics
388    ///
389    /// Panics if the order parameters fail validation or the order factory is already mutably
390    /// borrowed.
391    #[must_use]
392    #[expect(clippy::too_many_arguments)]
393    pub fn trailing_stop_market(
394        &self,
395        instrument_id: InstrumentId,
396        order_side: OrderSide,
397        quantity: Quantity,
398        trailing_offset: Decimal,
399        trailing_offset_type: Option<TrailingOffsetType>,
400        activation_price: Option<Price>,
401        trigger_price: Option<Price>,
402        trigger_type: Option<TriggerType>,
403        time_in_force: Option<TimeInForce>,
404        expire_time: Option<UnixNanos>,
405        reduce_only: Option<bool>,
406        quote_quantity: Option<bool>,
407        display_qty: Option<Quantity>,
408        emulation_trigger: Option<TriggerType>,
409        trigger_instrument_id: Option<InstrumentId>,
410        exec_algorithm_id: Option<ExecAlgorithmId>,
411        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
412        tags: Option<Vec<Ustr>>,
413        client_order_id: Option<ClientOrderId>,
414    ) -> OrderAny {
415        self.order_factory.borrow_mut().trailing_stop_market(
416            instrument_id,
417            order_side,
418            quantity,
419            trailing_offset,
420            trailing_offset_type,
421            activation_price,
422            trigger_price,
423            trigger_type,
424            time_in_force,
425            expire_time,
426            reduce_only,
427            quote_quantity,
428            display_qty,
429            emulation_trigger,
430            trigger_instrument_id,
431            exec_algorithm_id,
432            exec_algorithm_params,
433            tags,
434            client_order_id,
435        )
436    }
437
438    /// Creates a new trailing-stop-limit order.
439    ///
440    /// # Panics
441    ///
442    /// Panics if the order parameters fail validation or the order factory is already mutably
443    /// borrowed.
444    #[must_use]
445    #[expect(clippy::too_many_arguments)]
446    pub fn trailing_stop_limit(
447        &self,
448        instrument_id: InstrumentId,
449        order_side: OrderSide,
450        quantity: Quantity,
451        price: Price,
452        limit_offset: Decimal,
453        trailing_offset: Decimal,
454        trailing_offset_type: Option<TrailingOffsetType>,
455        activation_price: Option<Price>,
456        trigger_price: Option<Price>,
457        trigger_type: Option<TriggerType>,
458        time_in_force: Option<TimeInForce>,
459        expire_time: Option<UnixNanos>,
460        post_only: Option<bool>,
461        reduce_only: Option<bool>,
462        quote_quantity: Option<bool>,
463        display_qty: Option<Quantity>,
464        emulation_trigger: Option<TriggerType>,
465        trigger_instrument_id: Option<InstrumentId>,
466        exec_algorithm_id: Option<ExecAlgorithmId>,
467        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
468        tags: Option<Vec<Ustr>>,
469        client_order_id: Option<ClientOrderId>,
470    ) -> OrderAny {
471        self.order_factory.borrow_mut().trailing_stop_limit(
472            instrument_id,
473            order_side,
474            quantity,
475            Some(price),
476            limit_offset,
477            trailing_offset,
478            trailing_offset_type,
479            activation_price,
480            trigger_price,
481            trigger_type,
482            time_in_force,
483            expire_time,
484            post_only,
485            reduce_only,
486            quote_quantity,
487            display_qty,
488            emulation_trigger,
489            trigger_instrument_id,
490            exec_algorithm_id,
491            exec_algorithm_params,
492            tags,
493            client_order_id,
494        )
495    }
496
497    /// Creates a new order list from the given orders.
498    ///
499    /// # Panics
500    ///
501    /// Panics if the list parameters fail validation or the order factory is already mutably
502    /// borrowed.
503    #[must_use]
504    pub fn create_list(&self, orders: &mut [OrderAny], ts_init: UnixNanos) -> OrderList {
505        self.order_factory.borrow_mut().create_list(orders, ts_init)
506    }
507
508    /// Creates a bracket order with an entry order and attached take-profit and stop-loss legs.
509    ///
510    /// # Panics
511    ///
512    /// Panics if the bracket parameters fail validation or the order factory is already mutably
513    /// borrowed.
514    #[must_use]
515    #[builder]
516    pub fn bracket(
517        &self,
518        instrument_id: InstrumentId,
519        order_side: OrderSide,
520        quantity: Quantity,
521        #[builder(default = false)] quote_quantity: bool,
522        emulation_trigger: Option<TriggerType>,
523        trigger_instrument_id: Option<InstrumentId>,
524        #[builder(default = ContingencyType::Ouo)] contingency_type: ContingencyType,
525        #[builder(default = OrderType::Market)] entry_order_type: OrderType,
526        entry_price: Option<Price>,
527        entry_trigger_price: Option<Price>,
528        expire_time: Option<UnixNanos>,
529        #[builder(default = TimeInForce::Gtc)] time_in_force: TimeInForce,
530        #[builder(default = false)] entry_post_only: bool,
531        entry_exec_algorithm_id: Option<ExecAlgorithmId>,
532        entry_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
533        #[builder(default = vec![Ustr::from("ENTRY")])] entry_tags: Vec<Ustr>,
534        entry_client_order_id: Option<ClientOrderId>,
535        #[builder(default = OrderType::Limit)] tp_order_type: OrderType,
536        tp_price: Option<Price>,
537        tp_trigger_price: Option<Price>,
538        #[builder(default = TriggerType::Default)] tp_trigger_type: TriggerType,
539        tp_activation_price: Option<Price>,
540        tp_trailing_offset: Option<Decimal>,
541        #[builder(default = TrailingOffsetType::Price)] tp_trailing_offset_type: TrailingOffsetType,
542        tp_limit_offset: Option<Decimal>,
543        #[builder(default = TimeInForce::Gtc)] tp_time_in_force: TimeInForce,
544        #[builder(default = true)] tp_post_only: bool,
545        #[builder(default = true)] tp_reduce_only: bool,
546        tp_exec_algorithm_id: Option<ExecAlgorithmId>,
547        tp_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
548        #[builder(default = vec![Ustr::from("TAKE_PROFIT")])] tp_tags: Vec<Ustr>,
549        tp_client_order_id: Option<ClientOrderId>,
550        #[builder(default = OrderType::StopMarket)] sl_order_type: OrderType,
551        sl_trigger_price: Option<Price>,
552        #[builder(default = TriggerType::Default)] sl_trigger_type: TriggerType,
553        sl_activation_price: Option<Price>,
554        sl_trailing_offset: Option<Decimal>,
555        #[builder(default = TrailingOffsetType::Price)] sl_trailing_offset_type: TrailingOffsetType,
556        #[builder(default = TimeInForce::Gtc)] sl_time_in_force: TimeInForce,
557        #[builder(default = true)] sl_reduce_only: bool,
558        sl_exec_algorithm_id: Option<ExecAlgorithmId>,
559        sl_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
560        #[builder(default = vec![Ustr::from("STOP_LOSS")])] sl_tags: Vec<Ustr>,
561        sl_client_order_id: Option<ClientOrderId>,
562    ) -> Vec<OrderAny> {
563        let mut order_factory = self.order_factory.borrow_mut();
564        order_factory
565            .bracket()
566            .instrument_id(instrument_id)
567            .order_side(order_side)
568            .quantity(quantity)
569            .quote_quantity(quote_quantity)
570            .maybe_emulation_trigger(emulation_trigger)
571            .maybe_trigger_instrument_id(trigger_instrument_id)
572            .contingency_type(contingency_type)
573            .entry_order_type(entry_order_type)
574            .maybe_entry_price(entry_price)
575            .maybe_entry_trigger_price(entry_trigger_price)
576            .maybe_expire_time(expire_time)
577            .time_in_force(time_in_force)
578            .entry_post_only(entry_post_only)
579            .maybe_entry_exec_algorithm_id(entry_exec_algorithm_id)
580            .maybe_entry_exec_algorithm_params(entry_exec_algorithm_params)
581            .entry_tags(entry_tags)
582            .maybe_entry_client_order_id(entry_client_order_id)
583            .tp_order_type(tp_order_type)
584            .maybe_tp_price(tp_price)
585            .maybe_tp_trigger_price(tp_trigger_price)
586            .tp_trigger_type(tp_trigger_type)
587            .maybe_tp_activation_price(tp_activation_price)
588            .maybe_tp_trailing_offset(tp_trailing_offset)
589            .tp_trailing_offset_type(tp_trailing_offset_type)
590            .maybe_tp_limit_offset(tp_limit_offset)
591            .tp_time_in_force(tp_time_in_force)
592            .tp_post_only(tp_post_only)
593            .tp_reduce_only(tp_reduce_only)
594            .maybe_tp_exec_algorithm_id(tp_exec_algorithm_id)
595            .maybe_tp_exec_algorithm_params(tp_exec_algorithm_params)
596            .tp_tags(tp_tags)
597            .maybe_tp_client_order_id(tp_client_order_id)
598            .sl_order_type(sl_order_type)
599            .maybe_sl_trigger_price(sl_trigger_price)
600            .sl_trigger_type(sl_trigger_type)
601            .maybe_sl_activation_price(sl_activation_price)
602            .maybe_sl_trailing_offset(sl_trailing_offset)
603            .sl_trailing_offset_type(sl_trailing_offset_type)
604            .sl_time_in_force(sl_time_in_force)
605            .sl_reduce_only(sl_reduce_only)
606            .maybe_sl_exec_algorithm_id(sl_exec_algorithm_id)
607            .maybe_sl_exec_algorithm_params(sl_exec_algorithm_params)
608            .sl_tags(sl_tags)
609            .maybe_sl_client_order_id(sl_client_order_id)
610            .call()
611    }
612}
613
614/// User-facing portfolio read API.
615#[derive(Debug)]
616pub struct PortfolioApi<'a> {
617    portfolio: &'a RefCell<Portfolio>,
618}
619
620impl<'a> PortfolioApi<'a> {
621    pub(crate) const fn new(portfolio: &'a RefCell<Portfolio>) -> Self {
622        Self { portfolio }
623    }
624
625    /// Returns `true` if the portfolio has been initialized.
626    ///
627    /// # Panics
628    ///
629    /// Panics if the portfolio is already mutably borrowed.
630    #[must_use]
631    pub fn is_initialized(&self) -> bool {
632        self.portfolio.borrow().is_initialized()
633    }
634
635    /// Returns the locked balances for the `account_id`, or for the account issued under `venue`
636    /// when no account ID is given.
637    ///
638    /// # Panics
639    ///
640    /// Panics if the portfolio is already mutably borrowed.
641    #[must_use]
642    pub fn balances_locked(
643        &self,
644        venue: &Venue,
645        account_id: Option<&AccountId>,
646    ) -> IndexMap<Currency, Money> {
647        self.portfolio.borrow().balances_locked(venue, account_id)
648    }
649
650    /// Returns the initial margin requirements for the `account_id`, or for the account issued
651    /// under `venue` when no account ID is given.
652    ///
653    /// # Panics
654    ///
655    /// Panics if the portfolio is already mutably borrowed.
656    #[must_use]
657    pub fn instrument_initial_margins(
658        &self,
659        venue: &Venue,
660        account_id: Option<&AccountId>,
661    ) -> IndexMap<InstrumentId, Money> {
662        self.portfolio
663            .borrow()
664            .instrument_initial_margins(venue, account_id)
665    }
666
667    /// Returns the maintenance margin requirements for the `account_id`, or for the account
668    /// issued under `venue` when no account ID is given.
669    ///
670    /// # Panics
671    ///
672    /// Panics if the portfolio is already mutably borrowed.
673    #[must_use]
674    pub fn instrument_maintenance_margins(
675        &self,
676        venue: &Venue,
677        account_id: Option<&AccountId>,
678    ) -> IndexMap<InstrumentId, Money> {
679        self.portfolio
680            .borrow()
681            .instrument_maintenance_margins(venue, account_id)
682    }
683
684    /// Returns the unrealized PnLs for all positions at the given venue.
685    ///
686    /// # Panics
687    ///
688    /// Panics if the portfolio is already borrowed.
689    #[must_use]
690    pub fn unrealized_pnls(
691        &self,
692        venue: &Venue,
693        account_id: Option<&AccountId>,
694    ) -> Option<IndexMap<Currency, Money>> {
695        self.portfolio
696            .borrow_mut()
697            .unrealized_pnls(venue, account_id, None)
698    }
699
700    /// Returns the realized PnLs for all positions at the given venue.
701    ///
702    /// # Panics
703    ///
704    /// Panics if the portfolio is already borrowed.
705    #[must_use]
706    pub fn realized_pnls(
707        &self,
708        venue: &Venue,
709        account_id: Option<&AccountId>,
710    ) -> Option<IndexMap<Currency, Money>> {
711        self.portfolio
712            .borrow_mut()
713            .realized_pnls(venue, account_id, None)
714    }
715
716    /// Returns net exposures by currency for the given venue.
717    ///
718    /// # Panics
719    ///
720    /// Panics if the portfolio is already mutably borrowed.
721    #[must_use]
722    pub fn net_exposures(
723        &self,
724        venue: &Venue,
725        account_id: Option<&AccountId>,
726    ) -> Option<IndexMap<Currency, Money>> {
727        self.portfolio
728            .borrow()
729            .net_exposures(venue, account_id, None)
730    }
731
732    /// Returns the unrealized PnL for the given instrument ID.
733    ///
734    /// # Panics
735    ///
736    /// Panics if the portfolio is already borrowed.
737    #[must_use]
738    pub fn unrealized_pnl(&self, instrument_id: &InstrumentId) -> Option<Money> {
739        self.portfolio.borrow_mut().unrealized_pnl(instrument_id)
740    }
741
742    /// Returns the unrealized PnL for the given instrument ID and account filter.
743    ///
744    /// # Panics
745    ///
746    /// Panics if the portfolio is already borrowed.
747    #[must_use]
748    pub fn unrealized_pnl_for_account(
749        &self,
750        instrument_id: &InstrumentId,
751        account_id: Option<&AccountId>,
752    ) -> Option<Money> {
753        self.portfolio.borrow_mut().unrealized_pnl_for_account(
754            instrument_id,
755            None,
756            account_id,
757            None,
758        )
759    }
760
761    /// Returns the realized PnL for the given instrument ID.
762    ///
763    /// # Panics
764    ///
765    /// Panics if the portfolio is already borrowed.
766    #[must_use]
767    pub fn realized_pnl(&self, instrument_id: &InstrumentId) -> Option<Money> {
768        self.portfolio.borrow_mut().realized_pnl(instrument_id)
769    }
770
771    /// Returns the realized PnL for the given instrument ID and account filter.
772    ///
773    /// # Panics
774    ///
775    /// Panics if the portfolio is already borrowed.
776    #[must_use]
777    pub fn realized_pnl_for_account(
778        &self,
779        instrument_id: &InstrumentId,
780        account_id: Option<&AccountId>,
781    ) -> Option<Money> {
782        self.portfolio
783            .borrow_mut()
784            .realized_pnl_for_account(instrument_id, account_id, None)
785    }
786
787    /// Returns the total PnL for the given instrument ID.
788    ///
789    /// # Panics
790    ///
791    /// Panics if the portfolio is already borrowed.
792    #[must_use]
793    pub fn total_pnl(&self, instrument_id: &InstrumentId) -> Option<Money> {
794        self.portfolio.borrow_mut().total_pnl(instrument_id)
795    }
796
797    /// Returns the total PnL for the given instrument ID and account filter.
798    ///
799    /// # Panics
800    ///
801    /// Panics if the portfolio is already borrowed.
802    #[must_use]
803    pub fn total_pnl_for_account(
804        &self,
805        instrument_id: &InstrumentId,
806        account_id: Option<&AccountId>,
807    ) -> Option<Money> {
808        self.portfolio
809            .borrow_mut()
810            .total_pnl_for_account(instrument_id, None, account_id, None)
811    }
812
813    /// Returns the total PnLs for the given venue.
814    ///
815    /// # Panics
816    ///
817    /// Panics if the portfolio is already borrowed.
818    #[must_use]
819    pub fn total_pnls(
820        &self,
821        venue: &Venue,
822        account_id: Option<&AccountId>,
823    ) -> Option<IndexMap<Currency, Money>> {
824        self.portfolio
825            .borrow_mut()
826            .total_pnls(venue, account_id, None)
827    }
828
829    /// Returns the per-currency mark-to-market value of open positions at the given venue.
830    ///
831    /// # Panics
832    ///
833    /// Panics if the portfolio is already borrowed.
834    #[must_use]
835    pub fn mark_values(
836        &self,
837        venue: &Venue,
838        account_id: Option<&AccountId>,
839    ) -> IndexMap<Currency, Money> {
840        self.portfolio.borrow_mut().mark_values(venue, account_id)
841    }
842
843    /// Returns the per-currency total equity for the given venue.
844    ///
845    /// # Panics
846    ///
847    /// Panics if the portfolio is already borrowed.
848    #[must_use]
849    pub fn equity(
850        &self,
851        venue: &Venue,
852        account_id: Option<&AccountId>,
853    ) -> IndexMap<Currency, Money> {
854        self.portfolio.borrow_mut().equity(venue, account_id)
855    }
856
857    /// Builds a portfolio snapshot for the given account.
858    ///
859    /// # Panics
860    ///
861    /// Panics if the portfolio is already borrowed.
862    #[must_use]
863    pub fn build_snapshot(&self, account_id: &AccountId) -> Option<PortfolioSnapshot> {
864        self.portfolio.borrow_mut().build_snapshot(account_id)
865    }
866
867    /// Returns an owned snapshot of computed portfolio performance statistics.
868    ///
869    /// # Panics
870    ///
871    /// Panics if the portfolio is already mutably borrowed.
872    #[must_use]
873    pub fn statistics(&self) -> PortfolioStatistics {
874        self.portfolio.borrow().statistics()
875    }
876
877    /// Returns the recorded portfolio snapshots for the given account.
878    ///
879    /// # Panics
880    ///
881    /// Panics if the portfolio is already mutably borrowed.
882    #[must_use]
883    pub fn snapshots(&self, account_id: &AccountId) -> Vec<PortfolioSnapshot> {
884        self.portfolio.borrow().snapshots(account_id)
885    }
886
887    /// Returns the instruments currently flagged as unpriced for the given venue.
888    ///
889    /// # Panics
890    ///
891    /// Panics if the portfolio is already mutably borrowed.
892    #[must_use]
893    pub fn missing_price_instruments(&self, venue: &Venue) -> Vec<InstrumentId> {
894        self.portfolio
895            .borrow()
896            .missing_price_instruments(venue, None)
897    }
898
899    /// Returns the net exposure for the given instrument ID.
900    ///
901    /// # Panics
902    ///
903    /// Panics if the portfolio is already mutably borrowed.
904    #[must_use]
905    pub fn net_exposure(
906        &self,
907        instrument_id: &InstrumentId,
908        account_id: Option<&AccountId>,
909    ) -> Option<Money> {
910        self.portfolio
911            .borrow()
912            .net_exposure(instrument_id, None, account_id, None)
913    }
914
915    /// Returns the net position for the given instrument ID.
916    ///
917    /// # Panics
918    ///
919    /// Panics if the portfolio is already mutably borrowed.
920    #[must_use]
921    pub fn net_position(&self, instrument_id: &InstrumentId) -> Decimal {
922        self.portfolio.borrow().net_position(instrument_id)
923    }
924
925    /// Returns whether the net position is long for the given instrument ID.
926    ///
927    /// # Panics
928    ///
929    /// Panics if the portfolio is already mutably borrowed.
930    #[must_use]
931    pub fn is_net_long(&self, instrument_id: &InstrumentId) -> bool {
932        self.portfolio.borrow().is_net_long(instrument_id)
933    }
934
935    /// Returns whether the net position is short for the given instrument ID.
936    ///
937    /// # Panics
938    ///
939    /// Panics if the portfolio is already mutably borrowed.
940    #[must_use]
941    pub fn is_net_short(&self, instrument_id: &InstrumentId) -> bool {
942        self.portfolio.borrow().is_net_short(instrument_id)
943    }
944
945    /// Returns whether the net position is flat for the given instrument ID.
946    ///
947    /// # Panics
948    ///
949    /// Panics if the portfolio is already mutably borrowed.
950    #[must_use]
951    pub fn is_net_flat(&self, instrument_id: &InstrumentId) -> bool {
952        self.portfolio.borrow().is_net_flat(instrument_id)
953    }
954
955    /// Returns whether every net position is flat.
956    ///
957    /// # Panics
958    ///
959    /// Panics if the portfolio is already mutably borrowed.
960    #[must_use]
961    pub fn is_completely_net_flat(&self) -> bool {
962        self.portfolio.borrow().is_completely_net_flat()
963    }
964
965    /// Returns realized PnLs recorded during portfolio event processing.
966    ///
967    /// Each record is `(position_id, ts_event, realized_pnl)`.
968    ///
969    /// # Panics
970    ///
971    /// Panics if the portfolio is already mutably borrowed.
972    #[must_use]
973    pub fn recorded_realized_pnls(&self) -> AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>> {
974        self.portfolio.borrow().recorded_realized_pnls()
975    }
976}
977
978#[cfg(test)]
979mod tests {
980    use std::{cell::RefCell, rc::Rc};
981
982    use nautilus_common::{cache::Cache, clock::VirtualClock, factories::OrderFactory};
983    use nautilus_core::{UUID4, UnixNanos};
984    use nautilus_model::{
985        enums::{AccountType, OrderSide, OrderType},
986        events::AccountState,
987        identifiers::{AccountId, InstrumentId, StrategyId, TraderId, Venue},
988        orders::Order,
989        types::{AccountBalance, MarginBalance},
990    };
991    use rstest::rstest;
992
993    use super::*;
994
995    #[rstest]
996    fn test_order_api_creates_market_order() {
997        let trader_id = TraderId::from("TRADER-001");
998        let strategy_id = StrategyId::from("S-001");
999        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1000        let order_factory = RefCell::new(OrderFactory::new(
1001            trader_id,
1002            strategy_id,
1003            None,
1004            None,
1005            clock,
1006            false,
1007            true,
1008        ));
1009        let api = OrderApi::new(&order_factory);
1010        let instrument_id = InstrumentId::from("AUD/USD.SIM");
1011
1012        let order = api.market(
1013            instrument_id,
1014            OrderSide::Buy,
1015            Quantity::from("100000"),
1016            None,
1017            None,
1018            None,
1019            None,
1020            None,
1021            None,
1022            None,
1023        );
1024
1025        assert_eq!(order.order_type(), OrderType::Market);
1026        assert_eq!(order.instrument_id(), instrument_id);
1027        assert_eq!(order.order_side(), OrderSide::Buy);
1028        assert_eq!(order.quantity(), Quantity::from("100000"));
1029        assert_eq!(order.trader_id(), trader_id);
1030        assert_eq!(order.strategy_id(), strategy_id);
1031    }
1032
1033    #[rstest]
1034    fn test_order_api_creates_bracket_orders() {
1035        let trader_id = TraderId::from("TRADER-001");
1036        let strategy_id = StrategyId::from("S-001");
1037        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1038        let order_factory = RefCell::new(OrderFactory::new(
1039            trader_id,
1040            strategy_id,
1041            None,
1042            None,
1043            clock,
1044            false,
1045            true,
1046        ));
1047        let api = OrderApi::new(&order_factory);
1048        let instrument_id = InstrumentId::from("AUD/USD.SIM");
1049
1050        let orders = api
1051            .bracket()
1052            .instrument_id(instrument_id)
1053            .order_side(OrderSide::Buy)
1054            .quantity(Quantity::from("100000"))
1055            .tp_price(Price::from("1.10000"))
1056            .sl_trigger_price(Price::from("0.90000"))
1057            .call();
1058
1059        assert_eq!(orders.len(), 3);
1060        assert!(
1061            orders
1062                .iter()
1063                .all(|order| order.instrument_id() == instrument_id)
1064        );
1065        assert!(orders.iter().all(|order| order.trader_id() == trader_id));
1066        assert!(
1067            orders
1068                .iter()
1069                .all(|order| order.strategy_id() == strategy_id)
1070        );
1071        assert_eq!(orders[0].order_type(), OrderType::Market);
1072        assert_eq!(orders[0].order_side(), OrderSide::Buy);
1073        assert_eq!(orders[0].quantity(), Quantity::from("100000"));
1074        assert_eq!(orders[1].order_type(), OrderType::StopMarket);
1075        assert_eq!(orders[1].order_side(), OrderSide::Sell);
1076        assert_eq!(orders[1].trigger_price(), Some(Price::from("0.90000")));
1077        assert_eq!(orders[2].order_type(), OrderType::Limit);
1078        assert_eq!(orders[2].order_side(), OrderSide::Sell);
1079        assert_eq!(orders[2].price(), Some(Price::from("1.10000")));
1080    }
1081
1082    #[rstest]
1083    fn test_order_api_bracket_exits_are_reduce_only_by_default() {
1084        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1085        let order_factory = RefCell::new(OrderFactory::new(
1086            TraderId::from("TRADER-001"),
1087            StrategyId::from("S-001"),
1088            None,
1089            None,
1090            clock,
1091            false,
1092            true,
1093        ));
1094        let api = OrderApi::new(&order_factory);
1095
1096        let orders = api
1097            .bracket()
1098            .instrument_id(InstrumentId::from("AUD/USD.SIM"))
1099            .order_side(OrderSide::Buy)
1100            .quantity(Quantity::from("100000"))
1101            .tp_price(Price::from("1.10000"))
1102            .sl_trigger_price(Price::from("0.90000"))
1103            .call();
1104
1105        assert!(!orders[0].is_reduce_only(), "entry must not be reduce-only");
1106        assert!(orders[1].is_reduce_only(), "stop-loss must be reduce-only");
1107        assert!(
1108            orders[2].is_reduce_only(),
1109            "take-profit must be reduce-only"
1110        );
1111    }
1112
1113    #[rstest]
1114    #[case::tp_disabled(false, true)]
1115    #[case::sl_disabled(true, false)]
1116    #[case::both_disabled(false, false)]
1117    #[case::both_enabled(true, true)]
1118    fn test_order_api_bracket_overrides_exit_reduce_only(
1119        #[case] tp_reduce_only: bool,
1120        #[case] sl_reduce_only: bool,
1121    ) {
1122        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1123        let order_factory = RefCell::new(OrderFactory::new(
1124            TraderId::from("TRADER-001"),
1125            StrategyId::from("S-001"),
1126            None,
1127            None,
1128            clock,
1129            false,
1130            true,
1131        ));
1132        let api = OrderApi::new(&order_factory);
1133
1134        let orders = api
1135            .bracket()
1136            .instrument_id(InstrumentId::from("AUD/USD.SIM"))
1137            .order_side(OrderSide::Buy)
1138            .quantity(Quantity::from("100000"))
1139            .tp_price(Price::from("1.10000"))
1140            .tp_reduce_only(tp_reduce_only)
1141            .sl_trigger_price(Price::from("0.90000"))
1142            .sl_reduce_only(sl_reduce_only)
1143            .call();
1144
1145        assert!(!orders[0].is_reduce_only(), "entry must not be reduce-only");
1146        assert_eq!(orders[1].is_reduce_only(), sl_reduce_only);
1147        assert_eq!(orders[2].is_reduce_only(), tp_reduce_only);
1148    }
1149
1150    #[rstest]
1151    fn test_portfolio_api_empty_reads_return_empty_values() {
1152        let cache = Rc::new(RefCell::new(Cache::default()));
1153        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1154        let portfolio = RefCell::new(Portfolio::new(clock, cache, None));
1155        let api = PortfolioApi::new(&portfolio);
1156        let venue = Venue::from("SIM");
1157        let account_id = AccountId::from("SIM-001");
1158        let instrument_id = InstrumentId::from("AUD/USD.SIM");
1159
1160        assert!(!api.is_initialized());
1161        assert!(api.balances_locked(&venue, None).is_empty());
1162        assert!(api.instrument_initial_margins(&venue, None).is_empty());
1163        assert!(api.instrument_maintenance_margins(&venue, None).is_empty());
1164        assert_eq!(api.unrealized_pnls(&venue, None), Some(IndexMap::new()));
1165        assert_eq!(api.realized_pnls(&venue, None), Some(IndexMap::new()));
1166        assert_eq!(api.net_exposures(&venue, None), None);
1167        assert_eq!(api.unrealized_pnl(&instrument_id), None);
1168        assert_eq!(
1169            api.unrealized_pnl_for_account(&instrument_id, Some(&account_id)),
1170            None
1171        );
1172        assert_eq!(api.realized_pnl(&instrument_id), None);
1173        assert_eq!(
1174            api.realized_pnl_for_account(&instrument_id, Some(&account_id)),
1175            None
1176        );
1177        assert_eq!(api.total_pnl(&instrument_id), None);
1178        assert_eq!(
1179            api.total_pnl_for_account(&instrument_id, Some(&account_id)),
1180            None
1181        );
1182        assert_eq!(api.total_pnls(&venue, None), Some(IndexMap::new()));
1183        assert!(api.mark_values(&venue, None).is_empty());
1184        assert!(api.equity(&venue, None).is_empty());
1185        assert_eq!(api.build_snapshot(&account_id), None);
1186        assert!(api.snapshots(&account_id).is_empty());
1187        assert!(api.missing_price_instruments(&venue).is_empty());
1188        assert_eq!(api.net_exposure(&instrument_id, None), None);
1189        assert_eq!(api.net_position(&instrument_id), Decimal::ZERO);
1190        assert!(!api.is_net_long(&instrument_id));
1191        assert!(!api.is_net_short(&instrument_id));
1192        assert!(api.is_net_flat(&instrument_id));
1193        assert!(api.is_completely_net_flat());
1194        assert!(api.recorded_realized_pnls().is_empty());
1195
1196        let _statistics = api.statistics();
1197    }
1198
1199    #[rstest]
1200    fn test_portfolio_api_account_queries_select_account_id() {
1201        let cache = Rc::new(RefCell::new(Cache::default()));
1202        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1203        let portfolio = RefCell::new(Portfolio::new(clock, cache, None));
1204        let venue = Venue::from("SIM");
1205        let instrument_id = InstrumentId::from("AUD/USD.SIM");
1206        let total = Money::from("1000 USD");
1207
1208        for (account_id, locked, initial, maintenance) in [
1209            ("SIM-001", "100 USD", "30 USD", "15 USD"),
1210            ("SIM-002", "250 USD", "70 USD", "35 USD"),
1211        ] {
1212            let account_id = AccountId::from(account_id);
1213            let locked = Money::from(locked);
1214            let initial = Money::from(initial);
1215            let maintenance = Money::from(maintenance);
1216            let balance = AccountBalance::new(total, locked, total - locked);
1217            let margin = MarginBalance::new(initial, maintenance, Some(instrument_id));
1218            let event_id = UUID4::new();
1219
1220            let state = AccountState::new(
1221                account_id,
1222                AccountType::Margin,
1223                vec![balance],
1224                vec![margin],
1225                true,
1226                event_id,
1227                UnixNanos::default(),
1228                UnixNanos::default(),
1229                None,
1230            );
1231            portfolio.borrow_mut().update_account(&state);
1232        }
1233
1234        let api = PortfolioApi::new(&portfolio);
1235        let account_id = AccountId::from("SIM-002");
1236        let expected_locked = Money::from("250 USD");
1237        let expected_initial = Money::from("70 USD");
1238        let expected_maintenance = Money::from("35 USD");
1239
1240        let balances_locked = api.balances_locked(&venue, Some(&account_id));
1241        let initial_margins = api.instrument_initial_margins(&venue, Some(&account_id));
1242        let maintenance_margins = api.instrument_maintenance_margins(&venue, Some(&account_id));
1243
1244        assert_eq!(
1245            balances_locked,
1246            IndexMap::from([(Currency::USD(), expected_locked)])
1247        );
1248        assert_eq!(
1249            initial_margins,
1250            IndexMap::from([(instrument_id, expected_initial)])
1251        );
1252        assert_eq!(
1253            maintenance_margins,
1254            IndexMap::from([(instrument_id, expected_maintenance)])
1255        );
1256    }
1257}