Skip to main content

qx_core/
order.rs

1//! 订单与成交。
2//!
3//! 状态机区分"提交意图"与"venue 事实":
4//! `Submitted` 只是离开本地的意图,`Accepted` 才代表获得 venue 确认。
5
6use crate::clock::Ts;
7use crate::identity::InstrumentId;
8use crate::numeric::{ExactDecimal, Money, Price, Quantity};
9use crate::trading::OrderPolicy;
10use serde::{Deserialize, Serialize};
11use std::collections::VecDeque;
12
13#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
14pub enum Side {
15    Buy,
16    Sell,
17}
18
19#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
20pub enum OrderStatus {
21    PendingSubmit,
22    Submitted,
23    Accepted,
24    Working,
25    PartiallyFilled,
26    Filled,
27    CancelPending,
28    Cancelled,
29    Rejected,
30    Expired,
31    /// 连接中断或超时后的未知状态,必须进入对账,不能自动补单。
32    Unknown,
33}
34
35impl OrderStatus {
36    /// 是否为终态(不可再迁移)。
37    pub fn is_terminal(self) -> bool {
38        matches!(
39            self,
40            OrderStatus::Filled
41                | OrderStatus::Cancelled
42                | OrderStatus::Rejected
43                | OrderStatus::Expired
44        )
45    }
46
47    pub fn can_transition_to(self, next: Self) -> bool {
48        use OrderStatus::*;
49        if self == next {
50            return !self.is_terminal();
51        }
52        matches!(
53            (self, next),
54            (PendingSubmit, Submitted | Rejected | Unknown)
55                | (Submitted, Accepted | CancelPending | Rejected | Unknown)
56                | (Accepted, Working | CancelPending | Rejected | Unknown)
57                | (
58                    Working,
59                    PartiallyFilled | Filled | CancelPending | Rejected | Expired | Unknown
60                )
61                | (
62                    PartiallyFilled,
63                    PartiallyFilled | Filled | CancelPending | Expired | Unknown
64                )
65                | (CancelPending, Cancelled | Filled | Unknown)
66                | (
67                    Unknown,
68                    Accepted | Working | PartiallyFilled | Filled | Cancelled | Rejected | Expired
69                )
70        )
71    }
72
73    /// Return the shortest legal lifecycle path to an authoritative reconciliation snapshot.
74    /// Intermediate states are replayed from the snapshot fact; no venue side effect is implied.
75    pub fn reconciliation_path(self, target: Self) -> Option<Vec<Self>> {
76        const STATUSES: [OrderStatus; 11] = [
77            OrderStatus::PendingSubmit,
78            OrderStatus::Submitted,
79            OrderStatus::Accepted,
80            OrderStatus::Working,
81            OrderStatus::PartiallyFilled,
82            OrderStatus::Filled,
83            OrderStatus::CancelPending,
84            OrderStatus::Cancelled,
85            OrderStatus::Rejected,
86            OrderStatus::Expired,
87            OrderStatus::Unknown,
88        ];
89        if self == target {
90            return Some(Vec::new());
91        }
92        let mut queue = VecDeque::from([(self, Vec::new())]);
93        let mut visited = vec![self];
94        while let Some((status, path)) = queue.pop_front() {
95            for next in STATUSES {
96                if !status.can_transition_to(next)
97                    || (next == OrderStatus::Unknown && self != OrderStatus::Unknown)
98                    || visited.contains(&next)
99                {
100                    continue;
101                }
102                let mut next_path = path.clone();
103                next_path.push(next);
104                if next == target {
105                    return Some(next_path);
106                }
107                visited.push(next);
108                queue.push_back((next, next_path));
109            }
110        }
111        None
112    }
113
114    pub fn transition(&mut self, next: Self) -> Result<(), String> {
115        if self.can_transition_to(next) {
116            *self = next;
117            Ok(())
118        } else {
119            Err(format!("非法订单状态迁移: {:?} -> {:?}", self, next))
120        }
121    }
122}
123
124#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
125#[serde(deny_unknown_fields)]
126pub struct OrderTrace {
127    /// Stable run identity that created the order. Older orders omit it; readers must not infer it.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub run_id: Option<String>,
130    pub strategy_id: Option<String>,
131    pub signal_id: Option<u64>,
132    pub intent_id: Option<u64>,
133    pub rule_version: Option<String>,
134}
135
136/// Precise order amounts for versioned live/crypto paths.
137///
138/// Legacy `qty`/`limit`/`filled` stay at scale 1e9. When this payload is present those
139/// legacy amount fields must be zero/None; consumers must use this scale-bearing payload.
140#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct ExactOrderAmounts {
143    /// Base amount for ordinary orders. A quote-budget market buy uses zero here and
144    /// carries `quote_budget` instead; fills remain base quantities in `filled`.
145    pub quantity: ExactDecimal,
146    pub limit_price: Option<ExactDecimal>,
147    pub filled: ExactDecimal,
148    /// Maximum quote-currency spend for a market buy. The order's quote currency is taken
149    /// from its frozen TradingInstrumentSpec. This is a distinct sizing unit, never a
150    /// price-derived estimate of base quantity.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub quote_budget: Option<ExactDecimal>,
153    /// Cumulative quote-currency amount consumed by fills for a quote-budget order.
154    #[serde(default)]
155    pub quote_filled: ExactDecimal,
156    /// Fresh exact ticker price used only for risk/reservation on market orders.
157    /// It is never forwarded as the venue order price.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub market_reference_price: Option<ExactDecimal>,
160    /// Exchange-side conditional execution intent. Legacy orders omit this field.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub conditional: Option<ConditionalOrderIntent>,
163}
164
165#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
166#[serde(rename_all = "snake_case")]
167pub enum ConditionalOrderKind {
168    Trigger,
169    StopLoss,
170    TakeProfit,
171    Trailing,
172}
173
174#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
175#[serde(rename_all = "snake_case")]
176pub enum TriggerPriceType {
177    Last,
178    Mark,
179    Index,
180}
181
182/// Conditional terms are part of the immutable exact order request. For a trigger order,
183/// `limit_price` selects trigger-limit; omission selects trigger-market.
184#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
185#[serde(deny_unknown_fields)]
186pub struct ConditionalOrderIntent {
187    pub kind: ConditionalOrderKind,
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub trigger_price: Option<ExactDecimal>,
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub trigger_price_type: Option<TriggerPriceType>,
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub trailing_percent: Option<ExactDecimal>,
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub trailing_amount: Option<ExactDecimal>,
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub trailing_trigger_price: Option<ExactDecimal>,
198}
199
200/// Precise exchange fill values, kept separate from the legacy 1e9 amount fields.
201#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
202pub struct ExactFillAmounts {
203    pub quantity: ExactDecimal,
204    pub price: ExactDecimal,
205    /// Actual quote-currency cost reported by the venue when available. Used by quote-budget
206    /// market buys and to book exact spot cash without recomputing rounded products.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub quote_cost: Option<ExactDecimal>,
209    /// The venue/simulator has completed this quote-budget order, even when lot-step rounding
210    /// leaves a small unspent quote balance. This is an order lifecycle fact, not extra spend.
211    #[serde(default, skip_serializing_if = "is_false")]
212    pub quote_budget_complete: bool,
213}
214
215fn is_false(value: &bool) -> bool {
216    !*value
217}
218
219#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
220#[serde(deny_unknown_fields)]
221pub struct Order {
222    pub client_id: u64,
223    pub instrument: InstrumentId,
224    pub side: Side,
225    pub qty: Quantity,
226    /// None 表示市价单。
227    pub limit: Option<Price>,
228    pub status: OrderStatus,
229    pub filled: Quantity,
230    pub account_id: String,
231    pub trace: Option<OrderTrace>,
232    /// 现货/保证金/永续/期货的执行策略;None 保持现货 Cash/1x 兼容语义。
233    #[serde(default)]
234    pub policy: Option<OrderPolicy>,
235    /// Versioned high-precision amount payload. Omitted on all legacy 1e9 orders.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub exact_amounts: Option<ExactOrderAmounts>,
238}
239
240impl Order {
241    /// Compare immutable submission facts while ignoring the lifecycle state and cumulative
242    /// fills, which may have advanced since the original submission was persisted.
243    /// A reused client order ID is idempotent only when every economic and routing input
244    /// matches the original request.
245    pub fn same_submission_identity(&self, other: &Self) -> bool {
246        let same_exact_request = match (self.exact_amounts, other.exact_amounts) {
247            (Some(left), Some(right)) => {
248                left.quantity == right.quantity
249                    && left.limit_price == right.limit_price
250                    && left.quote_budget == right.quote_budget
251                    && left.market_reference_price == right.market_reference_price
252                    && left.conditional == right.conditional
253            }
254            (None, None) => true,
255            _ => false,
256        };
257
258        self.client_id == other.client_id
259            && self.instrument == other.instrument
260            && self.side == other.side
261            && self.qty == other.qty
262            && self.limit == other.limit
263            && self.account_id == other.account_id
264            && self.trace == other.trace
265            && self.policy == other.policy
266            && same_exact_request
267    }
268
269    /// Compare stable order identity while allowing quantity, price, or
270    /// conditional terms to evolve through a confirmed amendment.
271    pub fn same_amendment_lineage(&self, other: &Self) -> bool {
272        let same_exact_contract = match (self.exact_amounts, other.exact_amounts) {
273            (Some(left), Some(right)) => {
274                left.quote_budget == right.quote_budget
275                    && left.market_reference_price == right.market_reference_price
276            }
277            (None, None) => true,
278            _ => false,
279        };
280
281        self.client_id == other.client_id
282            && self.instrument == other.instrument
283            && self.side == other.side
284            && self.account_id == other.account_id
285            && self.trace == other.trace
286            && self.policy == other.policy
287            && same_exact_contract
288    }
289
290    pub fn validate(&self) -> Result<(), String> {
291        if self.client_id == 0 {
292            return Err("client_order_id 必须为正".into());
293        }
294        if let Some(exact) = self.exact_amounts {
295            if self.qty.raw() != 0 || self.filled.raw() != 0 || self.limit.is_some() {
296                return Err("精确订单必须清空旧 1e9 数量/价格字段,不能同时携带两套金额".into());
297            }
298            if let Some(quote_budget) = exact.quote_budget {
299                if self.side != Side::Buy
300                    || exact.limit_price.is_some()
301                    || !exact.quantity.is_zero()
302                    || !quote_budget.is_positive()
303                {
304                    return Err(
305                        "计价币预算订单必须是正预算的精确市价买单,且不能携带基础币数量或限价"
306                            .into(),
307                    );
308                }
309                if exact.filled.is_negative()
310                    || exact.quote_filled.is_negative()
311                    || exact
312                        .quote_filled
313                        .checked_cmp(quote_budget)
314                        .is_none_or(|ordering| ordering.is_gt())
315                {
316                    return Err("计价币预算订单成交量或花费超出有效范围".into());
317                }
318            } else {
319                if !exact.quantity.is_positive() {
320                    return Err("订单数量必须为正".into());
321                }
322                if exact.filled.is_negative()
323                    || exact
324                        .filled
325                        .checked_cmp(exact.quantity)
326                        .is_none_or(|ordering| ordering.is_gt())
327                {
328                    return Err("订单已成交数量超出有效范围".into());
329                }
330                if !exact.quote_filled.is_zero() {
331                    return Err("基础币数量订单不能携带计价币成交花费".into());
332                }
333            }
334            if exact.limit_price.is_some_and(|price| !price.is_positive()) {
335                return Err("限价单价格必须为正".into());
336            }
337            if exact
338                .market_reference_price
339                .is_some_and(|price| !price.is_positive())
340            {
341                return Err("市价单风控参考价必须为正".into());
342            }
343            if exact.limit_price.is_some() && exact.market_reference_price.is_some() {
344                return Err("精确限价单不能同时携带市价风险参考价".into());
345            }
346            if let Some(conditional) = exact.conditional {
347                if exact.quote_budget.is_some() {
348                    return Err("条件单不能使用计价币预算数量".into());
349                }
350                let has_trailing = conditional.trailing_percent.is_some()
351                    || conditional.trailing_amount.is_some()
352                    || conditional.trailing_trigger_price.is_some();
353                match conditional.kind {
354                    ConditionalOrderKind::Trailing => {
355                        if conditional.trigger_price.is_some()
356                            || conditional.trigger_price_type.is_some()
357                            || (conditional.trailing_percent.is_some()
358                                == conditional.trailing_amount.is_some())
359                        {
360                            return Err(
361                                "追踪单必须且只能设置 trailing_percent 或 trailing_amount,不能设置普通触发价/来源".into(),
362                            );
363                        }
364                        if conditional
365                            .trailing_percent
366                            .is_some_and(|value| !value.is_positive())
367                            || conditional
368                                .trailing_amount
369                                .is_some_and(|value| !value.is_positive())
370                        {
371                            return Err("追踪幅度必须为正".into());
372                        }
373                    }
374                    _ => {
375                        if conditional
376                            .trigger_price
377                            .is_none_or(|value| !value.is_positive())
378                            || has_trailing
379                        {
380                            return Err(
381                                "触发/止损/止盈单必须提供正触发价,且不能携带追踪参数".into()
382                            );
383                        }
384                    }
385                }
386                if conditional
387                    .trailing_trigger_price
388                    .is_some_and(|value| !value.is_positive())
389                {
390                    return Err("追踪单启动价必须为正".into());
391                }
392            }
393        } else {
394            if self.qty.raw() <= 0 {
395                return Err("订单数量必须为正".into());
396            }
397            if self.filled.raw() < 0 || self.filled.raw() > self.qty.raw() {
398                return Err("订单已成交数量超出有效范围".into());
399            }
400            if self.limit.is_some_and(|price| price.raw() <= 0) {
401                return Err("限价单价格必须为正".into());
402            }
403        }
404        if self.account_id.trim().is_empty() {
405            return Err("订单账户不能为空".into());
406        }
407        if self
408            .trace
409            .as_ref()
410            .and_then(|trace| trace.run_id.as_deref())
411            .is_some_and(|run_id| run_id.trim().is_empty())
412        {
413            return Err("订单 run_id 不能为空字符串;未知运行身份应省略该字段".into());
414        }
415        if self.policy.is_some_and(|policy| policy.leverage == 0) {
416            return Err("订单杠杆必须大于 0".into());
417        }
418        Ok(())
419    }
420
421    /// Guard a legacy 1e9 consumer against silently reading an exact amount as zero.
422    pub fn require_legacy_amounts(&self) -> Result<(), String> {
423        if self.exact_amounts.is_some() {
424            return Err("该路径尚未接入精确订单金额,拒绝读取 1e9 兼容字段".into());
425        }
426        Ok(())
427    }
428
429    pub fn remaining(&self) -> Quantity {
430        Quantity::from_raw(self.qty.raw().saturating_sub(self.filled.raw()).max(0))
431    }
432
433    /// Exact quantity including a high-precision payload when present.
434    pub fn quantity_decimal(&self) -> ExactDecimal {
435        self.exact_amounts.map_or_else(
436            || ExactDecimal::from_legacy_raw(self.qty.raw()),
437            |amounts| amounts.quantity,
438        )
439    }
440
441    pub fn quote_budget_decimal(&self) -> Option<ExactDecimal> {
442        self.exact_amounts.and_then(|amounts| amounts.quote_budget)
443    }
444
445    pub fn quote_filled_decimal(&self) -> ExactDecimal {
446        self.exact_amounts
447            .map_or(ExactDecimal::ZERO, |amounts| amounts.quote_filled)
448    }
449
450    /// Remaining amount in the order's declared sizing unit. For quote-budget orders this
451    /// is quote currency; consumers doing quantity/exposure math must use `remaining_decimal`.
452    pub fn remaining_budget_decimal(&self) -> Option<ExactDecimal> {
453        let amounts = self.exact_amounts?;
454        amounts.quote_budget?.checked_sub(amounts.quote_filled)
455    }
456
457    pub fn is_quote_budget_order(&self) -> bool {
458        self.quote_budget_decimal().is_some()
459    }
460
461    /// Whether any amount remains in the order's own sizing unit.
462    pub fn has_remaining_amount(&self) -> bool {
463        if self.is_quote_budget_order() {
464            return self
465                .remaining_budget_decimal()
466                .is_some_and(ExactDecimal::is_positive);
467        }
468        self.remaining_decimal()
469            .is_some_and(ExactDecimal::is_positive)
470    }
471
472    pub fn filled_decimal(&self) -> ExactDecimal {
473        self.exact_amounts.map_or_else(
474            || ExactDecimal::from_legacy_raw(self.filled.raw()),
475            |amounts| amounts.filled,
476        )
477    }
478
479    pub fn limit_price_decimal(&self) -> Option<ExactDecimal> {
480        self.exact_amounts.map_or_else(
481            || {
482                self.limit
483                    .map(|price| ExactDecimal::from_legacy_raw(price.raw()))
484            },
485            |amounts| amounts.limit_price,
486        )
487    }
488
489    /// Price used to value an exact pending order. A market order carries the fresh
490    /// reference captured at admission so later reservations do not fall back to 1e-9.
491    pub fn market_reference_price_decimal(&self) -> Option<ExactDecimal> {
492        self.exact_amounts
493            .and_then(|amounts| amounts.market_reference_price)
494    }
495
496    pub fn remaining_decimal(&self) -> Option<ExactDecimal> {
497        self.quantity_decimal().checked_sub(self.filled_decimal())
498    }
499
500    pub fn trace_fill(
501        &self,
502        fill: &mut Fill,
503        venue_id: Option<&str>,
504        venue_order_id: Option<&str>,
505    ) {
506        if fill.account_id.is_empty() {
507            fill.account_id = self.account_id.clone();
508        }
509        fill.venue_id = venue_id.map(str::to_string);
510        fill.venue_order_id = venue_order_id.map(str::to_string);
511        if let Some(trace) = &self.trace {
512            fill.strategy_id = trace.strategy_id.clone();
513            fill.signal_id = trace.signal_id;
514            fill.intent_id = trace.intent_id;
515            fill.rule_version = trace.rule_version.clone();
516        }
517    }
518}
519
520/// 成交:不可变事实。
521#[derive(Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
522pub struct FillFee {
523    pub amount: Money,
524    /// Venue 币种;`None` 仅用于兼容旧 Fill,按账簿币种解释。
525    #[serde(default, skip_serializing_if = "Option::is_none")]
526    pub currency: Option<String>,
527    /// Venue trade IDs which contributed this fee row. Persisted so a restored adapter can
528    /// deduplicate trade-level fee queries after process restart.
529    #[serde(default, skip_serializing_if = "Vec::is_empty")]
530    pub source_trade_ids: Vec<String>,
531}
532
533#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
534pub struct ExactFillFee {
535    pub amount: ExactDecimal,
536    pub currency: Option<String>,
537    #[serde(default, skip_serializing_if = "Vec::is_empty")]
538    pub source_trade_ids: Vec<String>,
539}
540
541#[derive(Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
542pub struct Fill {
543    pub order_id: u64,
544    pub qty: Quantity,
545    pub price: Price,
546    pub fee: Money,
547    pub ts: Ts,
548    /// 成交归属账户。真实 Venue 回报必须填充;旧模拟路径允许为空并由 OMS 补齐。
549    pub account_id: String,
550    pub strategy_id: Option<String>,
551    pub signal_id: Option<u64>,
552    pub intent_id: Option<u64>,
553    pub venue_id: Option<String>,
554    pub venue_order_id: Option<String>,
555    pub rule_version: Option<String>,
556    pub fee_currency: Option<String>,
557    /// 按币种拆分的成交手续费。为空时读取旧的 `fee` / `fee_currency` 两格。
558    #[serde(default, skip_serializing_if = "Vec::is_empty")]
559    pub fees: Vec<FillFee>,
560    /// Scale-aware per-currency fee rows for fills that exceed the legacy 1e9 amount grid.
561    #[serde(default, skip_serializing_if = "Vec::is_empty")]
562    pub exact_fees: Vec<ExactFillFee>,
563    /// Versioned high-precision quantity/price payload; absent on legacy 1e9 fills.
564    #[serde(default, skip_serializing_if = "Option::is_none")]
565    pub exact_amounts: Option<ExactFillAmounts>,
566}
567
568impl Fill {
569    /// Stable suffix for trade identities and scale-aware fill fields used by replay dedup.
570    pub fn exact_identity_suffix(&self) -> String {
571        let mut components = Vec::new();
572        if let Some(amounts) = self.exact_amounts {
573            components.push(format!(
574                "amount={}:{};price={}:{}",
575                amounts.quantity.coefficient(),
576                amounts.quantity.scale(),
577                amounts.price.coefficient(),
578                amounts.price.scale(),
579            ));
580        }
581        for fee in &self.exact_fees {
582            let mut trade_ids = fee.source_trade_ids.clone();
583            trade_ids.sort();
584            components.push(format!(
585                "fee={}:{};currency={};trades={}",
586                fee.amount.coefficient(),
587                fee.amount.scale(),
588                fee.currency.as_deref().unwrap_or_default(),
589                trade_ids
590                    .iter()
591                    .map(|trade_id| format!("{}:{trade_id}", trade_id.len()))
592                    .collect::<Vec<_>>()
593                    .join(","),
594            ));
595        }
596        if self.exact_fees.is_empty() {
597            for fee in &self.fees {
598                if fee.source_trade_ids.is_empty() {
599                    continue;
600                }
601                let mut trade_ids = fee.source_trade_ids.clone();
602                trade_ids.sort();
603                components.push(format!(
604                    "trades={}",
605                    trade_ids
606                        .iter()
607                        .map(|trade_id| format!("{}:{trade_id}", trade_id.len()))
608                        .collect::<Vec<_>>()
609                        .join(","),
610                ));
611            }
612        }
613        if components.is_empty() {
614            return String::new();
615        }
616        components.sort();
617        format!("|exact:{}", components.join("|"))
618    }
619
620    pub fn validate_exact_amounts(&self) -> Result<(), String> {
621        if let Some(exact) = self.exact_amounts {
622            if self.qty.raw() != 0 || self.price.raw() != 0 {
623                return Err("精确成交必须清空旧 1e9 数量/价格字段,不能同时携带两套金额".into());
624            }
625            if !exact.quantity.is_positive() || !exact.price.is_positive() {
626                return Err("精确成交数量和价格必须为正".into());
627            }
628            if exact.quote_cost.is_some_and(|cost| !cost.is_positive()) {
629                return Err("精确成交计价币成本必须为正".into());
630            }
631            if exact.quote_budget_complete && exact.quote_cost.is_none() {
632                return Err("quote_budget 完成标记必须包含精确计价币成本".into());
633            }
634        }
635        Ok(())
636    }
637
638    /// Guard a legacy 1e9 consumer against silently reading an exact fill as zero.
639    pub fn require_legacy_amounts(&self) -> Result<(), String> {
640        if self.exact_amounts.is_some() {
641            return Err("该路径尚未接入精确成交金额,拒绝读取 1e9 兼容字段".into());
642        }
643        Ok(())
644    }
645
646    pub fn quantity_decimal(&self) -> ExactDecimal {
647        self.exact_amounts.map_or_else(
648            || ExactDecimal::from_legacy_raw(self.qty.raw()),
649            |amounts| amounts.quantity,
650        )
651    }
652
653    pub fn price_decimal(&self) -> ExactDecimal {
654        self.exact_amounts.map_or_else(
655            || ExactDecimal::from_legacy_raw(self.price.raw()),
656            |amounts| amounts.price,
657        )
658    }
659
660    /// 读取新旧格式统一的费用事实,并拒绝同时写入互相矛盾的字段。
661    pub fn fee_charges(&self) -> Result<Vec<FillFee>, String> {
662        if !self.exact_fees.is_empty() {
663            return Err("精确手续费必须由精确账簿路径读取,不能投影到 1e9 Money".into());
664        }
665        if self.fees.is_empty() {
666            return Ok(if self.fee.raw() == 0 {
667                Vec::new()
668            } else {
669                vec![FillFee {
670                    amount: self.fee,
671                    currency: self.fee_currency.clone(),
672                    source_trade_ids: Vec::new(),
673                }]
674            });
675        }
676        if self.fee.raw() != 0
677            && (self.fees.len() != 1
678                || self.fees[0].amount != self.fee
679                || self.fees[0].currency.as_deref() != self.fee_currency.as_deref())
680        {
681            return Err("Fill 的兼容手续费字段与 fees 明细冲突".into());
682        }
683        for charge in &self.fees {
684            if charge.amount.raw() != 0
685                && charge
686                    .currency
687                    .as_deref()
688                    .is_none_or(|currency| currency.trim().is_empty())
689            {
690                return Err("非零 Fill 手续费必须声明币种".into());
691            }
692        }
693        Ok(self.fees.clone())
694    }
695}
696
697#[cfg(test)]
698mod tests {
699    use super::*;
700
701    #[test]
702    fn order_trace_run_identity_is_optional_backward_compatible_and_nonempty() {
703        let legacy: OrderTrace = serde_json::from_str(
704            r#"{"strategy_id":"legacy","signal_id":null,"intent_id":null,"rule_version":null}"#,
705        )
706        .unwrap();
707        assert_eq!(legacy.run_id, None);
708
709        let mut order = Order {
710            client_id: 1,
711            instrument: InstrumentId::parse("BTC/USDT.OKX").unwrap(),
712            side: Side::Buy,
713            qty: Quantity::from_i64(1),
714            limit: None,
715            status: OrderStatus::PendingSubmit,
716            filled: Quantity::ZERO,
717            account_id: "main".into(),
718            trace: Some(OrderTrace {
719                run_id: Some("  ".into()),
720                strategy_id: Some("strategy".into()),
721                signal_id: None,
722                intent_id: None,
723                rule_version: None,
724            }),
725            policy: None,
726            exact_amounts: None,
727        };
728        assert!(order.validate().unwrap_err().contains("run_id"));
729        order.trace.as_mut().unwrap().run_id = Some("run-42".into());
730        order.validate().unwrap();
731    }
732
733    #[test]
734    fn conditional_order_terms_are_validated_and_part_of_idempotency_identity() {
735        let mut order = Order {
736            client_id: 41,
737            instrument: InstrumentId::parse("BTC/USDT.OKX").unwrap(),
738            side: Side::Sell,
739            qty: Quantity::ZERO,
740            limit: None,
741            status: OrderStatus::PendingSubmit,
742            filled: Quantity::ZERO,
743            account_id: "main".into(),
744            trace: None,
745            policy: None,
746            exact_amounts: Some(ExactOrderAmounts {
747                quantity: ExactDecimal::parse("0.01").unwrap(),
748                limit_price: None,
749                filled: ExactDecimal::ZERO,
750                quote_budget: None,
751                quote_filled: ExactDecimal::ZERO,
752                market_reference_price: Some(ExactDecimal::parse("65000").unwrap()),
753                conditional: Some(ConditionalOrderIntent {
754                    kind: ConditionalOrderKind::StopLoss,
755                    trigger_price: Some(ExactDecimal::parse("62000").unwrap()),
756                    trigger_price_type: Some(TriggerPriceType::Mark),
757                    trailing_percent: None,
758                    trailing_amount: None,
759                    trailing_trigger_price: None,
760                }),
761            }),
762        };
763        order.validate().unwrap();
764        let mut retry = order.clone();
765        retry
766            .exact_amounts
767            .as_mut()
768            .unwrap()
769            .conditional
770            .as_mut()
771            .unwrap()
772            .trigger_price = Some(ExactDecimal::parse("61000").unwrap());
773        assert!(!order.same_submission_identity(&retry));
774
775        let intent = order
776            .exact_amounts
777            .as_mut()
778            .unwrap()
779            .conditional
780            .as_mut()
781            .unwrap();
782        intent.trigger_price = None;
783        assert!(order.validate().unwrap_err().contains("正触发价"));
784    }
785
786    #[test]
787    fn remaining_decreases() {
788        let o = Order {
789            client_id: 1,
790            instrument: InstrumentId::parse("X.Y").unwrap(),
791            side: Side::Buy,
792            qty: Quantity::from_i64(10),
793            limit: None,
794            status: OrderStatus::PartiallyFilled,
795            filled: Quantity::from_i64(4),
796            account_id: "a".into(),
797            trace: None,
798            policy: None,
799
800            exact_amounts: None,
801        };
802        assert_eq!(o.remaining().raw(), Quantity::from_i64(6).raw());
803        assert!(!o.status.is_terminal());
804    }
805
806    #[test]
807    fn unknown_requires_reconcile_before_recovery() {
808        assert!(OrderStatus::PendingSubmit.can_transition_to(OrderStatus::Unknown));
809        assert!(OrderStatus::Submitted.can_transition_to(OrderStatus::Unknown));
810        assert!(OrderStatus::Unknown.can_transition_to(OrderStatus::Accepted));
811        assert!(!OrderStatus::CancelPending.can_transition_to(OrderStatus::PartiallyFilled));
812        assert!(OrderStatus::CancelPending.can_transition_to(OrderStatus::Filled));
813        assert!(!OrderStatus::Filled.can_transition_to(OrderStatus::Working));
814    }
815
816    #[test]
817    fn invalid_order_shape_is_rejected_before_submission() {
818        let mut order = Order {
819            client_id: 1,
820            instrument: InstrumentId::parse("X.Y").unwrap(),
821            side: Side::Buy,
822            qty: Quantity::from_i64(1),
823            limit: Some(Price::from_i64(10)),
824            status: OrderStatus::Submitted,
825            filled: Quantity::ZERO,
826            account_id: "a".into(),
827            trace: None,
828            policy: None,
829
830            exact_amounts: None,
831        };
832        assert!(order.validate().is_ok());
833        order.qty = Quantity::ZERO;
834        assert!(order.validate().is_err());
835    }
836
837    #[test]
838    fn exact_order_amounts_keep_sub_nano_values_and_round_trip() {
839        let exact = ExactOrderAmounts {
840            quantity: ExactDecimal::parse("0.000000000123456789").unwrap(),
841            limit_price: Some(ExactDecimal::parse("0.00000001").unwrap()),
842            filled: ExactDecimal::parse("0.000000000023456789").unwrap(),
843            market_reference_price: None,
844            quote_budget: None,
845            quote_filled: Default::default(),
846            conditional: None,
847        };
848        let order = Order {
849            client_id: 2,
850            instrument: InstrumentId::parse("PEPE/USDT.OKX").unwrap(),
851            side: Side::Buy,
852            qty: Quantity::ZERO,
853            limit: None,
854            status: OrderStatus::PartiallyFilled,
855            filled: Quantity::ZERO,
856            account_id: "main".into(),
857            trace: None,
858            policy: None,
859            exact_amounts: Some(exact),
860        };
861
862        order.validate().unwrap();
863        assert_eq!(
864            order.remaining_decimal().unwrap(),
865            ExactDecimal::parse("0.0000000001").unwrap()
866        );
867        assert_eq!(order.quantity_decimal(), exact.quantity);
868        assert_eq!(order.limit_price_decimal(), exact.limit_price);
869
870        let encoded = serde_json::to_string(&order).unwrap();
871        let decoded: Order = serde_json::from_str(&encoded).unwrap();
872        assert_eq!(decoded, order);
873        assert!(encoded.contains("\"coefficient\":\"123456789\""));
874    }
875
876    #[test]
877    fn exact_amounts_reject_ambiguous_legacy_fields_and_invalid_fills() {
878        let mut order = Order {
879            client_id: 3,
880            instrument: InstrumentId::parse("SHIB/USDT.BINANCE").unwrap(),
881            side: Side::Buy,
882            qty: Quantity::from_i64(1),
883            limit: None,
884            status: OrderStatus::Submitted,
885            filled: Quantity::ZERO,
886            account_id: "main".into(),
887            trace: None,
888            policy: None,
889            exact_amounts: Some(ExactOrderAmounts {
890                quantity: ExactDecimal::parse("1000.0000000001").unwrap(),
891                limit_price: None,
892                filled: ExactDecimal::ZERO,
893                market_reference_price: None,
894                quote_budget: None,
895                quote_filled: Default::default(),
896                conditional: None,
897            }),
898        };
899        assert!(order.validate().is_err());
900        order.qty = Quantity::ZERO;
901        order.validate().unwrap();
902
903        let mut fill = Fill {
904            order_id: 3,
905            exact_amounts: Some(ExactFillAmounts {
906                quantity: ExactDecimal::ZERO,
907                price: ExactDecimal::parse("0.00000001").unwrap(),
908                quote_cost: None,
909                quote_budget_complete: false,
910            }),
911            ..Fill::default()
912        };
913        assert!(fill.validate_exact_amounts().is_err());
914        fill.exact_amounts.as_mut().unwrap().quantity =
915            ExactDecimal::parse("0.0000000001").unwrap();
916        fill.validate_exact_amounts().unwrap();
917    }
918
919    #[test]
920    fn order_wire_rejects_unknown_fields_and_keeps_legacy_optional_fields_readable() {
921        let policy = OrderPolicy {
922            reduce_only: false,
923            position_side: crate::PositionSide::Net,
924            margin_mode: crate::MarginMode::Cross,
925            position_mode: crate::PositionMode::OneWay,
926            leverage: 3,
927            post_only: false,
928        };
929        let order = Order {
930            client_id: 9,
931            instrument: InstrumentId::parse("BTCUSDT.BINANCE").unwrap(),
932            side: Side::Buy,
933            qty: Quantity::from_i64(1),
934            limit: None,
935            status: OrderStatus::PendingSubmit,
936            filled: Quantity::ZERO,
937            account_id: "main".into(),
938            trace: None,
939            policy: Some(policy),
940            exact_amounts: None,
941        };
942
943        let mut misspelled_policy = serde_json::to_value(&order).unwrap();
944        let object = misspelled_policy.as_object_mut().unwrap();
945        let policy = object.remove("policy").unwrap();
946        object.insert("polciy".into(), policy);
947        assert!(serde_json::from_value::<Order>(misspelled_policy).is_err());
948
949        let mut misspelled_policy_field = serde_json::to_value(&order).unwrap();
950        misspelled_policy_field["policy"]["post_onli"] = serde_json::Value::Bool(true);
951        assert!(serde_json::from_value::<Order>(misspelled_policy_field).is_err());
952
953        let mut legacy = serde_json::to_value(Order {
954            policy: None,
955            ..order
956        })
957        .unwrap();
958        let object = legacy.as_object_mut().unwrap();
959        object.remove("policy");
960        object.remove("exact_amounts");
961        let decoded: Order = serde_json::from_value(legacy).unwrap();
962        assert!(decoded.policy.is_none());
963        assert!(decoded.exact_amounts.is_none());
964    }
965}