Skip to main content

nautilus_portfolio/
config.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
16use nautilus_common::config::{ConfigError, ConfigErrorCollector, ConfigResult};
17use nautilus_core::serialization::default_true;
18use serde::{Deserialize, Serialize};
19
20/// Configuration for `Portfolio` instances.
21#[cfg_attr(
22    feature = "python",
23    pyo3::pyclass(module = "nautilus_trader.portfolio", from_py_object)
24)]
25#[cfg_attr(
26    feature = "python",
27    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.portfolio")
28)]
29#[cfg_attr(
30    feature = "python",
31    expect(
32        clippy::unsafe_derive_deserialize,
33        reason = "config deserializes plain fields; unsafe methods come from generated PyO3 integration"
34    )
35)]
36#[expect(
37    clippy::struct_excessive_bools,
38    reason = "config fields mirror the existing Python and serialization surface"
39)]
40#[derive(Debug, Clone, Copy, Serialize, Deserialize, bon::Builder)]
41#[builder(finish_fn(name = build_inner, vis = ""))]
42#[serde(deny_unknown_fields)]
43pub struct PortfolioConfig {
44    /// The type of prices used for portfolio calculations, such as unrealized PnLs.
45    /// If true (default), prefers mark prices when available, then falls back to quote,
46    /// last trade, or bar prices when `bar_updates` is true. If false, skips mark prices
47    /// and uses the fallback chain.
48    #[serde(default = "default_true")]
49    #[builder(default = true)]
50    pub use_mark_prices: bool,
51    /// The type of exchange rates used for portfolio calculations.
52    /// If false (default), uses quote prices.
53    /// If true, uses mark prices.
54    #[serde(default)]
55    #[builder(default)]
56    pub use_mark_xrates: bool,
57    /// If external bars should be considered for updating unrealized PnLs.
58    #[serde(default = "default_true")]
59    #[builder(default = true)]
60    pub bar_updates: bool,
61    /// If calculations should be converted into each account's base currency.
62    /// This setting is only effective for accounts with a specified base currency.
63    #[serde(default = "default_true")]
64    #[builder(default = true)]
65    pub convert_to_account_base_currency: bool,
66    /// If mark-to-market equity snapshots should be recorded and published for every account.
67    ///
68    /// Enabled by default. Records at account registration, every UTC midnight including
69    /// while flat, and shutdown. Disable for workloads such as optimizer runs that do not
70    /// consume an equity curve. This does not affect on-demand equity calculations or the
71    /// opt-in fine-grained `snapshot_interval_ms` stream.
72    #[serde(default = "default_true")]
73    #[builder(default = true)]
74    pub equity_curve: bool,
75    /// The minimum interval (milliseconds) between logging account state events for the same account.
76    /// When set, account state updates will only be logged if this much time has passed since the last log.
77    /// Useful for HFT deployments to prevent excessive logging when account states change rapidly.
78    #[serde(default)]
79    pub min_account_state_logging_interval_ms: Option<u64>,
80    /// The interval (milliseconds) between portfolio snapshot emissions per account.
81    /// When set, a [`PortfolioSnapshot`] is emitted at this cadence while the
82    /// account holds at least one open position, carrying continuous
83    /// mark-to-market equity. When `None` (the default), no fine-grained snapshots
84    /// are emitted; the `equity_curve` setting still controls daily snapshots.
85    ///
86    /// [`PortfolioSnapshot`]: nautilus_model::events::PortfolioSnapshot
87    #[serde(default)]
88    pub snapshot_interval_ms: Option<u64>,
89    /// If debug mode is active (will provide extra debug logging).
90    #[serde(default)]
91    #[builder(default)]
92    pub debug: bool,
93}
94
95impl<S: portfolio_config_builder::IsComplete> PortfolioConfigBuilder<S> {
96    /// Validates and builds the [`PortfolioConfig`].
97    ///
98    /// # Errors
99    ///
100    /// Returns an error if any field fails validation (see [`PortfolioConfig::validate`]).
101    pub fn build(self) -> ConfigResult<PortfolioConfig> {
102        let config = self.build_inner();
103        config.validate()?;
104        Ok(config)
105    }
106}
107
108impl PortfolioConfig {
109    /// Validates the portfolio configuration, collecting every field violation.
110    ///
111    /// # Errors
112    ///
113    /// Returns an error if any field fails validation. Multiple validation failures are collected
114    /// into one error.
115    pub fn validate(&self) -> ConfigResult<()> {
116        let mut errors = ConfigErrorCollector::new();
117
118        for (field, value) in [
119            (
120                "min_account_state_logging_interval_ms",
121                self.min_account_state_logging_interval_ms,
122            ),
123            ("snapshot_interval_ms", self.snapshot_interval_ms),
124        ] {
125            if let Some(ms) = value {
126                errors.check(
127                    ms > 0,
128                    ConfigError::range(
129                        field,
130                        format!("must be a positive number of milliseconds, was {ms}"),
131                    ),
132                );
133            }
134        }
135
136        errors.into_result()
137    }
138}
139
140impl Default for PortfolioConfig {
141    fn default() -> Self {
142        Self::builder()
143            .build()
144            .expect("default `PortfolioConfig` should be valid")
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use rstest::rstest;
151
152    use super::*;
153
154    #[rstest]
155    fn test_default_config_is_valid() {
156        assert!(PortfolioConfig::builder().build().is_ok());
157    }
158
159    #[rstest]
160    fn test_default_config_enables_daily_equity_curve_only() {
161        let config = PortfolioConfig::default();
162
163        assert!(config.equity_curve);
164        assert_eq!(config.snapshot_interval_ms, None);
165    }
166
167    #[rstest]
168    fn test_zero_min_account_state_logging_interval_rejected() {
169        let result = PortfolioConfig::builder()
170            .min_account_state_logging_interval_ms(0)
171            .build();
172        assert!(
173            matches!(result, Err(ConfigError::Range { field, .. }) if field == "min_account_state_logging_interval_ms")
174        );
175    }
176
177    #[rstest]
178    fn test_zero_snapshot_interval_rejected() {
179        let result = PortfolioConfig::builder().snapshot_interval_ms(0).build();
180        assert!(
181            matches!(result, Err(ConfigError::Range { field, .. }) if field == "snapshot_interval_ms")
182        );
183    }
184
185    #[rstest]
186    fn test_positive_intervals_accepted() {
187        let result = PortfolioConfig::builder()
188            .min_account_state_logging_interval_ms(1_000)
189            .snapshot_interval_ms(5_000)
190            .build();
191        assert!(result.is_ok());
192    }
193
194    #[rstest]
195    fn test_multiple_violations_collected() {
196        let result = PortfolioConfig::builder()
197            .min_account_state_logging_interval_ms(0)
198            .snapshot_interval_ms(0)
199            .build();
200        let ConfigError::Multiple { errors } = result.unwrap_err() else {
201            panic!("expected ConfigError::Multiple");
202        };
203        assert_eq!(errors.len(), 2);
204    }
205}