nautilus_model/identifiers/
venue.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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//! Represents a valid trading venue ID.
17
18use std::{
19    fmt::{Debug, Display, Formatter},
20    hash::Hash,
21};
22
23use nautilus_core::correctness::{check_valid_string, FAILED};
24use ustr::Ustr;
25
26use crate::venues::VENUE_MAP;
27
28pub const SYNTHETIC_VENUE: &str = "SYNTH";
29
30/// Represents a valid trading venue ID.
31#[repr(C)]
32#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
33#[cfg_attr(
34    feature = "python",
35    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
36)]
37pub struct Venue(Ustr);
38
39impl Venue {
40    /// Creates a new [`Venue`] instance with correctness checking.
41    ///
42    /// # Errors
43    ///
44    /// This function returns an error:
45    /// - If `value` is not a valid string.
46    ///
47    /// # Notes
48    ///
49    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
50    pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
51        let value = value.as_ref();
52        check_valid_string(value, stringify!(value))?;
53        Ok(Self(Ustr::from(value)))
54    }
55
56    /// Creates a new [`Venue`] instance.
57    ///
58    /// # Panics
59    ///
60    /// This function panics:
61    /// - If `value` is not a valid string.
62    pub fn new<T: AsRef<str>>(value: T) -> Self {
63        Self::new_checked(value).expect(FAILED)
64    }
65
66    /// Sets the inner identifier value.
67    pub(crate) fn set_inner(&mut self, value: &str) {
68        self.0 = Ustr::from(value);
69    }
70
71    /// Returns the inner identifier value.
72    #[must_use]
73    pub fn inner(&self) -> Ustr {
74        self.0
75    }
76
77    /// Returns the inner value as a string slice.
78    #[must_use]
79    pub fn as_str(&self) -> &str {
80        self.0.as_str()
81    }
82
83    #[must_use]
84    pub fn from_str_unchecked<T: AsRef<str>>(s: T) -> Self {
85        Self(Ustr::from(s.as_ref()))
86    }
87
88    #[must_use]
89    pub const fn from_ustr_unchecked(s: Ustr) -> Self {
90        Self(s)
91    }
92
93    pub fn from_code(code: &str) -> anyhow::Result<Self> {
94        let map_guard = VENUE_MAP
95            .lock()
96            .map_err(|e| anyhow::anyhow!("Error acquiring lock on `VENUE_MAP`: {e}"))?;
97        map_guard
98            .get(code)
99            .copied()
100            .ok_or_else(|| anyhow::anyhow!("Unknown venue code: {code}"))
101    }
102
103    #[must_use]
104    pub fn synthetic() -> Self {
105        // SAFETY: Unwrap safe as using known synthetic venue constant
106        Self::new(SYNTHETIC_VENUE)
107    }
108
109    #[must_use]
110    pub fn is_synthetic(&self) -> bool {
111        self.0.as_str() == SYNTHETIC_VENUE
112    }
113}
114
115impl Debug for Venue {
116    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
117        write!(f, "{:?}", self.0)
118    }
119}
120
121impl Display for Venue {
122    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
123        write!(f, "{}", self.0)
124    }
125}
126
127////////////////////////////////////////////////////////////////////////////////
128// Tests
129////////////////////////////////////////////////////////////////////////////////
130#[cfg(test)]
131mod tests {
132    use rstest::rstest;
133
134    use crate::identifiers::{stubs::*, Venue};
135
136    #[rstest]
137    fn test_string_reprs(venue_binance: Venue) {
138        assert_eq!(venue_binance.as_str(), "BINANCE");
139        assert_eq!(format!("{venue_binance}"), "BINANCE");
140    }
141}