Skip to main content

qx_execution/
application.rs

1//! 应用层端口。
2//!
3//! 原 `qx-application` crate,V10 P2a 按"端口即执行事实契约,归执行网关"并入本 crate。
4//! 这里不拥有 EventLog、数据库或具体 Venue;只定义执行编排需要的稳定事实和
5//! 端口。Runtime、Storage、Paper、CCXT 和 Binance 通过 adapter 实现这些端口,
6//! 避免应用服务反向依赖某个运行时具体类型。
7
8pub use qx_core::{
9    Fill, InstrumentId, Order, OrderPolicy, OrderStatus, OrderTrace, Price, Quantity, Side,
10    TradingInstrumentSpec, TradingProduct,
11};
12use qx_guanxing::QuoteTick;
13pub use qx_zhenlu::venue_capabilities::{
14    VenueCapabilities, VenueMarketScope, VenueOrderType, PAPER_VENUE_CAPABILITIES,
15};
16
17#[derive(Clone, PartialEq, Eq, Debug)]
18pub enum ExecutionEvent {
19    Accepted {
20        client_order_id: u64,
21        venue_order_id: String,
22    },
23    Rejected {
24        client_order_id: u64,
25        reason: String,
26    },
27    Fill(Box<Fill>),
28    FeeAdjustment {
29        account_id: String,
30        venue_id: String,
31        order_id: u64,
32        instrument: InstrumentId,
33        fees: Vec<qx_core::FillFee>,
34    },
35    FillWithSpec {
36        fill: Box<Fill>,
37        spec: Box<TradingInstrumentSpec>,
38    },
39    /// Persisted before the cancel side effect; a restart must reconcile this operation.
40    CancelPending {
41        client_order_id: u64,
42    },
43    /// Persisted before a venue amend side effect; retries after an unknown result are forbidden.
44    OrderAmendmentPending {
45        operation_id: String,
46        order: Box<Order>,
47    },
48    OrderAmended {
49        operation_id: String,
50        order: Box<Order>,
51    },
52    Cancelled {
53        client_order_id: u64,
54    },
55    ReconcileRequired {
56        client_order_id: u64,
57    },
58    /// 行情事实。撮合前必须先落行情事件,使 Paper 与 Live 共享同一道行情门禁。
59    MarketQuote {
60        instrument: InstrumentId,
61        quote: QuoteTick,
62    },
63}
64
65/// A venue's response to one atomic group submission. `venue_group_id` identifies
66/// the exchange-side order-list/resource (for example an OCO list), while each
67/// child event retains its own exchange order ID and fills.
68#[derive(Clone, PartialEq, Eq, Debug)]
69pub struct OrderGroupSubmission {
70    pub venue_group_id: Option<String>,
71    pub group_status: Option<qx_core::OrderGroupStatus>,
72    pub events: Vec<ExecutionEvent>,
73}
74
75#[derive(Clone, PartialEq, Eq, Debug)]
76pub struct ExecutionEventEnvelope {
77    pub event: ExecutionEvent,
78    pub event_ts: u64,
79    pub receive_ts: u64,
80    pub source_seq: u64,
81    pub correlation_id: String,
82}
83
84/// Result of appending an execution fact to a store with durable deduplication.
85/// `Duplicate` means the same correlation was already committed and the caller
86/// must not repeat the external side effect associated with that fact.
87#[derive(Clone, Copy, PartialEq, Eq, Debug)]
88pub enum EventAppendOutcome {
89    Appended,
90    Duplicate,
91}
92
93pub trait EventAppender {
94    fn append_execution_event(&mut self, envelope: ExecutionEventEnvelope) -> Result<(), String>;
95
96    /// Append a fact and report whether this call committed it. Persistent
97    /// implementations that support idempotency should override this method.
98    /// The default preserves compatibility for append-only adapters without a
99    /// duplicate receipt; production cancel paths use the Runtime override.
100    fn append_execution_event_with_outcome(
101        &mut self,
102        envelope: ExecutionEventEnvelope,
103    ) -> Result<EventAppendOutcome, String> {
104        self.append_execution_event(envelope)?;
105        Ok(EventAppendOutcome::Appended)
106    }
107}
108
109pub trait OrderStore {
110    fn orders(&self) -> Vec<Order>;
111
112    fn refresh_order_state(&mut self) -> Result<(), String> {
113        Ok(())
114    }
115
116    fn has_pending_amendment(&self, _client_order_id: u64) -> bool {
117        false
118    }
119
120    fn register_order(
121        &mut self,
122        order: Order,
123        ts: u64,
124        correlation_id: Option<String>,
125    ) -> Result<(), String>;
126}
127
128pub trait ExecutionEventPort: EventAppender + OrderStore {}
129
130impl<T: EventAppender + OrderStore> ExecutionEventPort for T {}
131
132/// 只读的账本条目计数,用于执行结果摘要;实现者不必暴露 Ledger 结构。
133pub trait LedgerProbe {
134    fn ledger_entry_count(&self) -> usize;
135}
136
137/// 风控端口对单笔订单的裁决。
138///
139/// 两条通道各有其义,V13 §9.12 #172 之前它们被混用过:
140/// * `Ok(Allow)` / `Ok(Reject { .. })` —— 端口**给出了**裁决;拒绝是正常业务结果,
141///   订单不该出门,但不代表链路坏了。
142/// * `Err(..)` —— 端口给不出裁决(读不到账户状态、上游链路故障等)。
143///
144/// 原形状是 `struct { accepted: bool, reason_code: &'static str }`:两个生产实现
145/// 只在通过时写 `accepted: true`,拒绝改走 `Err`,于是 `accepted: false` 与
146/// `if !decision.accepted { "风控拒绝订单" }` 那条播报只有测试假件能触发,真实
147/// 拒绝被上层报成「RiskPort 执行失败」。改名同时消掉与 `qx_risk::RiskDecision`
148/// 的同名异物(V13 §5 R2-1 预登记的口径)。
149#[derive(Clone, Debug, PartialEq, Eq)]
150pub enum RiskVerdict {
151    Allow,
152    Reject { reason: String },
153}
154
155pub trait RiskPort {
156    fn evaluate_order(&self, order: &Order) -> Result<RiskVerdict, String>;
157}
158
159pub trait VenuePort {
160    fn venue_id(&self) -> &str;
161    fn capabilities(&self) -> qx_zhenlu::venue_capabilities::VenueCapabilities;
162    /// Dynamic connector/reconciliation gate, checked before the gateway registers an order.
163    fn execution_readiness(&self) -> Result<(), String>;
164    fn validate_submit_capabilities(&self, order: &Order) -> Result<(), String> {
165        self.capabilities().validate_submit(order, self.venue_id())
166    }
167    /// Native groups are a separate venue capability; ordinary conditional orders do not imply OCO.
168    fn validate_submit_order_group(
169        &mut self,
170        _group: &qx_core::OrderGroupState,
171    ) -> Result<(), String> {
172        Err("Venue 未声明原生 OCO/Bracket 订单组能力".into())
173    }
174    fn submit_order_group(
175        &mut self,
176        _group: &qx_core::OrderGroupState,
177        _ts: u64,
178    ) -> Result<OrderGroupSubmission, String> {
179        Err("Venue 未实现原生 OCO/Bracket 订单组提交".into())
180    }
181    fn submit_order(&mut self, order: Order, ts: u64) -> Result<Vec<ExecutionEvent>, String>;
182    fn cancel_order(
183        &mut self,
184        client_order_id: u64,
185        ts: u64,
186    ) -> Result<Vec<ExecutionEvent>, String>;
187    fn validate_amend_order(&mut self, current: &Order, amended: &Order) -> Result<(), String> {
188        let _ = (current, amended);
189        Err("Venue 未声明原生改单预检能力".into())
190    }
191    fn amend_order(
192        &mut self,
193        current: &Order,
194        amended: &Order,
195        ts: u64,
196    ) -> Result<Vec<ExecutionEvent>, String> {
197        let _ = (current, amended, ts);
198        Err("Venue 未声明原生改单能力".into())
199    }
200}
201
202/// 多 Venue 路由端口。它刻意只返回标准事实,不承诺跨 Venue 原子性;
203/// 应用层必须在每条腿事实落盘后更新 SpreadOrderGroup,失败进入补偿/对账。
204pub trait VenueRouterPort {
205    fn capabilities_for(
206        &self,
207        venue_id: &str,
208    ) -> Option<qx_zhenlu::venue_capabilities::VenueCapabilities>;
209
210    fn execution_readiness_for(&self, venue_id: &str) -> Result<(), String>;
211
212    fn submit_order(
213        &mut self,
214        venue_id: &str,
215        order: Order,
216        ts: u64,
217    ) -> Result<Vec<ExecutionEvent>, String>;
218
219    fn cancel_order(
220        &mut self,
221        venue_id: &str,
222        client_order_id: u64,
223        ts: u64,
224    ) -> Result<Vec<ExecutionEvent>, String>;
225}
226
227/// 校验 Venue 返回的单腿提交事实。
228///
229/// 该校验位于应用端口层,所有 Paper、CCXT、Binance 以及未来券商适配器
230/// 只要接入 `VenuePort` 就必须遵守同一份契约。异常响应不能直接写入事件
231/// 账本;调用方应将订单置为待对账,避免把错误的成交或其他订单事实归属
232/// 到当前订单。
233pub fn validate_submit_events(order: &Order, events: &[ExecutionEvent]) -> Result<(), String> {
234    if events.is_empty() {
235        return Err("Venue submit 未返回执行事实".into());
236    }
237    let mut quote_spent = order.quote_filled_decimal();
238    for event in events {
239        match event {
240            ExecutionEvent::Accepted {
241                client_order_id,
242                venue_order_id,
243            } => {
244                if *client_order_id != order.client_id {
245                    return Err(format!(
246                        "Accepted client_order_id 不匹配: expected={} actual={}",
247                        order.client_id, client_order_id
248                    ));
249                }
250                if venue_order_id.trim().is_empty() {
251                    return Err("Accepted 缺少 venue_order_id".into());
252                }
253            }
254            ExecutionEvent::Rejected {
255                client_order_id,
256                reason,
257            } => {
258                if *client_order_id != order.client_id {
259                    return Err(format!(
260                        "Rejected client_order_id 不匹配: expected={} actual={}",
261                        order.client_id, client_order_id
262                    ));
263                }
264                if reason.trim().is_empty() {
265                    return Err("Rejected 缺少拒单原因".into());
266                }
267            }
268            ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. } => {
269                validate_fill_for_order(order, fill)?;
270                if let Some(budget) = order.quote_budget_decimal() {
271                    let cost = fill
272                        .exact_amounts
273                        .and_then(|amounts| amounts.quote_cost)
274                        .ok_or_else(|| "计价币预算订单成交缺少精确花费".to_string())?;
275                    quote_spent = quote_spent
276                        .checked_add(cost)
277                        .ok_or_else(|| "提交返回成交的计价币花费累计溢出".to_string())?;
278                    if quote_spent
279                        .checked_cmp(budget)
280                        .is_none_or(|ordering| ordering.is_gt())
281                    {
282                        return Err("提交返回的成交总花费超过计价币预算".into());
283                    }
284                }
285            }
286            ExecutionEvent::FeeAdjustment { .. } => {
287                return Err("订单提交接口不能返回独立手续费调整事实".into());
288            }
289            ExecutionEvent::Cancelled { client_order_id }
290            | ExecutionEvent::ReconcileRequired { client_order_id } => {
291                if *client_order_id != order.client_id {
292                    return Err(format!(
293                        "执行事实 client_order_id 不匹配: expected={} actual={}",
294                        order.client_id, client_order_id
295                    ));
296                }
297            }
298            ExecutionEvent::CancelPending { .. } => {
299                return Err("订单提交接口不能返回本地撤单发起事实".into());
300            }
301            ExecutionEvent::OrderAmendmentPending { .. } | ExecutionEvent::OrderAmended { .. } => {
302                return Err("订单提交接口不能返回改单事实".into());
303            }
304            ExecutionEvent::MarketQuote { instrument, .. } => {
305                return Err(format!("提交接口返回了行情事实: instrument={instrument}"));
306            }
307        }
308    }
309    Ok(())
310}
311
312/// 校验 Venue 返回的撤单事实。撤单竞态中,成交事实必须排在 Cancelled 前面;
313/// 撤单接口不能把其他订单的成交、接收或撤单事实写入当前订单。
314pub fn validate_cancel_events(
315    client_order_id: u64,
316    events: &[ExecutionEvent],
317) -> Result<(), String> {
318    if events.is_empty() {
319        return Err("Venue cancel 未返回执行事实".into());
320    }
321    let mut cancellation_seen = false;
322    for event in events {
323        match event {
324            ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. }
325                if fill.order_id == client_order_id && !cancellation_seen => {}
326            ExecutionEvent::FeeAdjustment { order_id, .. } if *order_id == client_order_id => {}
327            ExecutionEvent::Cancelled {
328                client_order_id: actual,
329            } if *actual == client_order_id => cancellation_seen = true,
330            ExecutionEvent::Rejected { .. } => {
331                return Err("撤单接口不能返回订单拒绝事实".into());
332            }
333            ExecutionEvent::ReconcileRequired {
334                client_order_id: actual,
335            } if *actual == client_order_id => {}
336            ExecutionEvent::Cancelled {
337                client_order_id: actual,
338            } => {
339                return Err(format!(
340                    "撤单事实 client_order_id 不匹配: expected={} actual={}",
341                    client_order_id, actual
342                ));
343            }
344            ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. } => {
345                return Err(format!(
346                    "撤单竞态成交顺序或 order_id 不匹配: expected={} actual={}",
347                    client_order_id, fill.order_id
348                ));
349            }
350            ExecutionEvent::FeeAdjustment { order_id, .. } => {
351                return Err(format!(
352                    "撤单费用 order_id 不匹配: expected={} actual={}",
353                    client_order_id, order_id
354                ));
355            }
356            ExecutionEvent::OrderAmendmentPending { .. } | ExecutionEvent::OrderAmended { .. } => {
357                return Err("撤单接口返回了改单事实".into());
358            }
359            _ => return Err("撤单接口返回了非撤单事实".into()),
360        }
361    }
362    Ok(())
363}
364
365fn validate_fill_for_order(order: &Order, fill: &Fill) -> Result<(), String> {
366    if fill.order_id != order.client_id {
367        return Err(format!(
368            "Fill order_id 不匹配: expected={} actual={}",
369            order.client_id, fill.order_id
370        ));
371    }
372    fill.validate_exact_amounts()?;
373    if order.exact_amounts.is_some() != fill.exact_amounts.is_some() {
374        return Err(if order.exact_amounts.is_some() {
375            "精确订单收到缺少精确值的成交".into()
376        } else {
377            "精确成交不能应用到旧精度订单".into()
378        });
379    }
380    let fill_quantity = fill.quantity_decimal();
381    if !fill_quantity.is_positive() {
382        return Err("Fill 数量必须为正".into());
383    }
384    let fill_price = fill.price_decimal();
385    if !fill_price.is_positive() {
386        return Err("Fill 价格必须为正".into());
387    }
388    if let Some(budget) = order.quote_budget_decimal() {
389        let cost = fill
390            .exact_amounts
391            .and_then(|amounts| amounts.quote_cost)
392            .ok_or_else(|| "计价币预算订单成交缺少精确花费".to_string())?;
393        let remaining_budget = budget
394            .checked_sub(order.quote_filled_decimal())
395            .ok_or_else(|| "计价币预算剩余量计算溢出".to_string())?;
396        if cost
397            .checked_cmp(remaining_budget)
398            .is_none_or(|ordering| ordering.is_gt())
399        {
400            return Err("Fill 花费超过订单剩余计价币预算".into());
401        }
402    } else {
403        let remaining = order
404            .remaining_decimal()
405            .ok_or_else(|| "订单剩余数量计算溢出".to_string())?;
406        if fill_quantity
407            .checked_cmp(remaining)
408            .is_none_or(|ordering| ordering.is_gt())
409        {
410            return Err("Fill 数量超过订单剩余数量".into());
411        }
412    }
413    if let Some(limit_price) = order.limit_price_decimal() {
414        let outside_limit = match order.side {
415            qx_core::Side::Buy => fill_price
416                .checked_cmp(limit_price)
417                .is_none_or(|ordering| ordering.is_gt()),
418            qx_core::Side::Sell => fill_price
419                .checked_cmp(limit_price)
420                .is_none_or(|ordering| ordering.is_lt()),
421        };
422        if outside_limit {
423            return Err("Fill 成交价格违反订单限价".into());
424        }
425    }
426    Ok(())
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432    use qx_core::{Price, Quantity};
433
434    fn test_order() -> Order {
435        Order {
436            client_id: 7,
437            instrument: InstrumentId::parse("BTCUSDT.BINANCE").unwrap(),
438            side: qx_core::Side::Buy,
439            qty: Quantity::from_i64(2),
440            limit: Some(Price::from_i64(100)),
441            status: qx_core::OrderStatus::PendingSubmit,
442            filled: Quantity::ZERO,
443            account_id: "test-account".into(),
444            trace: None,
445            policy: None,
446            exact_amounts: None,
447        }
448    }
449
450    #[test]
451    fn fill_validation_preserves_exact_precision_and_enforces_limit_side() {
452        use qx_core::{ExactDecimal, ExactFillAmounts, ExactOrderAmounts};
453
454        let mut order = test_order();
455        order.qty = Quantity::ZERO;
456        order.limit = None;
457        order.exact_amounts = Some(ExactOrderAmounts {
458            quantity: ExactDecimal::parse("0.0000000002").unwrap(),
459            limit_price: Some(ExactDecimal::parse("0.0000000100000001").unwrap()),
460            filled: ExactDecimal::ZERO,
461            market_reference_price: None,
462            quote_budget: None,
463            quote_filled: Default::default(),
464            conditional: None,
465        });
466        let fill = Fill {
467            order_id: order.client_id,
468            exact_amounts: Some(ExactFillAmounts {
469                quantity: ExactDecimal::parse("0.0000000001").unwrap(),
470                price: ExactDecimal::parse("0.0000000100000002").unwrap(),
471                quote_cost: None,
472                quote_budget_complete: false,
473            }),
474            ..Fill::default()
475        };
476        assert_eq!(
477            validate_fill_for_order(&order, &fill).unwrap_err(),
478            "Fill 成交价格违反订单限价"
479        );
480
481        let mut within_limit = fill;
482        within_limit.exact_amounts.as_mut().unwrap().price =
483            ExactDecimal::parse("0.0000000100000000").unwrap();
484        assert!(validate_fill_for_order(&order, &within_limit).is_ok());
485    }
486
487    #[test]
488    fn execution_contract_rejects_cross_order_or_invalid_fill() {
489        let order = test_order();
490        let wrong_order = ExecutionEvent::Accepted {
491            client_order_id: 8,
492            venue_order_id: "remote-8".into(),
493        };
494        assert!(validate_submit_events(&order, &[wrong_order]).is_err());
495
496        let invalid_fill = ExecutionEvent::Fill(Box::new(Fill {
497            order_id: order.client_id,
498            qty: Quantity::from_i64(3),
499            price: Price::from_i64(100),
500            ..Fill::default()
501        }));
502        assert!(validate_submit_events(&order, &[invalid_fill]).is_err());
503    }
504
505    #[test]
506    fn execution_contract_accepts_immediate_fill_and_valid_cancel() {
507        let order = test_order();
508        let fill = ExecutionEvent::Fill(Box::new(Fill {
509            order_id: order.client_id,
510            qty: Quantity::from_i64(2),
511            price: Price::from_i64(100),
512            ..Fill::default()
513        }));
514        assert!(validate_submit_events(&order, &[fill]).is_ok());
515        assert!(validate_cancel_events(
516            order.client_id,
517            &[ExecutionEvent::Cancelled {
518                client_order_id: order.client_id,
519            }]
520        )
521        .is_ok());
522        assert!(validate_cancel_events(
523            order.client_id,
524            &[
525                ExecutionEvent::Fill(Box::new(Fill {
526                    order_id: order.client_id,
527                    qty: Quantity::from_i64(1),
528                    price: Price::from_i64(100),
529                    ..Fill::default()
530                })),
531                ExecutionEvent::Cancelled {
532                    client_order_id: order.client_id,
533                },
534            ]
535        )
536        .is_ok());
537        assert!(validate_cancel_events(
538            order.client_id,
539            &[
540                ExecutionEvent::Cancelled {
541                    client_order_id: order.client_id,
542                },
543                ExecutionEvent::Fill(Box::new(Fill {
544                    order_id: order.client_id,
545                    qty: Quantity::from_i64(1),
546                    price: Price::from_i64(100),
547                    ..Fill::default()
548                })),
549            ]
550        )
551        .is_err());
552        assert!(validate_cancel_events(
553            order.client_id,
554            &[ExecutionEvent::Fill(Box::new(Fill {
555                order_id: order.client_id + 1,
556                qty: Quantity::from_i64(1),
557                price: Price::from_i64(100),
558                ..Fill::default()
559            }))]
560        )
561        .is_err());
562        assert!(validate_cancel_events(
563            order.client_id,
564            &[ExecutionEvent::Accepted {
565                client_order_id: order.client_id,
566                venue_order_id: "remote-7".into(),
567            }]
568        )
569        .is_err());
570    }
571}