Skip to main content

nautilus_model/identifiers/
instrument_id.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//! Represents a valid instrument ID.
17
18use std::{
19    fmt::{Debug, Display},
20    hash::Hash,
21    str::FromStr,
22};
23
24use nautilus_core::correctness::{FAILED, check_valid_string_ascii, check_valid_string_utf8};
25use serde::{Deserialize, Deserializer, Serialize};
26
27#[cfg(feature = "defi")]
28use crate::defi::{Blockchain, validation::validate_address};
29use crate::identifiers::{Symbol, Venue};
30
31/// Represents a valid instrument ID.
32///
33/// The symbol and venue combination should uniquely identify the instrument.
34#[repr(C)]
35#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
36#[cfg_attr(
37    feature = "python",
38    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
39)]
40pub struct InstrumentId {
41    /// The instruments ticker symbol.
42    pub symbol: Symbol,
43    /// The instruments trading venue.
44    pub venue: Venue,
45}
46
47impl InstrumentId {
48    /// Creates a new [`InstrumentId`] instance.
49    #[must_use]
50    pub fn new(symbol: Symbol, venue: Venue) -> Self {
51        Self { symbol, venue }
52    }
53
54    #[must_use]
55    pub fn is_synthetic(&self) -> bool {
56        self.venue.is_synthetic()
57    }
58}
59
60impl InstrumentId {
61    /// # Errors
62    ///
63    /// Returns an error if parsing the string fails or string is invalid.
64    pub fn from_as_ref<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
65        Self::from_str(value.as_ref())
66    }
67
68    /// Extracts the blockchain from the venue if it's a DEX venue.
69    #[cfg(feature = "defi")]
70    #[must_use]
71    pub fn blockchain(&self) -> Option<Blockchain> {
72        self.venue
73            .parse_dex()
74            .map(|(blockchain, _)| blockchain)
75            .ok()
76    }
77}
78
79impl FromStr for InstrumentId {
80    type Err = anyhow::Error;
81
82    fn from_str(s: &str) -> anyhow::Result<Self> {
83        match s.rsplit_once('.') {
84            Some((symbol_part, venue_part)) => {
85                check_valid_string_utf8(symbol_part, stringify!(value))?;
86                check_valid_string_ascii(venue_part, stringify!(value))?;
87
88                let venue = Venue::new_checked(venue_part)?;
89
90                let symbol = {
91                    #[cfg(feature = "defi")]
92                    if venue.is_dex() {
93                        let validated_address = validate_address(symbol_part)
94                            .map_err(|e| anyhow::anyhow!(err_message(s, e.to_string())))?;
95                        Symbol::new(validated_address.to_string())
96                    } else {
97                        Symbol::new(symbol_part)
98                    }
99
100                    #[cfg(not(feature = "defi"))]
101                    Symbol::new(symbol_part)
102                };
103
104                Ok(Self { symbol, venue })
105            }
106            None => {
107                anyhow::bail!(err_message(
108                    s,
109                    "missing '.' separator between symbol and venue components".to_string()
110                ))
111            }
112        }
113    }
114}
115
116impl<T: AsRef<str>> From<T> for InstrumentId {
117    fn from(value: T) -> Self {
118        Self::from_str(value.as_ref()).expect(FAILED)
119    }
120}
121
122impl Debug for InstrumentId {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        write!(f, "\"{}.{}\"", self.symbol, self.venue)
125    }
126}
127
128impl Display for InstrumentId {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        write!(f, "{}.{}", self.symbol, self.venue)
131    }
132}
133
134impl Serialize for InstrumentId {
135    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
136    where
137        S: serde::Serializer,
138    {
139        serializer.serialize_str(&self.to_string())
140    }
141}
142
143impl<'de> Deserialize<'de> for InstrumentId {
144    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
145    where
146        D: Deserializer<'de>,
147    {
148        let instrument_id_str: &str = Deserialize::deserialize(deserializer)?;
149        Self::from_str(instrument_id_str).map_err(serde::de::Error::custom)
150    }
151}
152
153fn err_message(s: &str, e: String) -> String {
154    format!("Error parsing `InstrumentId` from '{s}': {e}")
155}
156
157#[cfg(test)]
158mod tests {
159    use std::str::FromStr;
160
161    use rstest::rstest;
162
163    use super::InstrumentId;
164    use crate::identifiers::stubs::*;
165
166    #[rstest]
167    fn test_instrument_id_parse_success(instrument_id_eth_usdt_binance: InstrumentId) {
168        assert_eq!(instrument_id_eth_usdt_binance.symbol.to_string(), "ETHUSDT");
169        assert_eq!(instrument_id_eth_usdt_binance.venue.to_string(), "BINANCE");
170    }
171
172    #[rstest]
173    #[should_panic(
174        expected = "Error parsing `InstrumentId` from 'ETHUSDT-BINANCE': missing '.' separator between symbol and venue components"
175    )]
176    fn test_instrument_id_parse_failure_no_dot() {
177        let _ = InstrumentId::from("ETHUSDT-BINANCE");
178    }
179
180    #[rstest]
181    fn test_string_reprs() {
182        let id = InstrumentId::from("ETH/USDT.BINANCE");
183        assert_eq!(id.to_string(), "ETH/USDT.BINANCE");
184        assert_eq!(format!("{id}"), "ETH/USDT.BINANCE");
185    }
186
187    #[rstest]
188    fn test_instrument_id_from_str_with_utf8_symbol() {
189        let non_ascii_symbol = "TËST-PÉRP";
190        let non_ascii_instrument = "TËST-PÉRP.BINANCE";
191
192        let id = InstrumentId::from_str(non_ascii_instrument).unwrap();
193        assert_eq!(id.symbol.to_string(), non_ascii_symbol);
194        assert_eq!(id.venue.to_string(), "BINANCE");
195        assert_eq!(id.to_string(), non_ascii_instrument);
196    }
197
198    #[cfg(feature = "defi")]
199    #[rstest]
200    fn test_blockchain_instrument_id_valid() {
201        let id =
202            InstrumentId::from("0xC31E54c7a869B9FcBEcc14363CF510d1c41fa443.Arbitrum:UniswapV3");
203        assert_eq!(
204            id.symbol.to_string(),
205            "0xC31E54c7a869B9FcBEcc14363CF510d1c41fa443"
206        );
207        assert_eq!(id.venue.to_string(), "Arbitrum:UniswapV3");
208    }
209
210    #[cfg(feature = "defi")]
211    #[rstest]
212    #[should_panic(
213        expected = "Error creating `Venue` from 'InvalidChain:UniswapV3': invalid blockchain venue 'InvalidChain:UniswapV3': chain 'InvalidChain' not recognized"
214    )]
215    fn test_blockchain_instrument_id_invalid_chain() {
216        let _ =
217            InstrumentId::from("0xC31E54c7a869B9FcBEcc14363CF510d1c41fa443.InvalidChain:UniswapV3");
218    }
219
220    #[cfg(feature = "defi")]
221    #[rstest]
222    #[should_panic(
223        expected = "Error creating `Venue` from 'Arbitrum:': invalid blockchain venue 'Arbitrum:': expected format 'Chain:DexId'"
224    )]
225    fn test_blockchain_instrument_id_empty_dex() {
226        let _ = InstrumentId::from("0xC31E54c7a869B9FcBEcc14363CF510d1c41fa443.Arbitrum:");
227    }
228
229    #[cfg(feature = "defi")]
230    #[rstest]
231    fn test_regular_venue_with_blockchain_like_name_but_without_dex() {
232        // Should work fine since it doesn't contain ':' (not a DEX venue)
233        let id = InstrumentId::from("0xC31E54c7a869B9FcBEcc14363CF510d1c41fa443.Ethereum");
234        assert_eq!(
235            id.symbol.to_string(),
236            "0xC31E54c7a869B9FcBEcc14363CF510d1c41fa443"
237        );
238        assert_eq!(id.venue.to_string(), "Ethereum");
239    }
240
241    #[cfg(feature = "defi")]
242    #[rstest]
243    #[should_panic(
244        expected = "Error parsing `InstrumentId` from 'invalidaddress.Ethereum:UniswapV3': Ethereum address must start with '0x': invalidaddress"
245    )]
246    fn test_blockchain_instrument_id_invalid_address_no_prefix() {
247        let _ = InstrumentId::from("invalidaddress.Ethereum:UniswapV3");
248    }
249
250    #[cfg(feature = "defi")]
251    #[rstest]
252    #[should_panic(
253        expected = "Error parsing `InstrumentId` from '0x123.Ethereum:UniswapV3': Blockchain address '0x123' is incorrect: odd number of digits"
254    )]
255    fn test_blockchain_instrument_id_invalid_address_short() {
256        let _ = InstrumentId::from("0x123.Ethereum:UniswapV3");
257    }
258
259    #[cfg(feature = "defi")]
260    #[rstest]
261    #[should_panic(
262        expected = "Error parsing `InstrumentId` from '0xC31E54c7a869B9FcBEcc14363CF510d1c41fa44G.Ethereum:UniswapV3': Blockchain address '0xC31E54c7a869B9FcBEcc14363CF510d1c41fa44G' is incorrect: invalid character 'G' at position 39"
263    )]
264    fn test_blockchain_instrument_id_invalid_address_non_hex() {
265        let _ = InstrumentId::from("0xC31E54c7a869B9FcBEcc14363CF510d1c41fa44G.Ethereum:UniswapV3");
266    }
267
268    #[cfg(feature = "defi")]
269    #[rstest]
270    #[should_panic(
271        expected = "Error parsing `InstrumentId` from '0xc31e54c7a869b9fcbecc14363cf510d1c41fa443.Ethereum:UniswapV3': Blockchain address '0xc31e54c7a869b9fcbecc14363cf510d1c41fa443' has incorrect checksum"
272    )]
273    fn test_blockchain_instrument_id_invalid_address_checksum() {
274        let _ = InstrumentId::from("0xc31e54c7a869b9fcbecc14363cf510d1c41fa443.Ethereum:UniswapV3");
275    }
276
277    #[cfg(feature = "defi")]
278    #[rstest]
279    fn test_blockchain_extraction_valid_dex() {
280        let id =
281            InstrumentId::from("0xC31E54c7a869B9FcBEcc14363CF510d1c41fa443.Arbitrum:UniswapV3");
282        let blockchain = id.blockchain();
283        assert!(blockchain.is_some());
284        assert_eq!(blockchain.unwrap(), crate::defi::Blockchain::Arbitrum);
285    }
286
287    #[cfg(feature = "defi")]
288    #[rstest]
289    fn test_blockchain_extraction_tradifi_venue() {
290        let id = InstrumentId::from("ETH/USDT.BINANCE");
291        let blockchain = id.blockchain();
292        assert!(blockchain.is_none());
293    }
294}