Skip to main content

nautilus_model/identifiers/
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//! Identifiers for the trading domain model.
17//!
18//! # Design notes
19//!
20//! - `TradeId` remains a fixed-size `StackStr` with a 36-character limit.
21//! - High-cardinality external IDs must not use `Ustr`, because interning
22//!   unique values grows process memory without bound.
23//! - Some identifiers still use fixed-size `repr(C)` storage because the
24//!   supported C ABI shares raw layout by value.
25//! - A deeper storage redesign is deferred until the C ABI can move to
26//!   conversion-based bindings instead of layout sharing.
27
28use std::str::FromStr;
29
30use nautilus_core::correctness::CorrectnessError;
31use serde::{Deserialize, Deserializer, Serialize, Serializer};
32
33#[macro_use]
34mod macros;
35
36pub mod account_id;
37pub mod actor_id;
38pub mod client_id;
39pub mod client_order_id;
40pub mod component_id;
41pub mod exec_algorithm_id;
42pub mod futures;
43pub mod instrument_id;
44pub mod option_instrument_id;
45pub mod option_series_id;
46pub mod order_list_id;
47pub mod position_id;
48pub mod strategy_id;
49pub mod symbol;
50pub mod trade_id;
51pub mod trader_id;
52pub mod venue;
53pub mod venue_order_id;
54
55#[cfg(any(test, feature = "test-support"))]
56pub mod stubs;
57
58// Re-exports
59pub use crate::identifiers::{
60    account_id::AccountId,
61    actor_id::ActorId,
62    client_id::ClientId,
63    client_order_id::ClientOrderId,
64    component_id::ComponentId,
65    exec_algorithm_id::ExecAlgorithmId,
66    instrument_id::{GENERIC_SPREAD_ID_SEPARATOR, InstrumentId, InstrumentIdError},
67    option_instrument_id::{
68        OptionContractSpec, OptionInstrumentIdError, OptionSymbologyScheme,
69        cme_globex_option_symbol, compute_option_instrument_id, osi_option_symbol,
70    },
71    option_series_id::{OptionSeriesId, OptionSeriesIdError},
72    order_list_id::OrderListId,
73    position_id::PositionId,
74    strategy_id::{
75        StrategyId, UNASSIGNED_ORDER_ID_TAG, check_order_id_tag, normalize_order_id_tag,
76    },
77    symbol::Symbol,
78    trade_id::TradeId,
79    trader_id::TraderId,
80    venue::Venue,
81    venue_order_id::VenueOrderId,
82};
83
84/// Creates a generic spread instrument ID from `(instrument_id, ratio)` legs.
85///
86/// Sorts the legs by symbol and joins them with [`GENERIC_SPREAD_ID_SEPARATOR`], formatting a
87/// positive ratio as `(ratio)symbol` and a negative ratio as `((ratio))symbol`. For example,
88/// `MSFT.NASDAQ` with ratio 1 and `AAPL.NASDAQ` with ratio -2 produce
89/// `((2))AAPL___(1)MSFT.NASDAQ`.
90///
91/// A leg symbol that contains the separator or ends with `_` produces an ID that does not parse
92/// back into the same legs.
93///
94/// # Errors
95///
96/// Returns an error if:
97/// - Fewer than two legs are given.
98/// - A ratio is zero or `i64::MIN`.
99/// - The legs have different venues.
100pub fn new_generic_spread_id(
101    instrument_ratios: &[(InstrumentId, i64)],
102) -> anyhow::Result<InstrumentId> {
103    anyhow::ensure!(
104        instrument_ratios.len() > 1,
105        "instrument_ratios list needs to have at least 2 legs"
106    );
107
108    let first_venue = instrument_ratios[0].0.venue;
109    for (instrument_id, ratio) in instrument_ratios {
110        anyhow::ensure!(*ratio != 0, "ratio cannot be zero");
111        anyhow::ensure!(*ratio != i64::MIN, "ratio cannot be i64::MIN");
112        anyhow::ensure!(
113            instrument_id.venue == first_venue,
114            "All venues must match. Expected {first_venue}, was {}",
115            instrument_id.venue
116        );
117    }
118
119    let mut sorted_ratios = instrument_ratios.to_vec();
120    sorted_ratios.sort_by_key(|(instrument_id, _)| instrument_id.symbol);
121
122    let symbol_parts: Vec<String> = sorted_ratios
123        .into_iter()
124        .map(|(instrument_id, ratio)| {
125            if ratio > 0 {
126                format!("({ratio}){}", instrument_id.symbol)
127            } else {
128                format!("(({})){}", ratio.abs(), instrument_id.symbol)
129            }
130        })
131        .collect();
132
133    Ok(InstrumentId::new(
134        Symbol::new(symbol_parts.join(GENERIC_SPREAD_ID_SEPARATOR)),
135        first_venue,
136    ))
137}
138
139/// Parses a generic spread instrument ID into `(instrument_id, ratio)` legs.
140///
141/// Accepts the format [`new_generic_spread_id`] produces and returns the legs in the order they
142/// appear in the symbol, with a negative ratio for each `((ratio))symbol` leg. Each ratio must be
143/// non-zero and contain only ASCII digits, so a sign inside the parentheses is rejected.
144///
145/// # Errors
146///
147/// Returns an error if:
148/// - The symbol does not contain [`GENERIC_SPREAD_ID_SEPARATOR`].
149/// - A leg is not in the `(ratio)symbol` or `((ratio))symbol` format.
150pub fn parse_generic_spread_id_legs(
151    instrument_id: &InstrumentId,
152) -> anyhow::Result<Vec<(InstrumentId, i64)>> {
153    let symbol = instrument_id.symbol.as_str();
154    anyhow::ensure!(
155        symbol.contains(GENERIC_SPREAD_ID_SEPARATOR),
156        "Invalid generic spread instrument ID: {instrument_id}"
157    );
158
159    symbol
160        .split(GENERIC_SPREAD_ID_SEPARATOR)
161        .map(|component| {
162            parse_generic_spread_leg(component, instrument_id.venue)
163                .ok_or_else(|| anyhow::anyhow!("Invalid generic spread leg component: {component}"))
164        })
165        .collect()
166}
167
168fn parse_generic_spread_leg(component: &str, venue: Venue) -> Option<(InstrumentId, i64)> {
169    if let Some(rest) = component.strip_prefix("((") {
170        let (ratio, symbol) = rest.split_once("))")?;
171        return parse_generic_spread_leg_parts(ratio, symbol, venue, -1);
172    }
173
174    let rest = component.strip_prefix('(')?;
175    let (ratio, symbol) = rest.split_once(')')?;
176    parse_generic_spread_leg_parts(ratio, symbol, venue, 1)
177}
178
179fn parse_generic_spread_leg_parts(
180    ratio: &str,
181    symbol: &str,
182    venue: Venue,
183    sign: i64,
184) -> Option<(InstrumentId, i64)> {
185    // Only digit ratios are valid: `parse::<i64>` would accept a leading sign,
186    // silently flipping the sign encoded by the surrounding parentheses.
187    if !ratio.bytes().all(|b| b.is_ascii_digit()) {
188        return None;
189    }
190
191    let ratio = ratio.parse::<i64>().ok()?.checked_mul(sign)?;
192    if ratio == 0 {
193        return None;
194    }
195
196    let symbol = Symbol::new_checked(symbol).ok()?;
197    Some((InstrumentId::new(symbol, venue), ratio))
198}
199
200impl_from_str_for_identifier!(account_id::AccountId);
201impl_from_str_for_identifier!(actor_id::ActorId);
202impl_from_str_for_identifier!(client_id::ClientId);
203impl_from_str_for_identifier!(client_order_id::ClientOrderId);
204impl_from_str_for_identifier!(component_id::ComponentId);
205impl_from_str_for_identifier!(exec_algorithm_id::ExecAlgorithmId);
206impl_from_str_for_identifier!(order_list_id::OrderListId);
207impl_from_str_for_identifier!(position_id::PositionId);
208impl_from_str_for_identifier!(strategy_id::StrategyId);
209impl_from_str_for_identifier!(symbol::Symbol);
210impl_from_str_for_identifier!(trade_id::TradeId);
211impl_from_str_for_identifier!(trader_id::TraderId);
212impl_from_str_for_identifier!(venue::Venue);
213impl_from_str_for_identifier!(venue_order_id::VenueOrderId);
214
215impl_serialization_for_identifier!(account_id::AccountId);
216impl_serialization_for_identifier!(actor_id::ActorId);
217impl_serialization_for_identifier!(client_id::ClientId);
218impl_serialization_for_identifier!(client_order_id::ClientOrderId);
219impl_serialization_for_identifier!(component_id::ComponentId);
220impl_serialization_for_identifier!(exec_algorithm_id::ExecAlgorithmId);
221impl_serialization_for_identifier!(order_list_id::OrderListId);
222impl_serialization_for_identifier!(position_id::PositionId);
223impl_serialization_for_identifier!(strategy_id::StrategyId);
224impl_serialization_for_identifier!(symbol::Symbol);
225impl_serialization_for_identifier!(trader_id::TraderId);
226impl_serialization_for_identifier!(venue::Venue);
227impl_serialization_for_identifier!(venue_order_id::VenueOrderId);
228
229impl_as_ref_for_identifier!(account_id::AccountId);
230impl_as_ref_for_identifier!(actor_id::ActorId);
231impl_as_ref_for_identifier!(client_id::ClientId);
232impl_as_ref_for_identifier!(client_order_id::ClientOrderId);
233impl_as_ref_for_identifier!(component_id::ComponentId);
234impl_as_ref_for_identifier!(exec_algorithm_id::ExecAlgorithmId);
235impl_as_ref_for_identifier!(order_list_id::OrderListId);
236impl_as_ref_for_identifier!(position_id::PositionId);
237impl_as_ref_for_identifier!(strategy_id::StrategyId);
238impl_as_ref_for_identifier!(symbol::Symbol);
239impl_as_ref_for_identifier!(trader_id::TraderId);
240impl_as_ref_for_identifier!(venue::Venue);
241impl_as_ref_for_identifier!(venue_order_id::VenueOrderId);
242
243/// Print interned string cache statistics for debugging purposes.
244pub fn interned_string_stats() {
245    ustr::string_cache_iter().for_each(|s| println!("{s}"));
246}
247
248#[cfg(test)]
249mod tests {
250    use rstest::rstest;
251
252    use super::{InstrumentId, new_generic_spread_id, parse_generic_spread_id_legs};
253
254    #[rstest]
255    fn test_new_generic_spread_id_sorts_and_formats_legs() {
256        let msft = InstrumentId::from("MSFT.NASDAQ");
257        let aapl = InstrumentId::from("AAPL.NASDAQ");
258
259        let spread = new_generic_spread_id(&[(msft, 1), (aapl, -2)]).unwrap();
260
261        assert_eq!(spread, InstrumentId::from("((2))AAPL___(1)MSFT.NASDAQ"));
262    }
263
264    #[rstest]
265    #[case(
266        vec![("MSFT.NASDAQ", 1)],
267        "instrument_ratios list needs to have at least 2 legs"
268    )]
269    #[case(vec![("MSFT.NASDAQ", 0), ("AAPL.NASDAQ", 1)], "ratio cannot be zero")]
270    #[case(
271        vec![("MSFT.NASDAQ", 1), ("AAPL.XNAS", 1)],
272        "All venues must match. Expected NASDAQ, was XNAS"
273    )]
274    #[case(vec![("MSFT.NASDAQ", i64::MIN), ("AAPL.NASDAQ", 1)], "ratio cannot be i64::MIN")]
275    fn test_new_generic_spread_id_rejects_invalid_legs(
276        #[case] legs: Vec<(&str, i64)>,
277        #[case] expected: &str,
278    ) {
279        let legs: Vec<(InstrumentId, i64)> = legs
280            .into_iter()
281            .map(|(instrument_id, ratio)| (InstrumentId::from(instrument_id), ratio))
282            .collect();
283
284        let result = new_generic_spread_id(&legs);
285
286        assert_eq!(result.unwrap_err().to_string(), expected);
287    }
288
289    #[rstest]
290    #[case("((-2))AAPL___(1)MSFT.NASDAQ", "((-2))AAPL")] // Signed ratio in negative leg
291    #[case("(+1)MSFT___(2)AAPL.NASDAQ", "(+1)MSFT")] // Signed ratio in positive leg
292    #[case("(-1)MSFT___(2)AAPL.NASDAQ", "(-1)MSFT")] // Signed ratio in positive leg
293    #[case("()MSFT___(2)AAPL.NASDAQ", "()MSFT")] // Empty ratio
294    #[case("(1a)MSFT___(2)AAPL.NASDAQ", "(1a)MSFT")] // Non-digit ratio
295    fn test_parse_generic_spread_id_legs_rejects_non_digit_ratios(
296        #[case] value: &str,
297        #[case] component: &str,
298    ) {
299        let result = parse_generic_spread_id_legs(&InstrumentId::from(value));
300
301        assert_eq!(
302            result.unwrap_err().to_string(),
303            format!("Invalid generic spread leg component: {component}")
304        );
305    }
306
307    #[rstest]
308    #[case("(0)MSFT___(2)AAPL.NASDAQ", "(0)MSFT")] // Zero ratio
309    #[case("(1)___(2)AAPL.NASDAQ", "(1)")] // Empty symbol
310    #[case("(1) ___(2)AAPL.NASDAQ", "(1) ")] // Whitespace symbol
311    #[case("MSFT___(2)AAPL.NASDAQ", "MSFT")] // Missing ratio
312    #[case(
313        "(9223372036854775808)MSFT___(2)AAPL.NASDAQ",
314        "(9223372036854775808)MSFT"
315    )] // Ratio overflows i64
316    fn test_parse_generic_spread_id_legs_rejects_malformed_legs(
317        #[case] value: &str,
318        #[case] component: &str,
319    ) {
320        let result = parse_generic_spread_id_legs(&InstrumentId::from(value));
321
322        assert_eq!(
323            result.unwrap_err().to_string(),
324            format!("Invalid generic spread leg component: {component}")
325        );
326    }
327
328    #[rstest]
329    fn test_parse_generic_spread_id_legs_rejects_id_without_separator() {
330        let result = parse_generic_spread_id_legs(&InstrumentId::from("(1)MSFT.NASDAQ"));
331
332        assert_eq!(
333            result.unwrap_err().to_string(),
334            "Invalid generic spread instrument ID: (1)MSFT.NASDAQ"
335        );
336    }
337
338    #[rstest]
339    fn test_generic_spread_id_round_trip() {
340        let spread = new_generic_spread_id(&[
341            (InstrumentId::from("ESM4 P5230.XCME"), -1),
342            (InstrumentId::from("ESM4 P5250.XCME"), 1),
343        ])
344        .unwrap();
345
346        assert_eq!(
347            parse_generic_spread_id_legs(&spread).unwrap(),
348            vec![
349                (InstrumentId::from("ESM4 P5230.XCME"), -1),
350                (InstrumentId::from("ESM4 P5250.XCME"), 1),
351            ]
352        );
353    }
354}