Skip to main content

qx_zhenlu/
venue_capabilities.rs

1//! Executable capability declarations for order-routing venues.
2
3use qx_core::Order;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum VenueOrderType {
7    Market,
8    Limit,
9    Trigger,
10    StopLoss,
11    TakeProfit,
12    Trailing,
13}
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum VenueMarketScope {
17    InstrumentVenue,
18    BinanceSpot,
19    RuntimeConfigured,
20}
21
22/// A venue's declared execution surface. Empty/false fields mean unsupported and are
23/// rejected at the shared execution boundary; adapters must not infer support from a
24/// successful transport call.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct VenueCapabilities {
27    pub market_scope: VenueMarketScope,
28    pub exact_orders: bool,
29    pub order_types: &'static [VenueOrderType],
30    pub data_tiers: &'static [&'static str],
31    pub cancel: bool,
32    pub query: bool,
33    pub reconciliation: bool,
34    pub idempotent_client_order_id: bool,
35}
36
37const MARKET_AND_LIMIT: &[VenueOrderType] = &[VenueOrderType::Market, VenueOrderType::Limit];
38const CCXT_ORDER_TYPES: &[VenueOrderType] = &[
39    VenueOrderType::Market,
40    VenueOrderType::Limit,
41    VenueOrderType::Trigger,
42    VenueOrderType::StopLoss,
43    VenueOrderType::TakeProfit,
44    VenueOrderType::Trailing,
45];
46
47pub const PAPER_VENUE_CAPABILITIES: VenueCapabilities = VenueCapabilities {
48    market_scope: VenueMarketScope::InstrumentVenue,
49    exact_orders: true,
50    order_types: MARKET_AND_LIMIT,
51    data_tiers: &[],
52    cancel: true,
53    query: true,
54    reconciliation: false,
55    idempotent_client_order_id: true,
56};
57
58pub const BINANCE_SPOT_VENUE_CAPABILITIES: VenueCapabilities = VenueCapabilities {
59    market_scope: VenueMarketScope::BinanceSpot,
60    exact_orders: true,
61    order_types: MARKET_AND_LIMIT,
62    data_tiers: &[],
63    cancel: true,
64    query: true,
65    reconciliation: true,
66    idempotent_client_order_id: true,
67};
68
69pub const CCXT_PROCESS_VENUE_CAPABILITIES: VenueCapabilities = VenueCapabilities {
70    market_scope: VenueMarketScope::RuntimeConfigured,
71    exact_orders: true,
72    order_types: CCXT_ORDER_TYPES,
73    data_tiers: &[],
74    cancel: true,
75    query: true,
76    reconciliation: true,
77    idempotent_client_order_id: false,
78};
79
80impl VenueCapabilities {
81    pub fn validate_submit(&self, order: &Order, venue_id: &str) -> Result<(), String> {
82        if order.exact_amounts.is_some() && !self.exact_orders {
83            return Err("该 Venue 尚未贯通精确订单金额,拒绝提交".into());
84        }
85        match self.market_scope {
86            VenueMarketScope::InstrumentVenue => {}
87            VenueMarketScope::BinanceSpot
88                if order.instrument.venue.is_binance()
89                    && !order
90                        .instrument
91                        .symbol()
92                        .to_ascii_uppercase()
93                        .contains("-PERP") => {}
94            VenueMarketScope::RuntimeConfigured
95                if order
96                    .instrument
97                    .venue
98                    .as_str()
99                    .eq_ignore_ascii_case(configured_market_venue(venue_id)) => {}
100            scope => {
101                return Err(format!(
102                    "FAIL_CLOSED: Instrument market 不在 Venue 声明范围内(scope={scope:?}, instrument={}, venue={venue_id})",
103                    order.instrument
104                ));
105            }
106        }
107        let order_type = order
108            .exact_amounts
109            .and_then(|amounts| amounts.conditional)
110            .map(|intent| match intent.kind {
111                qx_core::ConditionalOrderKind::Trigger => VenueOrderType::Trigger,
112                qx_core::ConditionalOrderKind::StopLoss => VenueOrderType::StopLoss,
113                qx_core::ConditionalOrderKind::TakeProfit => VenueOrderType::TakeProfit,
114                qx_core::ConditionalOrderKind::Trailing => VenueOrderType::Trailing,
115            })
116            .unwrap_or_else(|| {
117                if order.limit_price_decimal().is_some() {
118                    VenueOrderType::Limit
119                } else {
120                    VenueOrderType::Market
121                }
122            });
123        if !self.order_types.contains(&order_type) {
124            return Err(format!(
125                "FAIL_CLOSED: Venue 未声明 {:?} 订单能力,拒绝注册/提交",
126                order_type
127            ));
128        }
129        Ok(())
130    }
131
132    pub fn validate_cancel(&self) -> Result<(), String> {
133        if !self.cancel {
134            return Err("FAIL_CLOSED: Venue 未声明撤单能力,拒绝调用撤单入口".into());
135        }
136        Ok(())
137    }
138
139    pub fn validate_query(&self) -> Result<(), String> {
140        if !self.query {
141            return Err("FAIL_CLOSED: Venue 未声明查询能力,拒绝调用查询入口".into());
142        }
143        Ok(())
144    }
145
146    pub fn require_query(&self) -> qx_core::QxResult<()> {
147        self.validate_query()
148            .map_err(qx_core::QxError::BusinessViolation)
149    }
150
151    pub fn validate_reconciliation(&self) -> Result<(), String> {
152        if !self.reconciliation {
153            return Err("FAIL_CLOSED: Venue 未声明对账能力,拒绝调用对账入口".into());
154        }
155        Ok(())
156    }
157
158    pub fn require_reconciliation(&self) -> qx_core::QxResult<()> {
159        self.validate_reconciliation()
160            .map_err(qx_core::QxError::BusinessViolation)
161    }
162}
163
164fn configured_market_venue(venue_id: &str) -> &str {
165    venue_id
166        .get(..5)
167        .filter(|prefix| prefix.eq_ignore_ascii_case("ccxt-"))
168        .map_or(venue_id, |_| &venue_id[5..])
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use qx_core::{
175        ConditionalOrderIntent, ConditionalOrderKind, ExactDecimal, ExactOrderAmounts,
176        InstrumentId, OrderStatus, Quantity, Side,
177    };
178
179    #[test]
180    fn venue_submit_gate_rejects_exact_values_when_capability_is_not_declared() {
181        let order = Order {
182            client_id: 1,
183            instrument: InstrumentId::parse("PEPE/USDT.OKX").unwrap(),
184            side: Side::Buy,
185            qty: Quantity::ZERO,
186            limit: None,
187            status: OrderStatus::PendingSubmit,
188            filled: Quantity::ZERO,
189            account_id: "main".into(),
190            trace: None,
191            policy: None,
192            exact_amounts: Some(ExactOrderAmounts {
193                quantity: ExactDecimal::parse("1000.0000000001").unwrap(),
194                limit_price: None,
195                filled: ExactDecimal::ZERO,
196                market_reference_price: None,
197                quote_budget: None,
198                quote_filled: Default::default(),
199                conditional: None,
200            }),
201        };
202        assert!(PAPER_VENUE_CAPABILITIES
203            .validate_submit(&order, "paper")
204            .is_ok());
205        assert!(CCXT_PROCESS_VENUE_CAPABILITIES
206            .validate_submit(&order, "ccxt-okx")
207            .is_ok());
208
209        let mut conditional = order;
210        conditional.exact_amounts.as_mut().unwrap().conditional = Some(ConditionalOrderIntent {
211            kind: ConditionalOrderKind::Trigger,
212            trigger_price: Some(ExactDecimal::parse("0.01").unwrap()),
213            trigger_price_type: None,
214            trailing_percent: None,
215            trailing_amount: None,
216            trailing_trigger_price: None,
217        });
218        assert!(PAPER_VENUE_CAPABILITIES
219            .validate_submit(&conditional, "paper")
220            .unwrap_err()
221            .contains("未声明 Trigger 订单能力"));
222        assert!(CCXT_PROCESS_VENUE_CAPABILITIES
223            .validate_submit(&conditional, "ccxt-okx")
224            .is_ok());
225    }
226}