qx-execution 0.4.2

牵星统一执行事实归约边界
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! 应用层端口。
//!
//! 原 `qx-application` crate,V10 P2a 按"端口即执行事实契约,归执行网关"并入本 crate。
//! 这里不拥有 EventLog、数据库或具体 Venue;只定义执行编排需要的稳定事实和
//! 端口。Runtime、Storage、Paper、CCXT 和 Binance 通过 adapter 实现这些端口,
//! 避免应用服务反向依赖某个运行时具体类型。

pub use qx_core::{
    Fill, InstrumentId, Order, OrderPolicy, OrderStatus, OrderTrace, Price, Quantity, Side,
    TradingInstrumentSpec, TradingProduct,
};
use qx_guanxing::QuoteTick;
pub use qx_zhenlu::venue_capabilities::{
    VenueCapabilities, VenueMarketScope, VenueOrderType, PAPER_VENUE_CAPABILITIES,
};

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ExecutionEvent {
    Accepted {
        client_order_id: u64,
        venue_order_id: String,
    },
    Rejected {
        client_order_id: u64,
        reason: String,
    },
    Fill(Box<Fill>),
    FeeAdjustment {
        account_id: String,
        venue_id: String,
        order_id: u64,
        instrument: InstrumentId,
        fees: Vec<qx_core::FillFee>,
    },
    FillWithSpec {
        fill: Box<Fill>,
        spec: Box<TradingInstrumentSpec>,
    },
    /// Persisted before the cancel side effect; a restart must reconcile this operation.
    CancelPending {
        client_order_id: u64,
    },
    /// Persisted before a venue amend side effect; retries after an unknown result are forbidden.
    OrderAmendmentPending {
        operation_id: String,
        order: Box<Order>,
    },
    OrderAmended {
        operation_id: String,
        order: Box<Order>,
    },
    Cancelled {
        client_order_id: u64,
    },
    ReconcileRequired {
        client_order_id: u64,
    },
    /// 行情事实。撮合前必须先落行情事件,使 Paper 与 Live 共享同一道行情门禁。
    MarketQuote {
        instrument: InstrumentId,
        quote: QuoteTick,
    },
}

/// A venue's response to one atomic group submission. `venue_group_id` identifies
/// the exchange-side order-list/resource (for example an OCO list), while each
/// child event retains its own exchange order ID and fills.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct OrderGroupSubmission {
    pub venue_group_id: Option<String>,
    pub group_status: Option<qx_core::OrderGroupStatus>,
    pub events: Vec<ExecutionEvent>,
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ExecutionEventEnvelope {
    pub event: ExecutionEvent,
    pub event_ts: u64,
    pub receive_ts: u64,
    pub source_seq: u64,
    pub correlation_id: String,
}

/// Result of appending an execution fact to a store with durable deduplication.
/// `Duplicate` means the same correlation was already committed and the caller
/// must not repeat the external side effect associated with that fact.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum EventAppendOutcome {
    Appended,
    Duplicate,
}

pub trait EventAppender {
    fn append_execution_event(&mut self, envelope: ExecutionEventEnvelope) -> Result<(), String>;

    /// Append a fact and report whether this call committed it. Persistent
    /// implementations that support idempotency should override this method.
    /// The default preserves compatibility for append-only adapters without a
    /// duplicate receipt; production cancel paths use the Runtime override.
    fn append_execution_event_with_outcome(
        &mut self,
        envelope: ExecutionEventEnvelope,
    ) -> Result<EventAppendOutcome, String> {
        self.append_execution_event(envelope)?;
        Ok(EventAppendOutcome::Appended)
    }
}

pub trait OrderStore {
    fn orders(&self) -> Vec<Order>;

    fn refresh_order_state(&mut self) -> Result<(), String> {
        Ok(())
    }

    fn has_pending_amendment(&self, _client_order_id: u64) -> bool {
        false
    }

    fn register_order(
        &mut self,
        order: Order,
        ts: u64,
        correlation_id: Option<String>,
    ) -> Result<(), String>;
}

pub trait ExecutionEventPort: EventAppender + OrderStore {}

impl<T: EventAppender + OrderStore> ExecutionEventPort for T {}

/// 只读的账本条目计数,用于执行结果摘要;实现者不必暴露 Ledger 结构。
pub trait LedgerProbe {
    fn ledger_entry_count(&self) -> usize;
}

/// 风控端口对单笔订单的裁决。
///
/// 两条通道各有其义,V13 §9.12 #172 之前它们被混用过:
/// * `Ok(Allow)` / `Ok(Reject { .. })` —— 端口**给出了**裁决;拒绝是正常业务结果,
///   订单不该出门,但不代表链路坏了。
/// * `Err(..)` —— 端口给不出裁决(读不到账户状态、上游链路故障等)。
///
/// 原形状是 `struct { accepted: bool, reason_code: &'static str }`:两个生产实现
/// 只在通过时写 `accepted: true`,拒绝改走 `Err`,于是 `accepted: false` 与
/// `if !decision.accepted { "风控拒绝订单" }` 那条播报只有测试假件能触发,真实
/// 拒绝被上层报成「RiskPort 执行失败」。改名同时消掉与 `qx_risk::RiskDecision`
/// 的同名异物(V13 §5 R2-1 预登记的口径)。
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RiskVerdict {
    Allow,
    Reject { reason: String },
}

pub trait RiskPort {
    fn evaluate_order(&self, order: &Order) -> Result<RiskVerdict, String>;
}

pub trait VenuePort {
    fn venue_id(&self) -> &str;
    fn capabilities(&self) -> qx_zhenlu::venue_capabilities::VenueCapabilities;
    /// Dynamic connector/reconciliation gate, checked before the gateway registers an order.
    fn execution_readiness(&self) -> Result<(), String>;
    fn validate_submit_capabilities(&self, order: &Order) -> Result<(), String> {
        self.capabilities().validate_submit(order, self.venue_id())
    }
    /// Native groups are a separate venue capability; ordinary conditional orders do not imply OCO.
    fn validate_submit_order_group(
        &mut self,
        _group: &qx_core::OrderGroupState,
    ) -> Result<(), String> {
        Err("Venue 未声明原生 OCO/Bracket 订单组能力".into())
    }
    fn submit_order_group(
        &mut self,
        _group: &qx_core::OrderGroupState,
        _ts: u64,
    ) -> Result<OrderGroupSubmission, String> {
        Err("Venue 未实现原生 OCO/Bracket 订单组提交".into())
    }
    fn submit_order(&mut self, order: Order, ts: u64) -> Result<Vec<ExecutionEvent>, String>;
    fn cancel_order(
        &mut self,
        client_order_id: u64,
        ts: u64,
    ) -> Result<Vec<ExecutionEvent>, String>;
    fn validate_amend_order(&mut self, current: &Order, amended: &Order) -> Result<(), String> {
        let _ = (current, amended);
        Err("Venue 未声明原生改单预检能力".into())
    }
    fn amend_order(
        &mut self,
        current: &Order,
        amended: &Order,
        ts: u64,
    ) -> Result<Vec<ExecutionEvent>, String> {
        let _ = (current, amended, ts);
        Err("Venue 未声明原生改单能力".into())
    }
}

/// 多 Venue 路由端口。它刻意只返回标准事实,不承诺跨 Venue 原子性;
/// 应用层必须在每条腿事实落盘后更新 SpreadOrderGroup,失败进入补偿/对账。
pub trait VenueRouterPort {
    fn capabilities_for(
        &self,
        venue_id: &str,
    ) -> Option<qx_zhenlu::venue_capabilities::VenueCapabilities>;

    fn execution_readiness_for(&self, venue_id: &str) -> Result<(), String>;

    fn submit_order(
        &mut self,
        venue_id: &str,
        order: Order,
        ts: u64,
    ) -> Result<Vec<ExecutionEvent>, String>;

    fn cancel_order(
        &mut self,
        venue_id: &str,
        client_order_id: u64,
        ts: u64,
    ) -> Result<Vec<ExecutionEvent>, String>;
}

/// 校验 Venue 返回的单腿提交事实。
///
/// 该校验位于应用端口层,所有 Paper、CCXT、Binance 以及未来券商适配器
/// 只要接入 `VenuePort` 就必须遵守同一份契约。异常响应不能直接写入事件
/// 账本;调用方应将订单置为待对账,避免把错误的成交或其他订单事实归属
/// 到当前订单。
pub fn validate_submit_events(order: &Order, events: &[ExecutionEvent]) -> Result<(), String> {
    if events.is_empty() {
        return Err("Venue submit 未返回执行事实".into());
    }
    let mut quote_spent = order.quote_filled_decimal();
    for event in events {
        match event {
            ExecutionEvent::Accepted {
                client_order_id,
                venue_order_id,
            } => {
                if *client_order_id != order.client_id {
                    return Err(format!(
                        "Accepted client_order_id 不匹配: expected={} actual={}",
                        order.client_id, client_order_id
                    ));
                }
                if venue_order_id.trim().is_empty() {
                    return Err("Accepted 缺少 venue_order_id".into());
                }
            }
            ExecutionEvent::Rejected {
                client_order_id,
                reason,
            } => {
                if *client_order_id != order.client_id {
                    return Err(format!(
                        "Rejected client_order_id 不匹配: expected={} actual={}",
                        order.client_id, client_order_id
                    ));
                }
                if reason.trim().is_empty() {
                    return Err("Rejected 缺少拒单原因".into());
                }
            }
            ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. } => {
                validate_fill_for_order(order, fill)?;
                if let Some(budget) = order.quote_budget_decimal() {
                    let cost = fill
                        .exact_amounts
                        .and_then(|amounts| amounts.quote_cost)
                        .ok_or_else(|| "计价币预算订单成交缺少精确花费".to_string())?;
                    quote_spent = quote_spent
                        .checked_add(cost)
                        .ok_or_else(|| "提交返回成交的计价币花费累计溢出".to_string())?;
                    if quote_spent
                        .checked_cmp(budget)
                        .is_none_or(|ordering| ordering.is_gt())
                    {
                        return Err("提交返回的成交总花费超过计价币预算".into());
                    }
                }
            }
            ExecutionEvent::FeeAdjustment { .. } => {
                return Err("订单提交接口不能返回独立手续费调整事实".into());
            }
            ExecutionEvent::Cancelled { client_order_id }
            | ExecutionEvent::ReconcileRequired { client_order_id } => {
                if *client_order_id != order.client_id {
                    return Err(format!(
                        "执行事实 client_order_id 不匹配: expected={} actual={}",
                        order.client_id, client_order_id
                    ));
                }
            }
            ExecutionEvent::CancelPending { .. } => {
                return Err("订单提交接口不能返回本地撤单发起事实".into());
            }
            ExecutionEvent::OrderAmendmentPending { .. } | ExecutionEvent::OrderAmended { .. } => {
                return Err("订单提交接口不能返回改单事实".into());
            }
            ExecutionEvent::MarketQuote { instrument, .. } => {
                return Err(format!("提交接口返回了行情事实: instrument={instrument}"));
            }
        }
    }
    Ok(())
}

/// 校验 Venue 返回的撤单事实。撤单竞态中,成交事实必须排在 Cancelled 前面;
/// 撤单接口不能把其他订单的成交、接收或撤单事实写入当前订单。
pub fn validate_cancel_events(
    client_order_id: u64,
    events: &[ExecutionEvent],
) -> Result<(), String> {
    if events.is_empty() {
        return Err("Venue cancel 未返回执行事实".into());
    }
    let mut cancellation_seen = false;
    for event in events {
        match event {
            ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. }
                if fill.order_id == client_order_id && !cancellation_seen => {}
            ExecutionEvent::FeeAdjustment { order_id, .. } if *order_id == client_order_id => {}
            ExecutionEvent::Cancelled {
                client_order_id: actual,
            } if *actual == client_order_id => cancellation_seen = true,
            ExecutionEvent::Rejected { .. } => {
                return Err("撤单接口不能返回订单拒绝事实".into());
            }
            ExecutionEvent::ReconcileRequired {
                client_order_id: actual,
            } if *actual == client_order_id => {}
            ExecutionEvent::Cancelled {
                client_order_id: actual,
            } => {
                return Err(format!(
                    "撤单事实 client_order_id 不匹配: expected={} actual={}",
                    client_order_id, actual
                ));
            }
            ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. } => {
                return Err(format!(
                    "撤单竞态成交顺序或 order_id 不匹配: expected={} actual={}",
                    client_order_id, fill.order_id
                ));
            }
            ExecutionEvent::FeeAdjustment { order_id, .. } => {
                return Err(format!(
                    "撤单费用 order_id 不匹配: expected={} actual={}",
                    client_order_id, order_id
                ));
            }
            ExecutionEvent::OrderAmendmentPending { .. } | ExecutionEvent::OrderAmended { .. } => {
                return Err("撤单接口返回了改单事实".into());
            }
            _ => return Err("撤单接口返回了非撤单事实".into()),
        }
    }
    Ok(())
}

fn validate_fill_for_order(order: &Order, fill: &Fill) -> Result<(), String> {
    if fill.order_id != order.client_id {
        return Err(format!(
            "Fill order_id 不匹配: expected={} actual={}",
            order.client_id, fill.order_id
        ));
    }
    fill.validate_exact_amounts()?;
    if order.exact_amounts.is_some() != fill.exact_amounts.is_some() {
        return Err(if order.exact_amounts.is_some() {
            "精确订单收到缺少精确值的成交".into()
        } else {
            "精确成交不能应用到旧精度订单".into()
        });
    }
    let fill_quantity = fill.quantity_decimal();
    if !fill_quantity.is_positive() {
        return Err("Fill 数量必须为正".into());
    }
    let fill_price = fill.price_decimal();
    if !fill_price.is_positive() {
        return Err("Fill 价格必须为正".into());
    }
    if let Some(budget) = order.quote_budget_decimal() {
        let cost = fill
            .exact_amounts
            .and_then(|amounts| amounts.quote_cost)
            .ok_or_else(|| "计价币预算订单成交缺少精确花费".to_string())?;
        let remaining_budget = budget
            .checked_sub(order.quote_filled_decimal())
            .ok_or_else(|| "计价币预算剩余量计算溢出".to_string())?;
        if cost
            .checked_cmp(remaining_budget)
            .is_none_or(|ordering| ordering.is_gt())
        {
            return Err("Fill 花费超过订单剩余计价币预算".into());
        }
    } else {
        let remaining = order
            .remaining_decimal()
            .ok_or_else(|| "订单剩余数量计算溢出".to_string())?;
        if fill_quantity
            .checked_cmp(remaining)
            .is_none_or(|ordering| ordering.is_gt())
        {
            return Err("Fill 数量超过订单剩余数量".into());
        }
    }
    if let Some(limit_price) = order.limit_price_decimal() {
        let outside_limit = match order.side {
            qx_core::Side::Buy => fill_price
                .checked_cmp(limit_price)
                .is_none_or(|ordering| ordering.is_gt()),
            qx_core::Side::Sell => fill_price
                .checked_cmp(limit_price)
                .is_none_or(|ordering| ordering.is_lt()),
        };
        if outside_limit {
            return Err("Fill 成交价格违反订单限价".into());
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use qx_core::{Price, Quantity};

    fn test_order() -> Order {
        Order {
            client_id: 7,
            instrument: InstrumentId::parse("BTCUSDT.BINANCE").unwrap(),
            side: qx_core::Side::Buy,
            qty: Quantity::from_i64(2),
            limit: Some(Price::from_i64(100)),
            status: qx_core::OrderStatus::PendingSubmit,
            filled: Quantity::ZERO,
            account_id: "test-account".into(),
            trace: None,
            policy: None,
            exact_amounts: None,
        }
    }

    #[test]
    fn fill_validation_preserves_exact_precision_and_enforces_limit_side() {
        use qx_core::{ExactDecimal, ExactFillAmounts, ExactOrderAmounts};

        let mut order = test_order();
        order.qty = Quantity::ZERO;
        order.limit = None;
        order.exact_amounts = Some(ExactOrderAmounts {
            quantity: ExactDecimal::parse("0.0000000002").unwrap(),
            limit_price: Some(ExactDecimal::parse("0.0000000100000001").unwrap()),
            filled: ExactDecimal::ZERO,
            market_reference_price: None,
            quote_budget: None,
            quote_filled: Default::default(),
            conditional: None,
        });
        let fill = Fill {
            order_id: order.client_id,
            exact_amounts: Some(ExactFillAmounts {
                quantity: ExactDecimal::parse("0.0000000001").unwrap(),
                price: ExactDecimal::parse("0.0000000100000002").unwrap(),
                quote_cost: None,
                quote_budget_complete: false,
            }),
            ..Fill::default()
        };
        assert_eq!(
            validate_fill_for_order(&order, &fill).unwrap_err(),
            "Fill 成交价格违反订单限价"
        );

        let mut within_limit = fill;
        within_limit.exact_amounts.as_mut().unwrap().price =
            ExactDecimal::parse("0.0000000100000000").unwrap();
        assert!(validate_fill_for_order(&order, &within_limit).is_ok());
    }

    #[test]
    fn execution_contract_rejects_cross_order_or_invalid_fill() {
        let order = test_order();
        let wrong_order = ExecutionEvent::Accepted {
            client_order_id: 8,
            venue_order_id: "remote-8".into(),
        };
        assert!(validate_submit_events(&order, &[wrong_order]).is_err());

        let invalid_fill = ExecutionEvent::Fill(Box::new(Fill {
            order_id: order.client_id,
            qty: Quantity::from_i64(3),
            price: Price::from_i64(100),
            ..Fill::default()
        }));
        assert!(validate_submit_events(&order, &[invalid_fill]).is_err());
    }

    #[test]
    fn execution_contract_accepts_immediate_fill_and_valid_cancel() {
        let order = test_order();
        let fill = ExecutionEvent::Fill(Box::new(Fill {
            order_id: order.client_id,
            qty: Quantity::from_i64(2),
            price: Price::from_i64(100),
            ..Fill::default()
        }));
        assert!(validate_submit_events(&order, &[fill]).is_ok());
        assert!(validate_cancel_events(
            order.client_id,
            &[ExecutionEvent::Cancelled {
                client_order_id: order.client_id,
            }]
        )
        .is_ok());
        assert!(validate_cancel_events(
            order.client_id,
            &[
                ExecutionEvent::Fill(Box::new(Fill {
                    order_id: order.client_id,
                    qty: Quantity::from_i64(1),
                    price: Price::from_i64(100),
                    ..Fill::default()
                })),
                ExecutionEvent::Cancelled {
                    client_order_id: order.client_id,
                },
            ]
        )
        .is_ok());
        assert!(validate_cancel_events(
            order.client_id,
            &[
                ExecutionEvent::Cancelled {
                    client_order_id: order.client_id,
                },
                ExecutionEvent::Fill(Box::new(Fill {
                    order_id: order.client_id,
                    qty: Quantity::from_i64(1),
                    price: Price::from_i64(100),
                    ..Fill::default()
                })),
            ]
        )
        .is_err());
        assert!(validate_cancel_events(
            order.client_id,
            &[ExecutionEvent::Fill(Box::new(Fill {
                order_id: order.client_id + 1,
                qty: Quantity::from_i64(1),
                price: Price::from_i64(100),
                ..Fill::default()
            }))]
        )
        .is_err());
        assert!(validate_cancel_events(
            order.client_id,
            &[ExecutionEvent::Accepted {
                client_order_id: order.client_id,
                venue_order_id: "remote-7".into(),
            }]
        )
        .is_err());
    }
}