use crate::clock::Ts;
use crate::identity::InstrumentId;
use crate::numeric::{ExactDecimal, Money, Price, Quantity};
use crate::trading::OrderPolicy;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Side {
Buy,
Sell,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum OrderStatus {
PendingSubmit,
Submitted,
Accepted,
Working,
PartiallyFilled,
Filled,
CancelPending,
Cancelled,
Rejected,
Expired,
Unknown,
}
impl OrderStatus {
pub fn is_terminal(self) -> bool {
matches!(
self,
OrderStatus::Filled
| OrderStatus::Cancelled
| OrderStatus::Rejected
| OrderStatus::Expired
)
}
pub fn can_transition_to(self, next: Self) -> bool {
use OrderStatus::*;
if self == next {
return !self.is_terminal();
}
matches!(
(self, next),
(PendingSubmit, Submitted | Rejected | Unknown)
| (Submitted, Accepted | CancelPending | Rejected | Unknown)
| (Accepted, Working | CancelPending | Rejected | Unknown)
| (
Working,
PartiallyFilled | Filled | CancelPending | Rejected | Expired | Unknown
)
| (
PartiallyFilled,
PartiallyFilled | Filled | CancelPending | Expired | Unknown
)
| (CancelPending, Cancelled | Filled | Unknown)
| (
Unknown,
Accepted | Working | PartiallyFilled | Filled | Cancelled | Rejected | Expired
)
)
}
pub fn reconciliation_path(self, target: Self) -> Option<Vec<Self>> {
const STATUSES: [OrderStatus; 11] = [
OrderStatus::PendingSubmit,
OrderStatus::Submitted,
OrderStatus::Accepted,
OrderStatus::Working,
OrderStatus::PartiallyFilled,
OrderStatus::Filled,
OrderStatus::CancelPending,
OrderStatus::Cancelled,
OrderStatus::Rejected,
OrderStatus::Expired,
OrderStatus::Unknown,
];
if self == target {
return Some(Vec::new());
}
let mut queue = VecDeque::from([(self, Vec::new())]);
let mut visited = vec![self];
while let Some((status, path)) = queue.pop_front() {
for next in STATUSES {
if !status.can_transition_to(next)
|| (next == OrderStatus::Unknown && self != OrderStatus::Unknown)
|| visited.contains(&next)
{
continue;
}
let mut next_path = path.clone();
next_path.push(next);
if next == target {
return Some(next_path);
}
visited.push(next);
queue.push_back((next, next_path));
}
}
None
}
pub fn transition(&mut self, next: Self) -> Result<(), String> {
if self.can_transition_to(next) {
*self = next;
Ok(())
} else {
Err(format!("非法订单状态迁移: {:?} -> {:?}", self, next))
}
}
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OrderTrace {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_id: Option<String>,
pub strategy_id: Option<String>,
pub signal_id: Option<u64>,
pub intent_id: Option<u64>,
pub rule_version: Option<String>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExactOrderAmounts {
pub quantity: ExactDecimal,
pub limit_price: Option<ExactDecimal>,
pub filled: ExactDecimal,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quote_budget: Option<ExactDecimal>,
#[serde(default)]
pub quote_filled: ExactDecimal,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub market_reference_price: Option<ExactDecimal>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conditional: Option<ConditionalOrderIntent>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConditionalOrderKind {
Trigger,
StopLoss,
TakeProfit,
Trailing,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TriggerPriceType {
Last,
Mark,
Index,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConditionalOrderIntent {
pub kind: ConditionalOrderKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trigger_price: Option<ExactDecimal>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trigger_price_type: Option<TriggerPriceType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trailing_percent: Option<ExactDecimal>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trailing_amount: Option<ExactDecimal>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trailing_trigger_price: Option<ExactDecimal>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct ExactFillAmounts {
pub quantity: ExactDecimal,
pub price: ExactDecimal,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quote_cost: Option<ExactDecimal>,
#[serde(default, skip_serializing_if = "is_false")]
pub quote_budget_complete: bool,
}
fn is_false(value: &bool) -> bool {
!*value
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Order {
pub client_id: u64,
pub instrument: InstrumentId,
pub side: Side,
pub qty: Quantity,
pub limit: Option<Price>,
pub status: OrderStatus,
pub filled: Quantity,
pub account_id: String,
pub trace: Option<OrderTrace>,
#[serde(default)]
pub policy: Option<OrderPolicy>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exact_amounts: Option<ExactOrderAmounts>,
}
impl Order {
pub fn same_submission_identity(&self, other: &Self) -> bool {
let same_exact_request = match (self.exact_amounts, other.exact_amounts) {
(Some(left), Some(right)) => {
left.quantity == right.quantity
&& left.limit_price == right.limit_price
&& left.quote_budget == right.quote_budget
&& left.market_reference_price == right.market_reference_price
&& left.conditional == right.conditional
}
(None, None) => true,
_ => false,
};
self.client_id == other.client_id
&& self.instrument == other.instrument
&& self.side == other.side
&& self.qty == other.qty
&& self.limit == other.limit
&& self.account_id == other.account_id
&& self.trace == other.trace
&& self.policy == other.policy
&& same_exact_request
}
pub fn same_amendment_lineage(&self, other: &Self) -> bool {
let same_exact_contract = match (self.exact_amounts, other.exact_amounts) {
(Some(left), Some(right)) => {
left.quote_budget == right.quote_budget
&& left.market_reference_price == right.market_reference_price
}
(None, None) => true,
_ => false,
};
self.client_id == other.client_id
&& self.instrument == other.instrument
&& self.side == other.side
&& self.account_id == other.account_id
&& self.trace == other.trace
&& self.policy == other.policy
&& same_exact_contract
}
pub fn validate(&self) -> Result<(), String> {
if self.client_id == 0 {
return Err("client_order_id 必须为正".into());
}
if let Some(exact) = self.exact_amounts {
if self.qty.raw() != 0 || self.filled.raw() != 0 || self.limit.is_some() {
return Err("精确订单必须清空旧 1e9 数量/价格字段,不能同时携带两套金额".into());
}
if let Some(quote_budget) = exact.quote_budget {
if self.side != Side::Buy
|| exact.limit_price.is_some()
|| !exact.quantity.is_zero()
|| !quote_budget.is_positive()
{
return Err(
"计价币预算订单必须是正预算的精确市价买单,且不能携带基础币数量或限价"
.into(),
);
}
if exact.filled.is_negative()
|| exact.quote_filled.is_negative()
|| exact
.quote_filled
.checked_cmp(quote_budget)
.is_none_or(|ordering| ordering.is_gt())
{
return Err("计价币预算订单成交量或花费超出有效范围".into());
}
} else {
if !exact.quantity.is_positive() {
return Err("订单数量必须为正".into());
}
if exact.filled.is_negative()
|| exact
.filled
.checked_cmp(exact.quantity)
.is_none_or(|ordering| ordering.is_gt())
{
return Err("订单已成交数量超出有效范围".into());
}
if !exact.quote_filled.is_zero() {
return Err("基础币数量订单不能携带计价币成交花费".into());
}
}
if exact.limit_price.is_some_and(|price| !price.is_positive()) {
return Err("限价单价格必须为正".into());
}
if exact
.market_reference_price
.is_some_and(|price| !price.is_positive())
{
return Err("市价单风控参考价必须为正".into());
}
if exact.limit_price.is_some() && exact.market_reference_price.is_some() {
return Err("精确限价单不能同时携带市价风险参考价".into());
}
if let Some(conditional) = exact.conditional {
if exact.quote_budget.is_some() {
return Err("条件单不能使用计价币预算数量".into());
}
let has_trailing = conditional.trailing_percent.is_some()
|| conditional.trailing_amount.is_some()
|| conditional.trailing_trigger_price.is_some();
match conditional.kind {
ConditionalOrderKind::Trailing => {
if conditional.trigger_price.is_some()
|| conditional.trigger_price_type.is_some()
|| (conditional.trailing_percent.is_some()
== conditional.trailing_amount.is_some())
{
return Err(
"追踪单必须且只能设置 trailing_percent 或 trailing_amount,不能设置普通触发价/来源".into(),
);
}
if conditional
.trailing_percent
.is_some_and(|value| !value.is_positive())
|| conditional
.trailing_amount
.is_some_and(|value| !value.is_positive())
{
return Err("追踪幅度必须为正".into());
}
}
_ => {
if conditional
.trigger_price
.is_none_or(|value| !value.is_positive())
|| has_trailing
{
return Err(
"触发/止损/止盈单必须提供正触发价,且不能携带追踪参数".into()
);
}
}
}
if conditional
.trailing_trigger_price
.is_some_and(|value| !value.is_positive())
{
return Err("追踪单启动价必须为正".into());
}
}
} else {
if self.qty.raw() <= 0 {
return Err("订单数量必须为正".into());
}
if self.filled.raw() < 0 || self.filled.raw() > self.qty.raw() {
return Err("订单已成交数量超出有效范围".into());
}
if self.limit.is_some_and(|price| price.raw() <= 0) {
return Err("限价单价格必须为正".into());
}
}
if self.account_id.trim().is_empty() {
return Err("订单账户不能为空".into());
}
if self
.trace
.as_ref()
.and_then(|trace| trace.run_id.as_deref())
.is_some_and(|run_id| run_id.trim().is_empty())
{
return Err("订单 run_id 不能为空字符串;未知运行身份应省略该字段".into());
}
if self.policy.is_some_and(|policy| policy.leverage == 0) {
return Err("订单杠杆必须大于 0".into());
}
Ok(())
}
pub fn require_legacy_amounts(&self) -> Result<(), String> {
if self.exact_amounts.is_some() {
return Err("该路径尚未接入精确订单金额,拒绝读取 1e9 兼容字段".into());
}
Ok(())
}
pub fn remaining(&self) -> Quantity {
Quantity::from_raw(self.qty.raw().saturating_sub(self.filled.raw()).max(0))
}
pub fn quantity_decimal(&self) -> ExactDecimal {
self.exact_amounts.map_or_else(
|| ExactDecimal::from_legacy_raw(self.qty.raw()),
|amounts| amounts.quantity,
)
}
pub fn quote_budget_decimal(&self) -> Option<ExactDecimal> {
self.exact_amounts.and_then(|amounts| amounts.quote_budget)
}
pub fn quote_filled_decimal(&self) -> ExactDecimal {
self.exact_amounts
.map_or(ExactDecimal::ZERO, |amounts| amounts.quote_filled)
}
pub fn remaining_budget_decimal(&self) -> Option<ExactDecimal> {
let amounts = self.exact_amounts?;
amounts.quote_budget?.checked_sub(amounts.quote_filled)
}
pub fn is_quote_budget_order(&self) -> bool {
self.quote_budget_decimal().is_some()
}
pub fn has_remaining_amount(&self) -> bool {
if self.is_quote_budget_order() {
return self
.remaining_budget_decimal()
.is_some_and(ExactDecimal::is_positive);
}
self.remaining_decimal()
.is_some_and(ExactDecimal::is_positive)
}
pub fn filled_decimal(&self) -> ExactDecimal {
self.exact_amounts.map_or_else(
|| ExactDecimal::from_legacy_raw(self.filled.raw()),
|amounts| amounts.filled,
)
}
pub fn limit_price_decimal(&self) -> Option<ExactDecimal> {
self.exact_amounts.map_or_else(
|| {
self.limit
.map(|price| ExactDecimal::from_legacy_raw(price.raw()))
},
|amounts| amounts.limit_price,
)
}
pub fn market_reference_price_decimal(&self) -> Option<ExactDecimal> {
self.exact_amounts
.and_then(|amounts| amounts.market_reference_price)
}
pub fn remaining_decimal(&self) -> Option<ExactDecimal> {
self.quantity_decimal().checked_sub(self.filled_decimal())
}
pub fn trace_fill(
&self,
fill: &mut Fill,
venue_id: Option<&str>,
venue_order_id: Option<&str>,
) {
if fill.account_id.is_empty() {
fill.account_id = self.account_id.clone();
}
fill.venue_id = venue_id.map(str::to_string);
fill.venue_order_id = venue_order_id.map(str::to_string);
if let Some(trace) = &self.trace {
fill.strategy_id = trace.strategy_id.clone();
fill.signal_id = trace.signal_id;
fill.intent_id = trace.intent_id;
fill.rule_version = trace.rule_version.clone();
}
}
}
#[derive(Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
pub struct FillFee {
pub amount: Money,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub currency: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub source_trade_ids: Vec<String>,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct ExactFillFee {
pub amount: ExactDecimal,
pub currency: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub source_trade_ids: Vec<String>,
}
#[derive(Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
pub struct Fill {
pub order_id: u64,
pub qty: Quantity,
pub price: Price,
pub fee: Money,
pub ts: Ts,
pub account_id: String,
pub strategy_id: Option<String>,
pub signal_id: Option<u64>,
pub intent_id: Option<u64>,
pub venue_id: Option<String>,
pub venue_order_id: Option<String>,
pub rule_version: Option<String>,
pub fee_currency: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fees: Vec<FillFee>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub exact_fees: Vec<ExactFillFee>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exact_amounts: Option<ExactFillAmounts>,
}
impl Fill {
pub fn exact_identity_suffix(&self) -> String {
let mut components = Vec::new();
if let Some(amounts) = self.exact_amounts {
components.push(format!(
"amount={}:{};price={}:{}",
amounts.quantity.coefficient(),
amounts.quantity.scale(),
amounts.price.coefficient(),
amounts.price.scale(),
));
}
for fee in &self.exact_fees {
let mut trade_ids = fee.source_trade_ids.clone();
trade_ids.sort();
components.push(format!(
"fee={}:{};currency={};trades={}",
fee.amount.coefficient(),
fee.amount.scale(),
fee.currency.as_deref().unwrap_or_default(),
trade_ids
.iter()
.map(|trade_id| format!("{}:{trade_id}", trade_id.len()))
.collect::<Vec<_>>()
.join(","),
));
}
if self.exact_fees.is_empty() {
for fee in &self.fees {
if fee.source_trade_ids.is_empty() {
continue;
}
let mut trade_ids = fee.source_trade_ids.clone();
trade_ids.sort();
components.push(format!(
"trades={}",
trade_ids
.iter()
.map(|trade_id| format!("{}:{trade_id}", trade_id.len()))
.collect::<Vec<_>>()
.join(","),
));
}
}
if components.is_empty() {
return String::new();
}
components.sort();
format!("|exact:{}", components.join("|"))
}
pub fn validate_exact_amounts(&self) -> Result<(), String> {
if let Some(exact) = self.exact_amounts {
if self.qty.raw() != 0 || self.price.raw() != 0 {
return Err("精确成交必须清空旧 1e9 数量/价格字段,不能同时携带两套金额".into());
}
if !exact.quantity.is_positive() || !exact.price.is_positive() {
return Err("精确成交数量和价格必须为正".into());
}
if exact.quote_cost.is_some_and(|cost| !cost.is_positive()) {
return Err("精确成交计价币成本必须为正".into());
}
if exact.quote_budget_complete && exact.quote_cost.is_none() {
return Err("quote_budget 完成标记必须包含精确计价币成本".into());
}
}
Ok(())
}
pub fn require_legacy_amounts(&self) -> Result<(), String> {
if self.exact_amounts.is_some() {
return Err("该路径尚未接入精确成交金额,拒绝读取 1e9 兼容字段".into());
}
Ok(())
}
pub fn quantity_decimal(&self) -> ExactDecimal {
self.exact_amounts.map_or_else(
|| ExactDecimal::from_legacy_raw(self.qty.raw()),
|amounts| amounts.quantity,
)
}
pub fn price_decimal(&self) -> ExactDecimal {
self.exact_amounts.map_or_else(
|| ExactDecimal::from_legacy_raw(self.price.raw()),
|amounts| amounts.price,
)
}
pub fn fee_charges(&self) -> Result<Vec<FillFee>, String> {
if !self.exact_fees.is_empty() {
return Err("精确手续费必须由精确账簿路径读取,不能投影到 1e9 Money".into());
}
if self.fees.is_empty() {
return Ok(if self.fee.raw() == 0 {
Vec::new()
} else {
vec![FillFee {
amount: self.fee,
currency: self.fee_currency.clone(),
source_trade_ids: Vec::new(),
}]
});
}
if self.fee.raw() != 0
&& (self.fees.len() != 1
|| self.fees[0].amount != self.fee
|| self.fees[0].currency.as_deref() != self.fee_currency.as_deref())
{
return Err("Fill 的兼容手续费字段与 fees 明细冲突".into());
}
for charge in &self.fees {
if charge.amount.raw() != 0
&& charge
.currency
.as_deref()
.is_none_or(|currency| currency.trim().is_empty())
{
return Err("非零 Fill 手续费必须声明币种".into());
}
}
Ok(self.fees.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn order_trace_run_identity_is_optional_backward_compatible_and_nonempty() {
let legacy: OrderTrace = serde_json::from_str(
r#"{"strategy_id":"legacy","signal_id":null,"intent_id":null,"rule_version":null}"#,
)
.unwrap();
assert_eq!(legacy.run_id, None);
let mut order = Order {
client_id: 1,
instrument: InstrumentId::parse("BTC/USDT.OKX").unwrap(),
side: Side::Buy,
qty: Quantity::from_i64(1),
limit: None,
status: OrderStatus::PendingSubmit,
filled: Quantity::ZERO,
account_id: "main".into(),
trace: Some(OrderTrace {
run_id: Some(" ".into()),
strategy_id: Some("strategy".into()),
signal_id: None,
intent_id: None,
rule_version: None,
}),
policy: None,
exact_amounts: None,
};
assert!(order.validate().unwrap_err().contains("run_id"));
order.trace.as_mut().unwrap().run_id = Some("run-42".into());
order.validate().unwrap();
}
#[test]
fn conditional_order_terms_are_validated_and_part_of_idempotency_identity() {
let mut order = Order {
client_id: 41,
instrument: InstrumentId::parse("BTC/USDT.OKX").unwrap(),
side: Side::Sell,
qty: Quantity::ZERO,
limit: None,
status: OrderStatus::PendingSubmit,
filled: Quantity::ZERO,
account_id: "main".into(),
trace: None,
policy: None,
exact_amounts: Some(ExactOrderAmounts {
quantity: ExactDecimal::parse("0.01").unwrap(),
limit_price: None,
filled: ExactDecimal::ZERO,
quote_budget: None,
quote_filled: ExactDecimal::ZERO,
market_reference_price: Some(ExactDecimal::parse("65000").unwrap()),
conditional: Some(ConditionalOrderIntent {
kind: ConditionalOrderKind::StopLoss,
trigger_price: Some(ExactDecimal::parse("62000").unwrap()),
trigger_price_type: Some(TriggerPriceType::Mark),
trailing_percent: None,
trailing_amount: None,
trailing_trigger_price: None,
}),
}),
};
order.validate().unwrap();
let mut retry = order.clone();
retry
.exact_amounts
.as_mut()
.unwrap()
.conditional
.as_mut()
.unwrap()
.trigger_price = Some(ExactDecimal::parse("61000").unwrap());
assert!(!order.same_submission_identity(&retry));
let intent = order
.exact_amounts
.as_mut()
.unwrap()
.conditional
.as_mut()
.unwrap();
intent.trigger_price = None;
assert!(order.validate().unwrap_err().contains("正触发价"));
}
#[test]
fn remaining_decreases() {
let o = Order {
client_id: 1,
instrument: InstrumentId::parse("X.Y").unwrap(),
side: Side::Buy,
qty: Quantity::from_i64(10),
limit: None,
status: OrderStatus::PartiallyFilled,
filled: Quantity::from_i64(4),
account_id: "a".into(),
trace: None,
policy: None,
exact_amounts: None,
};
assert_eq!(o.remaining().raw(), Quantity::from_i64(6).raw());
assert!(!o.status.is_terminal());
}
#[test]
fn unknown_requires_reconcile_before_recovery() {
assert!(OrderStatus::PendingSubmit.can_transition_to(OrderStatus::Unknown));
assert!(OrderStatus::Submitted.can_transition_to(OrderStatus::Unknown));
assert!(OrderStatus::Unknown.can_transition_to(OrderStatus::Accepted));
assert!(!OrderStatus::CancelPending.can_transition_to(OrderStatus::PartiallyFilled));
assert!(OrderStatus::CancelPending.can_transition_to(OrderStatus::Filled));
assert!(!OrderStatus::Filled.can_transition_to(OrderStatus::Working));
}
#[test]
fn invalid_order_shape_is_rejected_before_submission() {
let mut order = Order {
client_id: 1,
instrument: InstrumentId::parse("X.Y").unwrap(),
side: Side::Buy,
qty: Quantity::from_i64(1),
limit: Some(Price::from_i64(10)),
status: OrderStatus::Submitted,
filled: Quantity::ZERO,
account_id: "a".into(),
trace: None,
policy: None,
exact_amounts: None,
};
assert!(order.validate().is_ok());
order.qty = Quantity::ZERO;
assert!(order.validate().is_err());
}
#[test]
fn exact_order_amounts_keep_sub_nano_values_and_round_trip() {
let exact = ExactOrderAmounts {
quantity: ExactDecimal::parse("0.000000000123456789").unwrap(),
limit_price: Some(ExactDecimal::parse("0.00000001").unwrap()),
filled: ExactDecimal::parse("0.000000000023456789").unwrap(),
market_reference_price: None,
quote_budget: None,
quote_filled: Default::default(),
conditional: None,
};
let order = Order {
client_id: 2,
instrument: InstrumentId::parse("PEPE/USDT.OKX").unwrap(),
side: Side::Buy,
qty: Quantity::ZERO,
limit: None,
status: OrderStatus::PartiallyFilled,
filled: Quantity::ZERO,
account_id: "main".into(),
trace: None,
policy: None,
exact_amounts: Some(exact),
};
order.validate().unwrap();
assert_eq!(
order.remaining_decimal().unwrap(),
ExactDecimal::parse("0.0000000001").unwrap()
);
assert_eq!(order.quantity_decimal(), exact.quantity);
assert_eq!(order.limit_price_decimal(), exact.limit_price);
let encoded = serde_json::to_string(&order).unwrap();
let decoded: Order = serde_json::from_str(&encoded).unwrap();
assert_eq!(decoded, order);
assert!(encoded.contains("\"coefficient\":\"123456789\""));
}
#[test]
fn exact_amounts_reject_ambiguous_legacy_fields_and_invalid_fills() {
let mut order = Order {
client_id: 3,
instrument: InstrumentId::parse("SHIB/USDT.BINANCE").unwrap(),
side: Side::Buy,
qty: Quantity::from_i64(1),
limit: None,
status: OrderStatus::Submitted,
filled: Quantity::ZERO,
account_id: "main".into(),
trace: None,
policy: None,
exact_amounts: Some(ExactOrderAmounts {
quantity: ExactDecimal::parse("1000.0000000001").unwrap(),
limit_price: None,
filled: ExactDecimal::ZERO,
market_reference_price: None,
quote_budget: None,
quote_filled: Default::default(),
conditional: None,
}),
};
assert!(order.validate().is_err());
order.qty = Quantity::ZERO;
order.validate().unwrap();
let mut fill = Fill {
order_id: 3,
exact_amounts: Some(ExactFillAmounts {
quantity: ExactDecimal::ZERO,
price: ExactDecimal::parse("0.00000001").unwrap(),
quote_cost: None,
quote_budget_complete: false,
}),
..Fill::default()
};
assert!(fill.validate_exact_amounts().is_err());
fill.exact_amounts.as_mut().unwrap().quantity =
ExactDecimal::parse("0.0000000001").unwrap();
fill.validate_exact_amounts().unwrap();
}
#[test]
fn order_wire_rejects_unknown_fields_and_keeps_legacy_optional_fields_readable() {
let policy = OrderPolicy {
reduce_only: false,
position_side: crate::PositionSide::Net,
margin_mode: crate::MarginMode::Cross,
position_mode: crate::PositionMode::OneWay,
leverage: 3,
post_only: false,
};
let order = Order {
client_id: 9,
instrument: InstrumentId::parse("BTCUSDT.BINANCE").unwrap(),
side: Side::Buy,
qty: Quantity::from_i64(1),
limit: None,
status: OrderStatus::PendingSubmit,
filled: Quantity::ZERO,
account_id: "main".into(),
trace: None,
policy: Some(policy),
exact_amounts: None,
};
let mut misspelled_policy = serde_json::to_value(&order).unwrap();
let object = misspelled_policy.as_object_mut().unwrap();
let policy = object.remove("policy").unwrap();
object.insert("polciy".into(), policy);
assert!(serde_json::from_value::<Order>(misspelled_policy).is_err());
let mut misspelled_policy_field = serde_json::to_value(&order).unwrap();
misspelled_policy_field["policy"]["post_onli"] = serde_json::Value::Bool(true);
assert!(serde_json::from_value::<Order>(misspelled_policy_field).is_err());
let mut legacy = serde_json::to_value(Order {
policy: None,
..order
})
.unwrap();
let object = legacy.as_object_mut().unwrap();
object.remove("policy");
object.remove("exact_amounts");
let decoded: Order = serde_json::from_value(legacy).unwrap();
assert!(decoded.policy.is_none());
assert!(decoded.exact_amounts.is_none());
}
}