nautilus_model/identifiers/
venue.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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::{FAILED, check_valid_string};
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 = "posei_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    /// Returns an error if `value` is not a valid string.
45    ///
46    /// # Notes
47    ///
48    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
49    pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
50        let value = value.as_ref();
51        check_valid_string(value, stringify!(value))?;
52        Ok(Self(Ustr::from(value)))
53    }
54
55    /// Creates a new [`Venue`] instance.
56    ///
57    /// # Panics
58    ///
59    /// Panics if `value` is not a valid string.
60    pub fn new<T: AsRef<str>>(value: T) -> Self {
61        Self::new_checked(value).expect(FAILED)
62    }
63
64    /// Sets the inner identifier value.
65    #[allow(dead_code)]
66    pub(crate) fn set_inner(&mut self, value: &str) {
67        self.0 = Ustr::from(value);
68    }
69
70    /// Returns the inner identifier value.
71    #[must_use]
72    pub fn inner(&self) -> Ustr {
73        self.0
74    }
75
76    /// Returns the inner value as a string slice.
77    #[must_use]
78    pub fn as_str(&self) -> &str {
79        self.0.as_str()
80    }
81
82    #[must_use]
83    pub fn from_str_unchecked<T: AsRef<str>>(s: T) -> Self {
84        Self(Ustr::from(s.as_ref()))
85    }
86
87    #[must_use]
88    pub const fn from_ustr_unchecked(s: Ustr) -> Self {
89        Self(s)
90    }
91
92    /// # Errors
93    ///
94    /// Returns an error if the venue code is unknown or lock on venue map fails.
95    pub fn from_code(code: &str) -> anyhow::Result<Self> {
96        let map_guard = VENUE_MAP
97            .lock()
98            .map_err(|e| anyhow::anyhow!("Error acquiring lock on `VENUE_MAP`: {e}"))?;
99        map_guard
100            .get(code)
101            .copied()
102            .ok_or_else(|| anyhow::anyhow!("Unknown venue code: {code}"))
103    }
104
105    #[must_use]
106    pub fn synthetic() -> Self {
107        // SAFETY: Unwrap safe as using known synthetic venue constant
108        Self::new(SYNTHETIC_VENUE)
109    }
110
111    #[must_use]
112    pub fn is_synthetic(&self) -> bool {
113        self.0.as_str() == SYNTHETIC_VENUE
114    }
115}
116
117impl Debug for Venue {
118    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
119        write!(f, "{:?}", self.0)
120    }
121}
122
123impl Display for Venue {
124    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
125        write!(f, "{}", self.0)
126    }
127}
128
129////////////////////////////////////////////////////////////////////////////////
130// Tests
131////////////////////////////////////////////////////////////////////////////////
132#[cfg(test)]
133mod tests {
134    use rstest::rstest;
135
136    use crate::identifiers::{Venue, stubs::*};
137
138    #[rstest]
139    fn test_string_reprs(venue_binance: Venue) {
140        assert_eq!(venue_binance.as_str(), "BINANCE");
141        assert_eq!(format!("{venue_binance}"), "BINANCE");
142    }
143}