use serde::{Deserialize, Serialize};
use std::fmt;
pub const DEFAULT_SETTLEMENT_CURRENCY: &str = "USDT";
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct VenueId(pub String);
impl VenueId {
pub fn new(s: impl Into<String>) -> Self {
Self(s.into().to_uppercase())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_binance(&self) -> bool {
self.0.eq_ignore_ascii_case("BINANCE")
}
}
impl fmt::Debug for VenueId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl fmt::Display for VenueId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
pub struct InstrumentId {
symbol: String,
pub venue: VenueId,
}
impl InstrumentId {
pub fn unknown() -> Self {
Self {
symbol: "UNKNOWN".into(),
venue: VenueId::new("UNKNOWN"),
}
}
pub fn is_valid_symbol(symbol: &str) -> bool {
if symbol.is_empty()
|| symbol.len() > 128
|| symbol.starts_with(|c: char| {
c.is_ascii_alphabetic() && symbol.as_bytes().get(1) == Some(&b':')
})
{
return false;
}
let mut previous_separator = true;
for byte in symbol.bytes() {
if byte.is_ascii_alphanumeric() {
previous_separator = false;
} else if matches!(byte, b'/' | b':' | b'_' | b'-') && !previous_separator {
previous_separator = true;
} else {
return false;
}
}
!previous_separator
}
pub fn new(symbol: impl Into<String>, venue: VenueId) -> Option<Self> {
let symbol = symbol.into();
Self::is_valid_symbol(&symbol).then_some(Self { symbol, venue })
}
pub fn symbol(&self) -> &str {
&self.symbol
}
pub fn parse(s: &str) -> Option<Self> {
let (sym, ven) = s.rsplit_once('.')?;
if !Self::is_valid_symbol(sym) || ven.is_empty() {
return None;
}
Self::new(sym, VenueId::new(ven))
}
}
impl<'de> Deserialize<'de> for InstrumentId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct RawInstrumentId {
symbol: String,
venue: VenueId,
}
let raw = RawInstrumentId::deserialize(deserializer)?;
if !InstrumentId::is_valid_symbol(&raw.symbol) {
return Err(serde::de::Error::custom("invalid instrument symbol"));
}
Ok(Self {
symbol: raw.symbol,
venue: raw.venue,
})
}
}
impl fmt::Debug for InstrumentId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}", self.symbol, self.venue)
}
}
impl fmt::Display for InstrumentId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}", self.symbol, self.venue)
}
}
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize)]
pub struct MarketId {
pub venue: VenueId,
pub raw_symbol: String,
}
impl fmt::Display for MarketId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.venue, self.raw_symbol)
}
}
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize)]
pub struct CanonicalProduct {
pub base: String,
pub quote: String,
}
impl CanonicalProduct {
pub fn new(base: impl Into<String>, quote: impl Into<String>) -> Self {
Self {
base: base.into().to_uppercase(),
quote: quote.into().to_uppercase(),
}
}
}
impl fmt::Display for CanonicalProduct {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}", self.base, self.quote)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_instrument_id() {
let id = InstrumentId::parse("BTCUSDT-PERP.BINANCE").unwrap();
assert_eq!(id.symbol(), "BTCUSDT-PERP");
assert_eq!(id.venue.as_str(), "BINANCE");
assert_eq!(format!("{}", id), "BTCUSDT-PERP.BINANCE");
}
#[test]
fn canonical_is_not_instrument() {
let c = CanonicalProduct::new("btc", "usdt");
assert_eq!(format!("{}", c), "BTC-USDT");
}
#[test]
fn instrument_symbol_validation_accepts_market_forms_and_rejects_path_syntax() {
for symbol in ["BTCUSDT", "000001", "BTC-USDT", "BTC/USDT:USDT", "BTC_USDT"] {
assert!(InstrumentId::is_valid_symbol(symbol), "{symbol}");
assert!(InstrumentId::parse(&format!("{symbol}.BINANCE")).is_some());
}
for symbol in [
"",
"../../etc/passwd",
"/etc/passwd",
"C:temp",
"BTC?USDT",
"BTC\nUSDT",
"BTC.USDT",
"BTC--USDT",
"BTC/",
"é",
] {
assert!(!InstrumentId::is_valid_symbol(symbol), "{symbol:?}");
assert!(InstrumentId::parse(&format!("{symbol}.BINANCE")).is_none());
}
assert!(!InstrumentId::is_valid_symbol(&"A".repeat(129)));
assert!(InstrumentId::new("BTC/USDT:USDT", VenueId::new("BINANCE")).is_some());
assert!(InstrumentId::new("../../etc/passwd", VenueId::new("BINANCE")).is_none());
}
#[test]
fn instrument_id_deserialization_uses_the_shared_symbol_guard() {
let id = InstrumentId::new("BTC/USDT:USDT", VenueId::new("BINANCE")).unwrap();
let serialized = serde_json::to_value(&id).unwrap();
assert_eq!(serialized["symbol"], "BTC/USDT:USDT");
assert_eq!(serialized["venue"], "BINANCE");
assert!(serde_json::from_value::<InstrumentId>(serialized).is_ok());
assert!(serde_json::from_str::<InstrumentId>(
r#"{"symbol":"../../etc/passwd","venue":"BINANCE"}"#
)
.is_err());
}
}