Skip to main content

nautilus_bybit/common/
symbol.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//! Helpers for working with Bybit-specific symbol strings.
17
18use std::{borrow::Cow, fmt::Display};
19
20use nautilus_model::identifiers::{InstrumentId, Symbol};
21use ustr::Ustr;
22
23use super::{consts::BYBIT_VENUE, enums::BybitProductType};
24
25const VALID_SUFFIXES: &[&str] = &["-SPOT", "-LINEAR", "-INVERSE", "-OPTION"];
26
27/// Returns true if the supplied value contains a recognised Bybit product suffix.
28fn has_valid_suffix(value: &str) -> bool {
29    VALID_SUFFIXES.iter().any(|suffix| value.contains(suffix))
30}
31
32/// Represents a Bybit symbol augmented with a product-type suffix.
33#[derive(Clone, Debug, Eq, PartialEq, Hash)]
34pub struct BybitSymbol {
35    value: Ustr,
36}
37
38impl BybitSymbol {
39    /// Creates a new [`BybitSymbol`] after validating the suffix and normalising to upper case.
40    ///
41    /// # Errors
42    ///
43    /// Returns an error if the value does not contain one of the recognised Bybit suffixes.
44    pub fn new<S: AsRef<str>>(value: S) -> anyhow::Result<Self> {
45        let value_ref = value.as_ref();
46        let needs_upper = value_ref.bytes().any(|b| b.is_ascii_lowercase());
47        let normalised: Cow<'_, str> = if needs_upper {
48            Cow::Owned(value_ref.to_ascii_uppercase())
49        } else {
50            Cow::Borrowed(value_ref)
51        };
52        anyhow::ensure!(
53            has_valid_suffix(normalised.as_ref()),
54            "invalid Bybit symbol '{value_ref}': expected suffix in {VALID_SUFFIXES:?}"
55        );
56        Ok(Self {
57            value: Ustr::from(normalised.as_ref()),
58        })
59    }
60
61    /// Returns the underlying symbol without the Bybit suffix.
62    #[must_use]
63    pub fn raw_symbol(&self) -> &str {
64        self.value
65            .rsplit_once('-')
66            .map_or(self.value.as_str(), |(prefix, _)| prefix)
67    }
68
69    /// Returns the product type identified by the suffix.
70    ///
71    /// # Panics
72    ///
73    /// Panics if the symbol has no valid suffix (unreachable after construction).
74    #[must_use]
75    pub fn product_type(&self) -> BybitProductType {
76        BybitProductType::from_suffix(self.value.as_str())
77            .expect("symbol checked for suffix during construction")
78    }
79
80    /// Returns the instrument identifier corresponding to this symbol.
81    #[must_use]
82    pub fn to_instrument_id(&self) -> InstrumentId {
83        InstrumentId::new(Symbol::from_ustr_unchecked(self.value), *BYBIT_VENUE)
84    }
85
86    /// Returns the symbol value as `Ustr`.
87    #[must_use]
88    pub fn as_ustr(&self) -> Ustr {
89        self.value
90    }
91}
92
93impl Display for BybitSymbol {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.write_str(self.value.as_str())
96    }
97}
98
99impl TryFrom<&str> for BybitSymbol {
100    type Error = anyhow::Error;
101
102    fn try_from(value: &str) -> anyhow::Result<Self> {
103        Self::new(value)
104    }
105}
106
107impl TryFrom<String> for BybitSymbol {
108    type Error = anyhow::Error;
109
110    fn try_from(value: String) -> anyhow::Result<Self> {
111        Self::new(value)
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use rstest::rstest;
118
119    use super::*;
120
121    #[rstest]
122    fn new_valid_symbol_is_uppercased() {
123        let symbol = BybitSymbol::new("btcusdt-linear").unwrap();
124        assert_eq!(symbol.to_string(), "BTCUSDT-LINEAR");
125    }
126
127    #[rstest]
128    fn new_invalid_symbol_errors() {
129        let err = BybitSymbol::new("BTCUSDT").unwrap_err();
130        assert!(format!("{err}").contains("expected suffix"));
131    }
132
133    #[rstest]
134    fn raw_symbol_strips_suffix() {
135        let symbol = BybitSymbol::new("ETH-26JUN26-16000-P-OPTION").unwrap();
136        assert_eq!(symbol.raw_symbol(), "ETH-26JUN26-16000-P");
137    }
138
139    #[rstest]
140    fn product_type_detection_matches_suffix() {
141        let linear = BybitSymbol::new("BTCUSDT-LINEAR").unwrap();
142        assert!(linear.product_type().is_linear());
143
144        let inverse = BybitSymbol::new("BTCUSD-INVERSE").unwrap();
145        assert!(inverse.product_type().is_inverse());
146
147        let spot = BybitSymbol::new("ETHUSDT-SPOT").unwrap();
148        assert!(spot.product_type().is_spot());
149
150        let option = BybitSymbol::new("ETH-26JUN26-16000-P-OPTION").unwrap();
151        assert!(option.product_type().is_option());
152    }
153
154    #[rstest]
155    fn instrument_id_uses_bybit_venue() {
156        let symbol = BybitSymbol::new("BTCUSDT-LINEAR").unwrap();
157        let instrument_id = symbol.to_instrument_id();
158        assert_eq!(instrument_id.to_string(), "BTCUSDT-LINEAR.BYBIT");
159    }
160}