1use serde::{Deserialize, Serialize};
11use std::fmt;
12
13pub const DEFAULT_SETTLEMENT_CURRENCY: &str = "USDT";
22
23#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
25pub struct VenueId(pub String);
26
27impl VenueId {
28 pub fn new(s: impl Into<String>) -> Self {
29 Self(s.into().to_uppercase())
30 }
31 pub fn as_str(&self) -> &str {
32 &self.0
33 }
34
35 pub fn is_binance(&self) -> bool {
41 self.0.eq_ignore_ascii_case("BINANCE")
42 }
43}
44
45impl fmt::Debug for VenueId {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 write!(f, "{}", self.0)
48 }
49}
50impl fmt::Display for VenueId {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 write!(f, "{}", self.0)
53 }
54}
55
56#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
58pub struct InstrumentId {
59 symbol: String,
60 pub venue: VenueId,
61}
62
63impl InstrumentId {
64 pub fn unknown() -> Self {
66 Self {
67 symbol: "UNKNOWN".into(),
68 venue: VenueId::new("UNKNOWN"),
69 }
70 }
71
72 pub fn is_valid_symbol(symbol: &str) -> bool {
76 if symbol.is_empty()
77 || symbol.len() > 128
78 || symbol.starts_with(|c: char| {
79 c.is_ascii_alphabetic() && symbol.as_bytes().get(1) == Some(&b':')
80 })
81 {
82 return false;
83 }
84 let mut previous_separator = true;
85 for byte in symbol.bytes() {
86 if byte.is_ascii_alphanumeric() {
87 previous_separator = false;
88 } else if matches!(byte, b'/' | b':' | b'_' | b'-') && !previous_separator {
89 previous_separator = true;
90 } else {
91 return false;
92 }
93 }
94 !previous_separator
95 }
96
97 pub fn new(symbol: impl Into<String>, venue: VenueId) -> Option<Self> {
99 let symbol = symbol.into();
100 Self::is_valid_symbol(&symbol).then_some(Self { symbol, venue })
101 }
102
103 pub fn symbol(&self) -> &str {
104 &self.symbol
105 }
106
107 pub fn parse(s: &str) -> Option<Self> {
109 let (sym, ven) = s.rsplit_once('.')?;
110 if !Self::is_valid_symbol(sym) || ven.is_empty() {
111 return None;
112 }
113 Self::new(sym, VenueId::new(ven))
114 }
115}
116
117impl<'de> Deserialize<'de> for InstrumentId {
118 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
119 where
120 D: serde::Deserializer<'de>,
121 {
122 #[derive(Deserialize)]
123 struct RawInstrumentId {
124 symbol: String,
125 venue: VenueId,
126 }
127
128 let raw = RawInstrumentId::deserialize(deserializer)?;
129 if !InstrumentId::is_valid_symbol(&raw.symbol) {
130 return Err(serde::de::Error::custom("invalid instrument symbol"));
131 }
132 Ok(Self {
133 symbol: raw.symbol,
134 venue: raw.venue,
135 })
136 }
137}
138
139impl fmt::Debug for InstrumentId {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 write!(f, "{}.{}", self.symbol, self.venue)
142 }
143}
144impl fmt::Display for InstrumentId {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 write!(f, "{}.{}", self.symbol, self.venue)
147 }
148}
149
150#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize)]
152pub struct MarketId {
153 pub venue: VenueId,
154 pub raw_symbol: String,
155}
156
157impl fmt::Display for MarketId {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 write!(f, "{}:{}", self.venue, self.raw_symbol)
160 }
161}
162
163#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize)]
165pub struct CanonicalProduct {
166 pub base: String,
167 pub quote: String,
168}
169
170impl CanonicalProduct {
171 pub fn new(base: impl Into<String>, quote: impl Into<String>) -> Self {
172 Self {
173 base: base.into().to_uppercase(),
174 quote: quote.into().to_uppercase(),
175 }
176 }
177}
178
179impl fmt::Display for CanonicalProduct {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 write!(f, "{}-{}", self.base, self.quote)
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn parse_instrument_id() {
191 let id = InstrumentId::parse("BTCUSDT-PERP.BINANCE").unwrap();
192 assert_eq!(id.symbol(), "BTCUSDT-PERP");
193 assert_eq!(id.venue.as_str(), "BINANCE");
194 assert_eq!(format!("{}", id), "BTCUSDT-PERP.BINANCE");
195 }
196
197 #[test]
198 fn canonical_is_not_instrument() {
199 let c = CanonicalProduct::new("btc", "usdt");
200 assert_eq!(format!("{}", c), "BTC-USDT");
201 }
202
203 #[test]
204 fn instrument_symbol_validation_accepts_market_forms_and_rejects_path_syntax() {
205 for symbol in ["BTCUSDT", "000001", "BTC-USDT", "BTC/USDT:USDT", "BTC_USDT"] {
206 assert!(InstrumentId::is_valid_symbol(symbol), "{symbol}");
207 assert!(InstrumentId::parse(&format!("{symbol}.BINANCE")).is_some());
208 }
209 for symbol in [
210 "",
211 "../../etc/passwd",
212 "/etc/passwd",
213 "C:temp",
214 "BTC?USDT",
215 "BTC\nUSDT",
216 "BTC.USDT",
217 "BTC--USDT",
218 "BTC/",
219 "é",
220 ] {
221 assert!(!InstrumentId::is_valid_symbol(symbol), "{symbol:?}");
222 assert!(InstrumentId::parse(&format!("{symbol}.BINANCE")).is_none());
223 }
224 assert!(!InstrumentId::is_valid_symbol(&"A".repeat(129)));
225 assert!(InstrumentId::new("BTC/USDT:USDT", VenueId::new("BINANCE")).is_some());
226 assert!(InstrumentId::new("../../etc/passwd", VenueId::new("BINANCE")).is_none());
227 }
228
229 #[test]
230 fn instrument_id_deserialization_uses_the_shared_symbol_guard() {
231 let id = InstrumentId::new("BTC/USDT:USDT", VenueId::new("BINANCE")).unwrap();
232 let serialized = serde_json::to_value(&id).unwrap();
233 assert_eq!(serialized["symbol"], "BTC/USDT:USDT");
234 assert_eq!(serialized["venue"], "BINANCE");
235 assert!(serde_json::from_value::<InstrumentId>(serialized).is_ok());
236 assert!(serde_json::from_str::<InstrumentId>(
237 r#"{"symbol":"../../etc/passwd","venue":"BINANCE"}"#
238 )
239 .is_err());
240 }
241}