Skip to main content

qx_core/
identity.rs

1//! 身份模型:多交易所的地基。
2//!
3//! 三层分离、绝不相互覆盖:
4//! - [`CanonicalProduct`] 研究表达(如 `BTC-USDT`)
5//! - [`InstrumentId`]   执行与估值(如 `BTCUSDT-PERP.BINANCE`)
6//! - 数据血缘由 `qx_guanxing` 的 `DataSourceId` 承担
7//!
8//! 子账户必须并入 [`VenueId`],否则同一 API key 下不同保证金模式/权限会被错误合并。
9
10use serde::{Deserialize, Serialize};
11use std::fmt;
12
13/// 没人声明时,账户账簿用哪种币记账 —— 全仓唯一写点。
14///
15/// 三条回落链都从这里取值:worker 没写 `settlement_currency`、同一账户日志的写入方
16/// 全都缺席、回测侧 market spec 没结算币种。字面量分头抄写时,一处改大盘子就跟着分叉
17/// (V13 §4 L2-6),所以 `tools/check_architecture.py` 的 `settlement_currency_check()`
18/// 钉住"生产代码里不得再出现 `"USDT"` 整串字面量"。
19///
20/// 它只是**缺省值**,不是合法币种白名单:任何非空字符串都是合法的 `settlement_currency`。
21pub const DEFAULT_SETTLEMENT_CURRENCY: &str = "USDT";
22
23/// 交易场所标识 = provider + region + account_set。
24#[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    /// 标的/产品级的 Binance 判定,全仓唯一一处:读的是 `InstrumentId` 里已经解析过的
36    /// venue 段(`BTCUSDT-PERP.BINANCE`),它必须是精确的一家交易所。
37    ///
38    /// 口径与 [`crate::VenueFamily::parse`] **故意不同**:`binance-testnet` 是 worker 的
39    /// 账户域(那里按子串认,见该模块说明),不是一种产品 venue,所以这里不能改成子串。
40    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/// 可交易工具标识 = native symbol + venue,点号分隔。
57#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
58pub struct InstrumentId {
59    symbol: String,
60    pub venue: VenueId,
61}
62
63impl InstrumentId {
64    /// Explicit sentinel identity for absent/legacy wire fields; it is not a tradeable product.
65    pub fn unknown() -> Self {
66        Self {
67            symbol: "UNKNOWN".into(),
68            venue: VenueId::new("UNKNOWN"),
69        }
70    }
71
72    /// Shared lexical guard for symbols received through textual identity boundaries.
73    /// Supports common spot (`BTC-USDT`, `BTC/USDT`) and derivative
74    /// (`BTC/USDT:USDT`) forms while excluding path and request syntax.
75    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    /// Construct a typed identity after validating the native symbol.
98    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    /// 解析 `"BTCUSDT-PERP.BINANCE"` → symbol=`BTCUSDT-PERP`, venue=`BINANCE`
108    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/// 交易所原生市场标识 = venue + raw_symbol(用于符号映射)。
151#[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/// 规范化产品:只用于研究与策略表达,不用于成交。
164#[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}