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