Skip to main content

qx_core/
trading.rs

1//! 统一交易产品、杠杆和保证金语义。
2//!
3//! 这里不依赖交易所;现货、保证金、永续和交割合约都通过同一组确定性
4//! 定点运算表达。CCXT 只负责把交易所 market/position/funding 映射到这些
5//! 契约,回测和实盘不得各自重新实现一套保证金规则。
6
7use crate::numeric::{DecimalRounding, ExactDecimal};
8use crate::{InstrumentId, Money, QxError, QxResult, DEFAULT_SETTLEMENT_CURRENCY, SCALE};
9use serde::{Deserialize, Serialize};
10
11#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum TradingProduct {
14    Spot,
15    Margin,
16    Perpetual,
17    Future,
18    /// 期权(规划 §15.1 的产品类型表把 `option` 单列一格)。
19    ///
20    /// 刻意**不**计入 [`TradingProduct::is_derivative`]:衍生品那条分支要求 `linear`/`inverse`
21    /// 恰好指定一个,而期权两者都为 false 才是对的(权利金对标的线性程度不是合约的
22    /// 线性/反向属性)。期权合约身份里真正缺的那几格(行权价、到期日、认购/认沽、行权方式)
23    /// 尚未建模,见 `maturity/capabilities.yaml` 的 `option_contract_identity_is_not_modelled`。
24    Option,
25}
26
27impl TradingProduct {
28    pub fn is_derivative(self) -> bool {
29        matches!(self, Self::Perpetual | Self::Future)
30    }
31
32    pub fn supports_leverage(self) -> bool {
33        !matches!(self, Self::Spot)
34    }
35}
36
37#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum MarginMode {
40    Cash,
41    Cross,
42    Isolated,
43}
44
45#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
46#[serde(rename_all = "snake_case")]
47pub enum PositionMode {
48    OneWay,
49    Hedge,
50}
51
52#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum PositionSide {
55    Net,
56    Long,
57    Short,
58}
59
60#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
61pub struct ExactTradingRules {
62    /// Base units per contract, or 1 for spot. Preserved as a decimal string on the wire.
63    pub contract_size: ExactDecimal,
64    pub price_tick: ExactDecimal,
65    pub quantity_step: ExactDecimal,
66    pub minimum_quantity: ExactDecimal,
67    /// Quote-currency minimum order value; zero means the venue publishes no usable minimum.
68    pub minimum_notional: ExactDecimal,
69}
70
71#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
72pub struct TradingInstrumentSpec {
73    pub instrument: InstrumentId,
74    pub product: TradingProduct,
75    pub base_currency: String,
76    pub quote_currency: String,
77    pub settlement_currency: String,
78    /// 1.0 表示现货;合约可为 0.001 BTC/contract 或 1 USD/contract。
79    pub contract_size: i128,
80    pub linear: bool,
81    pub inverse: bool,
82    pub price_tick: i128,
83    pub qty_step: i128,
84    pub min_qty: i128,
85    /// Minimum order notional in quote-currency raw units; zero means the venue did not
86    /// publish a usable minimum. Kept optional at the JSON boundary for older frozen specs.
87    #[serde(default, skip_serializing_if = "raw_zero")]
88    pub min_notional_raw: i128,
89    pub max_leverage: u32,
90    pub maintenance_margin_bps: u32,
91    pub valid_from: u64,
92    pub valid_to: Option<u64>,
93    /// Versioned decimal venue rules. Absent on historical 1e9 specifications.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub exact_rules: Option<ExactTradingRules>,
96}
97
98/// Resolve the ledger currency for a backtest from its declared instrument spec,
99/// using the core default only when the spec is absent.
100pub fn resolve_settlement_currency(spec: Option<&TradingInstrumentSpec>) -> String {
101    spec.map(|spec| spec.settlement_currency.clone())
102        .unwrap_or_else(|| DEFAULT_SETTLEMENT_CURRENCY.into())
103}
104
105impl TradingInstrumentSpec {
106    /// Canonical spot fallback used only when a caller explicitly permits an absent market
107    /// specification. Keep the fallback definition in the domain contract so report verifiers
108    /// can reproduce the exact specification used by execution.
109    pub fn spot_default(instrument: &InstrumentId, settlement_currency: &str) -> Self {
110        let currency = settlement_currency.trim().to_ascii_uppercase();
111        Self {
112            instrument: instrument.clone(),
113            product: TradingProduct::Spot,
114            base_currency: instrument.symbol().to_owned(),
115            quote_currency: currency.clone(),
116            settlement_currency: currency,
117            contract_size: SCALE,
118            linear: false,
119            inverse: false,
120            price_tick: 1,
121            qty_step: 1,
122            min_qty: 1,
123            min_notional_raw: 0,
124            max_leverage: 1,
125            maintenance_margin_bps: 0,
126            valid_from: 0,
127            valid_to: None,
128            exact_rules: None,
129        }
130    }
131
132    /// Whether the complete inclusive timestamp span `[first, last]` fits this spec's
133    /// validity window. `valid_to` is exclusive. Callers with ordered data can validate the
134    /// entire series from its endpoints in constant time.
135    pub fn covers_timestamp_range(&self, first: u64, last: u64) -> bool {
136        first <= last
137            && first >= self.valid_from
138            && self.valid_to.is_none_or(|valid_to| last < valid_to)
139    }
140
141    pub fn validate(&self) -> QxResult<()> {
142        if self.base_currency.trim().is_empty()
143            || self.quote_currency.trim().is_empty()
144            || self.settlement_currency.trim().is_empty()
145            || self.contract_size <= 0
146            || self.exact_rules.is_none()
147                && (self.price_tick <= 0 || self.qty_step <= 0 || self.min_qty <= 0)
148            || self.min_notional_raw < 0
149            || self.price_tick < 0
150            || self.qty_step < 0
151            || self.min_qty < 0
152            || self.max_leverage == 0
153            || self.maintenance_margin_bps > 10_000
154            || self.valid_to.is_some_and(|to| to <= self.valid_from)
155            || (self.linear == self.inverse && self.product.is_derivative())
156            || self.exact_rules.as_ref().is_some_and(|rules| {
157                !rules.contract_size.is_positive()
158                    || !rules.price_tick.is_positive()
159                    || !rules.quantity_step.is_positive()
160                    || !rules.minimum_quantity.is_positive()
161                    || rules.minimum_notional.is_negative()
162            })
163        {
164            return Err(QxError::BusinessViolation(
165                "TradingInstrumentSpec 字段非法或 linear/inverse 未唯一指定".into(),
166            ));
167        }
168        if self.product == TradingProduct::Spot
169            && (self.max_leverage != 1 || self.margin_mode_default() != MarginMode::Cash)
170        {
171            return Err(QxError::BusinessViolation(
172                "现货产品默认只能使用 Cash、1 倍杠杆".into(),
173            ));
174        }
175        Ok(())
176    }
177
178    pub fn margin_mode_default(&self) -> MarginMode {
179        if self.product == TradingProduct::Spot {
180            MarginMode::Cash
181        } else {
182            MarginMode::Cross
183        }
184    }
185
186    /// 返回结算币种定点原始值的名义额。
187    pub fn notional(&self, qty: i128, price: i128) -> QxResult<i128> {
188        if qty < 0 || price <= 0 || self.contract_size <= 0 {
189            return Err(QxError::BusinessViolation("名义额输入非法".into()));
190        }
191        self.notional_exact(raw_decimal(qty), raw_decimal(price))?
192            .checked_mul_at_scale(exact_one(), 9, DecimalRounding::AwayFromZero)
193            .ok_or_else(|| QxError::Invariant("名义额计算溢出".into()))?
194            .to_raw(9)
195            .map_err(|error| QxError::Invariant(error.into()))
196    }
197
198    /// Venue order-cost amount in quote-currency raw units. Inverse contracts quote their
199    /// fixed contract value directly; linear products multiply base quantity by price.
200    pub fn quote_notional(&self, qty: i128, price: i128) -> QxResult<i128> {
201        if qty < 0 || price <= 0 || self.contract_size <= 0 {
202            return Err(QxError::BusinessViolation("订单名义金额输入非法".into()));
203        }
204        self.quote_notional_exact(raw_decimal(qty), raw_decimal(price))?
205            .checked_mul_at_scale(exact_one(), 9, DecimalRounding::TowardZero)
206            .ok_or_else(|| QxError::Invariant("订单名义金额计算溢出".into()))?
207            .to_raw(9)
208            .map_err(|error| QxError::Invariant(error.into()))
209    }
210
211    pub fn initial_margin(&self, qty: i128, price: i128, leverage: u32) -> QxResult<i128> {
212        if leverage == 0 || leverage > self.max_leverage {
213            return Err(QxError::BusinessViolation("杠杆超出产品限制".into()));
214        }
215        if !self.product.supports_leverage() && leverage != 1 {
216            return Err(QxError::BusinessViolation(
217                "现货不能使用大于 1 的杠杆".into(),
218            ));
219        }
220        let notional = raw_decimal(self.notional(qty, price)?);
221        let leverage = ExactDecimal::from_parts(i128::from(leverage), 0)
222            .map_err(|error| QxError::Invariant(error.into()))?;
223        notional
224            .checked_div_at_scale(leverage, 9, DecimalRounding::AwayFromZero)
225            .and_then(|value| value.to_raw(9).ok())
226            .ok_or_else(|| QxError::Invariant("初始保证金计算溢出".into()))
227    }
228
229    /// Exact initial margin for high-precision order and account risk paths. Notional is
230    /// rounded upward before division, and the resulting required margin is rounded upward
231    /// again so a sub-nano amount cannot be understated at either step.
232    pub fn initial_margin_exact(
233        &self,
234        quantity: ExactDecimal,
235        price: ExactDecimal,
236        leverage: u32,
237    ) -> QxResult<ExactDecimal> {
238        if leverage == 0 || leverage > self.max_leverage {
239            return Err(QxError::BusinessViolation("杠杆超出产品限制".into()));
240        }
241        if !self.product.supports_leverage() && leverage != 1 {
242            return Err(QxError::BusinessViolation(
243                "现货不能使用大于 1 的杠杆".into(),
244            ));
245        }
246        let notional = self.notional_exact(quantity, price)?;
247        let leverage = ExactDecimal::from_parts(i128::from(leverage), 0)
248            .map_err(|error| QxError::Invariant(error.into()))?;
249        notional
250            .checked_div_at_scale(
251                leverage,
252                ExactDecimal::MAX_SCALE,
253                DecimalRounding::AwayFromZero,
254            )
255            .ok_or_else(|| QxError::Invariant("精确初始保证金计算溢出".into()))
256    }
257
258    /// 在进入 OMS/交易所适配器前校验数量和价格的交易所规格约束。
259    ///
260    /// 这里不做静默截断或四舍五入;策略目标若无法精确落在 lot/tick 上,
261    /// 必须显式调整目标或由上层按业务规则拆单,避免回测与实盘产生不同语义。
262    pub fn validate_order(&self, qty: i128, price: Option<i128>) -> QxResult<()> {
263        self.validate_order_with_reference(qty, price, price)
264    }
265
266    /// Validate a market order against an observed price without treating that reference as a
267    /// submitted limit price. This checks minimum quote cost while applying the tick rule only
268    /// to actual limit prices.
269    pub fn validate_order_with_reference(
270        &self,
271        qty: i128,
272        limit_price: Option<i128>,
273        reference_price: Option<i128>,
274    ) -> QxResult<()> {
275        if qty <= 0 {
276            return Err(QxError::BusinessViolation("订单数量必须为正数".into()));
277        }
278        self.validate_exact_order_with_reference(
279            raw_decimal(qty),
280            limit_price.map(raw_decimal),
281            reference_price.map(raw_decimal),
282        )
283    }
284
285    /// Validate high-precision quantity/price values against the frozen venue rules.
286    /// Amount filters use exact decimal multiples; minimum notional is rounded down so a
287    /// value below the exchange floor cannot pass due to local rounding.
288    pub fn validate_exact_order_with_reference(
289        &self,
290        quantity: ExactDecimal,
291        limit_price: Option<ExactDecimal>,
292        reference_price: Option<ExactDecimal>,
293    ) -> QxResult<()> {
294        self.validate_exact_order_precision(quantity, limit_price)?;
295        let (_, _, _, minimum_notional) = self.exact_rule_values();
296        if minimum_notional.is_positive() {
297            let reference_price = reference_price.ok_or_else(|| {
298                QxError::BusinessViolation("缺少可核验参考价,无法校验交易所最小名义金额".into())
299            })?;
300            let quote_notional = self.quote_notional_exact(quantity, reference_price)?;
301            if !reference_price.is_positive()
302                || quote_notional.checked_cmp(minimum_notional) == Some(std::cmp::Ordering::Less)
303            {
304                return Err(QxError::BusinessViolation(
305                    "订单名义金额低于交易所最小限制".into(),
306                ));
307            }
308        }
309        Ok(())
310    }
311
312    /// Validate exact lot/tick/minimum quantity rules without a market-order reference price.
313    /// The execution boundary uses this before risk evaluation; risk and the venue adapter then
314    /// check notional using their fresh reference price.
315    pub fn validate_exact_order_precision(
316        &self,
317        quantity: ExactDecimal,
318        limit_price: Option<ExactDecimal>,
319    ) -> QxResult<()> {
320        let (minimum_quantity, quantity_step, price_tick, _) = self.exact_rule_values();
321        if !quantity.is_positive()
322            || quantity
323                .checked_cmp(minimum_quantity)
324                .is_none_or(|ordering| ordering.is_lt())
325            || quantity.is_multiple_of(quantity_step) != Some(true)
326        {
327            return Err(QxError::BusinessViolation(
328                "订单数量不满足最小数量或数量步长".into(),
329            ));
330        }
331        if let Some(price) = limit_price {
332            if !price.is_positive() || price.is_multiple_of(price_tick) != Some(true) {
333                return Err(QxError::BusinessViolation(
334                    "订单价格不满足正数或价格 tick".into(),
335                ));
336            }
337        }
338        Ok(())
339    }
340
341    /// Validate a quote-currency-sized Spot market buy. This path has no base quantity or
342    /// limit price to pass through the ordinary lot/tick validator; its exact budget is the
343    /// order notional and must satisfy the frozen quote-currency minimum.
344    pub fn validate_exact_quote_budget(&self, budget: ExactDecimal) -> QxResult<()> {
345        self.validate()?;
346        if self.product != TradingProduct::Spot || !budget.is_positive() {
347            return Err(QxError::BusinessViolation(
348                "计价币预算只支持正数现货订单".into(),
349            ));
350        }
351        let raw_minimum = ExactDecimal::from_parts(self.min_notional_raw, 9)
352            .map_err(|error| QxError::Invariant(error.into()))?;
353        let exact_minimum = self
354            .exact_rules
355            .as_ref()
356            .map(|rules| rules.minimum_notional)
357            .unwrap_or(ExactDecimal::ZERO);
358        let minimum = if exact_minimum
359            .checked_cmp(raw_minimum)
360            .is_some_and(|ordering| ordering.is_gt())
361        {
362            exact_minimum
363        } else {
364            raw_minimum
365        };
366        if budget
367            .checked_cmp(minimum)
368            .is_some_and(|ordering| ordering.is_lt())
369        {
370            return Err(QxError::BusinessViolation(
371                "订单名义金额低于交易所最小限制".into(),
372            ));
373        }
374        Ok(())
375    }
376
377    /// Convert a remaining quote-currency budget into the largest base quantity that fits
378    /// the frozen quantity step at `price`. This is a sizing helper, not a substitute for
379    /// validating the original quote budget or the resulting fill.
380    pub fn base_quantity_for_quote_budget(
381        &self,
382        budget: ExactDecimal,
383        price: ExactDecimal,
384    ) -> QxResult<ExactDecimal> {
385        self.validate()?;
386        if self.product != TradingProduct::Spot || !budget.is_positive() || !price.is_positive() {
387            return Err(QxError::BusinessViolation(
388                "计价币预算换算要求正数现货预算和价格".into(),
389            ));
390        }
391        let contract_size = self.contract_size_decimal();
392        let quote_per_quantity = price
393            .checked_mul_at_scale(
394                contract_size,
395                ExactDecimal::MAX_SCALE,
396                DecimalRounding::AwayFromZero,
397            )
398            .filter(|value| value.is_positive())
399            .ok_or_else(|| QxError::Invariant("计价币预算单位成本计算失败".into()))?;
400        let unrounded_quantity = budget
401            .checked_div_at_scale(
402                quote_per_quantity,
403                ExactDecimal::MAX_SCALE,
404                DecimalRounding::Floor,
405            )
406            .ok_or_else(|| QxError::Invariant("计价币预算基础币数量换算失败".into()))?;
407        self.floor_exact_quantity_to_step(unrounded_quantity)
408    }
409
410    /// Round a non-negative exact quantity down to this instrument's frozen quantity step.
411    pub fn floor_exact_quantity_to_step(&self, quantity: ExactDecimal) -> QxResult<ExactDecimal> {
412        self.validate()?;
413        if quantity.is_negative() {
414            return Err(QxError::BusinessViolation(
415                "数量步进取整不能接收负数".into(),
416            ));
417        }
418        let quantity_step = self.exact_rule_values().1;
419        let step_count = quantity
420            .checked_div_at_scale(quantity_step, 0, DecimalRounding::Floor)
421            .ok_or_else(|| QxError::Invariant("数量步进计数计算失败".into()))?;
422        step_count
423            .checked_mul_at_scale(
424                quantity_step,
425                ExactDecimal::MAX_SCALE,
426                DecimalRounding::TowardZero,
427            )
428            .ok_or_else(|| QxError::Invariant("数量步进取整溢出".into()))
429    }
430
431    pub fn quantity_step_exact(&self) -> QxResult<ExactDecimal> {
432        self.validate()?;
433        Ok(self.exact_rule_values().1)
434    }
435
436    /// Quote-currency order value at a declared 18-place arithmetic scale, rounded down.
437    pub fn quote_notional_exact(
438        &self,
439        quantity: ExactDecimal,
440        price: ExactDecimal,
441    ) -> QxResult<ExactDecimal> {
442        self.quote_cash_exact(quantity, price, DecimalRounding::TowardZero)
443    }
444
445    /// Quote-currency cash flow at the declared exact scale. The caller chooses a conservative
446    /// rounding direction: round a buy debit away from zero and a sell credit toward zero.
447    pub fn quote_cash_exact(
448        &self,
449        quantity: ExactDecimal,
450        price: ExactDecimal,
451        rounding: DecimalRounding,
452    ) -> QxResult<ExactDecimal> {
453        if quantity.is_negative() || !price.is_positive() {
454            return Err(QxError::BusinessViolation("订单名义金额输入非法".into()));
455        }
456        let contract_size = self.contract_size_decimal();
457        let amount = quantity
458            .checked_mul_at_scale(contract_size, ExactDecimal::MAX_SCALE, rounding)
459            .ok_or_else(|| QxError::Invariant("订单合约乘数计算溢出".into()))?;
460        if self.inverse {
461            Ok(amount)
462        } else {
463            amount
464                .checked_mul_at_scale(price, ExactDecimal::MAX_SCALE, rounding)
465                .ok_or_else(|| QxError::Invariant("订单报价名义金额计算溢出".into()))
466        }
467    }
468
469    /// Settlement-currency exposure using exact quantity, price, and contract size.
470    /// Positive exposure is rounded up so a limit check cannot understate risk.
471    pub fn notional_exact(
472        &self,
473        quantity: ExactDecimal,
474        price: ExactDecimal,
475    ) -> QxResult<ExactDecimal> {
476        if quantity.is_negative() || !price.is_positive() {
477            return Err(QxError::BusinessViolation("名义额输入非法".into()));
478        }
479        let amount = quantity
480            .checked_mul_at_scale(
481                self.contract_size_decimal(),
482                ExactDecimal::MAX_SCALE,
483                DecimalRounding::AwayFromZero,
484            )
485            .ok_or_else(|| QxError::Invariant("名义额乘数计算溢出".into()))?;
486        let result = if self.inverse {
487            amount.checked_div_at_scale(
488                price,
489                ExactDecimal::MAX_SCALE,
490                DecimalRounding::AwayFromZero,
491            )
492        } else {
493            amount.checked_mul_at_scale(
494                price,
495                ExactDecimal::MAX_SCALE,
496                DecimalRounding::AwayFromZero,
497            )
498        };
499        result.ok_or_else(|| QxError::Invariant("名义额计算溢出".into()))
500    }
501
502    fn contract_size_decimal(&self) -> ExactDecimal {
503        self.exact_rules
504            .as_ref()
505            .map(|rules| rules.contract_size)
506            .unwrap_or_else(|| raw_decimal(self.contract_size))
507    }
508
509    fn exact_rule_values(&self) -> (ExactDecimal, ExactDecimal, ExactDecimal, ExactDecimal) {
510        self.exact_rules.as_ref().map_or_else(
511            || {
512                (
513                    raw_decimal(self.min_qty),
514                    raw_decimal(self.qty_step),
515                    raw_decimal(self.price_tick),
516                    raw_decimal(self.min_notional_raw),
517                )
518            },
519            |rules| {
520                (
521                    rules.minimum_quantity,
522                    rules.quantity_step,
523                    rules.price_tick,
524                    rules.minimum_notional,
525                )
526            },
527        )
528    }
529
530    /// 校验交易所成交回报的精度约束(tick/step 对齐)。
531    ///
532    /// 与 `validate_order` 的差别是刻意的:`min_qty` 只约束下单数量,一笔合规订单可以被
533    /// 拆成多笔小于最小下单量的成交,因此回报侧不套用该下限;落在 tick/step 之外的回报
534    /// 意味着事实与冻结产品规格冲突,上层必须按未知结果处理而不是静默记账或截断。
535    pub fn validate_fill(&self, qty: i128, price: i128) -> QxResult<()> {
536        if qty <= 0 {
537            return Err(QxError::BusinessViolation("成交数量必须为正数".into()));
538        }
539        self.validate_exact_fill(raw_decimal(qty), raw_decimal(price))
540    }
541
542    /// Validate exchange execution values at their original decimal precision. Fill quantity
543    /// is checked against the lot step but not the order minimum, since one accepted order can
544    /// produce multiple smaller partial fills.
545    pub fn validate_exact_fill(&self, quantity: ExactDecimal, price: ExactDecimal) -> QxResult<()> {
546        let (_, quantity_step, price_tick, _) = self.exact_rule_values();
547        if !quantity.is_positive() || quantity.is_multiple_of(quantity_step) != Some(true) {
548            return Err(QxError::BusinessViolation(
549                "成交数量不是正数或不在数量步长上".into(),
550            ));
551        }
552        if !price.is_positive() || price.is_multiple_of(price_tick) != Some(true) {
553            return Err(QxError::BusinessViolation(
554                "成交价格不是正数或不在价格 tick 上".into(),
555            ));
556        }
557        Ok(())
558    }
559
560    pub fn maintenance_margin(&self, qty: i128, price: i128) -> QxResult<i128> {
561        let notional = raw_decimal(self.notional(qty, price)?);
562        let rate = ExactDecimal::from_parts(i128::from(self.maintenance_margin_bps), 0)
563            .map_err(|error| QxError::Invariant(error.into()))?;
564        let basis_points = ExactDecimal::from_parts(10_000, 0)
565            .map_err(|error| QxError::Invariant(error.into()))?;
566        notional
567            .checked_mul_at_scale(rate, 9, DecimalRounding::AwayFromZero)
568            .and_then(|value| {
569                value.checked_div_at_scale(basis_points, 9, DecimalRounding::AwayFromZero)
570            })
571            .and_then(|value| value.to_raw(9).ok())
572            .ok_or_else(|| QxError::Invariant("维持保证金计算溢出".into()))
573    }
574
575    /// 线性合约按价格差计算,反向合约按 1/price 计算;qty 可为负表示空头。
576    pub fn unrealized_pnl(&self, qty: i128, entry_price: i128, mark_price: i128) -> QxResult<i128> {
577        if entry_price <= 0 || mark_price <= 0 {
578            return Err(QxError::BusinessViolation("PnL 价格必须为正".into()));
579        }
580        let quantity = raw_decimal(qty);
581        let contract_size = raw_decimal(self.contract_size);
582        let entry = raw_decimal(entry_price);
583        let mark = raw_decimal(mark_price);
584        let delta = mark
585            .checked_sub(entry)
586            .ok_or_else(|| QxError::Invariant("价格差计算溢出".into()))?;
587        let value = if self.inverse {
588            let denominator = entry.checked_mul_at_scale(
589                mark,
590                ExactDecimal::MAX_SCALE,
591                DecimalRounding::TowardZero,
592            );
593            quantity
594                .checked_mul_at_scale(
595                    contract_size,
596                    ExactDecimal::MAX_SCALE,
597                    DecimalRounding::TowardZero,
598                )
599                .and_then(|contracts| {
600                    contracts.checked_mul_at_scale(
601                        delta,
602                        ExactDecimal::MAX_SCALE,
603                        DecimalRounding::Floor,
604                    )
605                })
606                .and_then(|numerator| {
607                    numerator.checked_div_at_scale(denominator?, 9, DecimalRounding::Floor)
608                })
609        } else {
610            quantity
611                .checked_mul_at_scale(
612                    contract_size,
613                    ExactDecimal::MAX_SCALE,
614                    DecimalRounding::TowardZero,
615                )
616                .and_then(|contracts| {
617                    contracts.checked_mul_at_scale(delta, 9, DecimalRounding::Floor)
618                })
619        };
620        value
621            .and_then(|value| value.to_raw(9).ok())
622            .ok_or_else(|| QxError::Invariant("未实现 PnL 计算溢出".into()))
623    }
624
625    /// Compute derivative PnL in settlement currency without projecting quantity or prices
626    /// onto the legacy 1e-9 grid. A signed quantity is positive for a long and negative for a
627    /// short. Positive PnL rounds down and losses round toward negative infinity so accounting
628    /// never overstates gains or understates losses.
629    pub fn unrealized_pnl_exact(
630        &self,
631        signed_quantity: ExactDecimal,
632        entry_price: ExactDecimal,
633        mark_price: ExactDecimal,
634    ) -> QxResult<ExactDecimal> {
635        if signed_quantity.is_zero() || !entry_price.is_positive() || !mark_price.is_positive() {
636            return Err(QxError::BusinessViolation("精确衍生品 PnL 输入非法".into()));
637        }
638        let contract_size = self.contract_size_decimal();
639        let price_delta = mark_price
640            .checked_sub(entry_price)
641            .ok_or_else(|| QxError::Invariant("精确 PnL 价格差溢出".into()))?;
642        let result = if self.inverse {
643            let numerator = signed_quantity
644                .checked_mul_at_scale(
645                    contract_size,
646                    ExactDecimal::MAX_SCALE,
647                    DecimalRounding::HalfEven,
648                )
649                .and_then(|value| {
650                    value.checked_mul_at_scale(
651                        price_delta,
652                        ExactDecimal::MAX_SCALE,
653                        DecimalRounding::Floor,
654                    )
655                })
656                .ok_or_else(|| QxError::Invariant("精确反向合约 PnL 分子溢出".into()))?;
657            let denominator = entry_price
658                .checked_mul_at_scale(
659                    mark_price,
660                    ExactDecimal::MAX_SCALE,
661                    DecimalRounding::TowardZero,
662                )
663                .ok_or_else(|| QxError::Invariant("精确反向合约 PnL 分母溢出".into()))?;
664            result_at_scale_floor(numerator, denominator)?
665        } else {
666            signed_quantity
667                .checked_mul_at_scale(
668                    contract_size,
669                    ExactDecimal::MAX_SCALE,
670                    DecimalRounding::HalfEven,
671                )
672                .and_then(|contracts| {
673                    contracts.checked_mul_at_scale(
674                        price_delta,
675                        ExactDecimal::MAX_SCALE,
676                        DecimalRounding::Floor,
677                    )
678                })
679                .ok_or_else(|| QxError::Invariant("精确线性合约 PnL 溢出".into()))?
680        };
681        Ok(result)
682    }
683
684    pub fn funding_payment(
685        &self,
686        qty: i128,
687        mark_price: i128,
688        funding_rate_bps: i64,
689    ) -> QxResult<i128> {
690        if mark_price <= 0 {
691            return Err(QxError::BusinessViolation("资金费标记价格必须为正".into()));
692        }
693        let notional = raw_decimal(
694            self.notional(
695                qty.checked_abs()
696                    .ok_or_else(|| QxError::BusinessViolation("资金费数量绝对值溢出".into()))?,
697                mark_price,
698            )?,
699        );
700        let rate = ExactDecimal::from_parts(i128::from(funding_rate_bps), 0)
701            .map_err(|error| QxError::Invariant(error.into()))?;
702        let basis_points = ExactDecimal::from_parts(10_000, 0)
703            .map_err(|error| QxError::Invariant(error.into()))?;
704        let amount = notional
705            .checked_mul_at_scale(rate, 9, DecimalRounding::TowardZero)
706            .and_then(|value| {
707                value.checked_div_at_scale(basis_points, 9, DecimalRounding::TowardZero)
708            })
709            .ok_or_else(|| QxError::Invariant("资金费计算溢出".into()))?;
710        let amount = if qty < 0 {
711            ExactDecimal::ZERO
712                .checked_sub(amount)
713                .ok_or_else(|| QxError::Invariant("资金费方向计算溢出".into()))?
714        } else {
715            amount
716        };
717        amount
718            .to_raw(9)
719            .map_err(|_| QxError::Invariant("资金费计算溢出".into()))
720    }
721
722    /// Scale-aware funding amount before applying the cashflow sign. Positive values mean
723    /// the position pays the venue when the rate is positive; negative quantities reverse
724    /// that direction. This keeps sub-1e-9 quantities and prices intact for small contracts.
725    pub fn funding_payment_exact(
726        &self,
727        signed_quantity: ExactDecimal,
728        mark_price: ExactDecimal,
729        funding_rate_bps: i64,
730    ) -> QxResult<ExactDecimal> {
731        if !self.product.is_derivative() || signed_quantity.is_zero() || !mark_price.is_positive() {
732            return Err(QxError::BusinessViolation(
733                "精确资金费要求非零衍生品持仓和正标记价".into(),
734            ));
735        }
736        let quantity = ExactDecimal::from_parts(
737            signed_quantity
738                .coefficient()
739                .checked_abs()
740                .ok_or_else(|| QxError::BusinessViolation("精确资金费数量绝对值溢出".into()))?,
741            signed_quantity.scale(),
742        )
743        .map_err(|error| QxError::Invariant(error.into()))?;
744        let notional = self.notional_exact(quantity, mark_price)?;
745        let rate = ExactDecimal::from_parts(i128::from(funding_rate_bps), 0)
746            .map_err(|error| QxError::Invariant(error.into()))?;
747        let basis_points = ExactDecimal::from_parts(10_000, 0)
748            .map_err(|error| QxError::Invariant(error.into()))?;
749        let amount = notional
750            .checked_mul_at_scale(rate, ExactDecimal::MAX_SCALE, DecimalRounding::TowardZero)
751            .and_then(|value| {
752                value.checked_div_at_scale(
753                    basis_points,
754                    ExactDecimal::MAX_SCALE,
755                    DecimalRounding::TowardZero,
756                )
757            })
758            .ok_or_else(|| QxError::Invariant("精确资金费计算溢出".into()))?;
759        if signed_quantity.is_negative() {
760            ExactDecimal::ZERO
761                .checked_sub(amount)
762                .ok_or_else(|| QxError::Invariant("精确资金费方向计算溢出".into()))
763        } else {
764            Ok(amount)
765        }
766    }
767}
768
769fn raw_decimal(value: i128) -> ExactDecimal {
770    ExactDecimal::from_legacy_raw(value)
771}
772
773fn result_at_scale_floor(
774    numerator: ExactDecimal,
775    denominator: ExactDecimal,
776) -> QxResult<ExactDecimal> {
777    numerator
778        .checked_div_at_scale(denominator, ExactDecimal::MAX_SCALE, DecimalRounding::Floor)
779        .ok_or_else(|| QxError::Invariant("精确反向合约 PnL 除法溢出".into()))
780}
781
782fn exact_one() -> ExactDecimal {
783    ExactDecimal::ONE
784}
785
786fn raw_zero(value: &i128) -> bool {
787    *value == 0
788}
789
790#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
791#[serde(deny_unknown_fields)]
792pub struct OrderPolicy {
793    pub reduce_only: bool,
794    pub position_side: PositionSide,
795    pub margin_mode: MarginMode,
796    pub position_mode: PositionMode,
797    pub leverage: u32,
798    pub post_only: bool,
799}
800
801impl Default for OrderPolicy {
802    fn default() -> Self {
803        Self {
804            reduce_only: false,
805            position_side: PositionSide::Net,
806            margin_mode: MarginMode::Cash,
807            position_mode: PositionMode::OneWay,
808            leverage: 1,
809            post_only: false,
810        }
811    }
812}
813
814impl OrderPolicy {
815    pub fn validate_for(&self, spec: &TradingInstrumentSpec) -> QxResult<()> {
816        spec.validate()?;
817        if self.leverage == 0 || self.leverage > spec.max_leverage {
818            return Err(QxError::BusinessViolation(
819                "OrderPolicy 杠杆超出产品限制".into(),
820            ));
821        }
822        if !spec.product.supports_leverage()
823            && (self.leverage != 1 || self.margin_mode != MarginMode::Cash)
824        {
825            return Err(QxError::BusinessViolation(
826                "现货 OrderPolicy 只能为 Cash/1x".into(),
827            ));
828        }
829        if self.position_mode == PositionMode::OneWay && self.position_side != PositionSide::Net {
830            return Err(QxError::BusinessViolation(
831                "OneWay 模式 position_side 必须为 Net".into(),
832            ));
833        }
834        if self.position_mode == PositionMode::Hedge && !spec.product.is_derivative() {
835            return Err(QxError::BusinessViolation(
836                "Hedge 持仓模式仅支持永续或交割合约".into(),
837            ));
838        }
839        if self.position_mode == PositionMode::Hedge && self.position_side == PositionSide::Net {
840            return Err(QxError::BusinessViolation(
841                "Hedge 模式 position_side 必须为 Long 或 Short".into(),
842            ));
843        }
844        Ok(())
845    }
846}
847
848#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
849pub struct MarginState {
850    pub collateral: Money,
851    pub unrealized_pnl: Money,
852    pub funding: Money,
853    pub interest: Money,
854    pub initial_margin: Money,
855    pub maintenance_margin: Money,
856}
857
858impl MarginState {
859    /// 权益 = 抵押 + 未实现 − 资金费 − 利息。
860    ///
861    /// 算式单源在 [`MarginState::valuate`](P1-6 估值单点),这里只取结果的 `equity` 字段。
862    /// `MarginState` 本身不带币种,故传空串。
863    pub fn equity(self) -> Option<Money> {
864        self.valuate(String::new()).map(|result| result.equity)
865    }
866
867    /// 可用保证金 = 权益 − 初始保证金(同样走 [`MarginState::valuate`] 的 `available` 字段)。
868    pub fn available(self) -> Option<Money> {
869        self.valuate(String::new()).map(|result| result.available)
870    }
871}
872
873#[cfg(test)]
874mod tests {
875    use super::*;
876
877    fn spec(product: TradingProduct) -> TradingInstrumentSpec {
878        TradingInstrumentSpec {
879            instrument: InstrumentId::parse("BTC/USDT:USDT.BYBIT").unwrap(),
880            product,
881            base_currency: "BTC".into(),
882            quote_currency: "USDT".into(),
883            settlement_currency: "USDT".into(),
884            contract_size: SCALE,
885            linear: product != TradingProduct::Spot,
886            inverse: false,
887            price_tick: 1,
888            qty_step: 1,
889            min_qty: 1,
890            min_notional_raw: 0,
891            max_leverage: if product == TradingProduct::Spot {
892                1
893            } else {
894                100
895            },
896            maintenance_margin_bps: 500,
897            valid_from: 1,
898            valid_to: None,
899            exact_rules: None,
900        }
901    }
902
903    #[test]
904    fn settlement_currency_comes_from_the_spec_or_the_core_default() {
905        assert_eq!(
906            resolve_settlement_currency(None),
907            DEFAULT_SETTLEMENT_CURRENCY
908        );
909        let mut market = spec(TradingProduct::Spot);
910        market.settlement_currency = "CNY".into();
911        assert_eq!(resolve_settlement_currency(Some(&market)), "CNY");
912    }
913
914    #[test]
915    fn market_spec_covers_timestamp_range_with_half_open_validity() {
916        let mut market = spec(TradingProduct::Spot);
917        market.valid_from = 10;
918        market.valid_to = Some(20);
919
920        assert!(market.covers_timestamp_range(10, 19));
921        assert!(!market.covers_timestamp_range(9, 19));
922        assert!(!market.covers_timestamp_range(10, 20));
923        assert!(!market.covers_timestamp_range(20, 20));
924        assert!(!market.covers_timestamp_range(12, 11));
925    }
926
927    #[test]
928    fn linear_contract_margin_pnl_and_funding_are_deterministic() {
929        let spec = spec(TradingProduct::Perpetual);
930        assert!(spec.validate().is_ok());
931        assert_eq!(spec.notional(SCALE, 100 * SCALE).unwrap(), 100 * SCALE);
932        assert_eq!(
933            spec.initial_margin(SCALE, 100 * SCALE, 10).unwrap(),
934            10 * SCALE
935        );
936        assert_eq!(
937            spec.maintenance_margin(SCALE, 100 * SCALE).unwrap(),
938            5 * SCALE
939        );
940        assert_eq!(
941            spec.unrealized_pnl(SCALE, 100 * SCALE, 110 * SCALE)
942                .unwrap(),
943            10 * SCALE
944        );
945        assert_eq!(
946            spec.funding_payment(SCALE, 100 * SCALE, 10).unwrap(),
947            100_000_000
948        );
949    }
950
951    #[test]
952    fn exact_funding_payment_preserves_sub_nano_exposure_and_short_direction() {
953        let spec = spec(TradingProduct::Perpetual);
954        let quantity = ExactDecimal::parse("0.000000000001").unwrap();
955        let mark = ExactDecimal::parse("100").unwrap();
956        let expected = ExactDecimal::parse("0.000000000001").unwrap();
957        assert_eq!(
958            spec.funding_payment_exact(quantity, mark, 100).unwrap(),
959            expected
960        );
961        assert_eq!(
962            spec.funding_payment_exact(quantity.checked_neg().unwrap(), mark, 100)
963                .unwrap(),
964            expected.checked_neg().unwrap()
965        );
966        assert_eq!(
967            spec.funding_payment_exact(quantity, mark, -100).unwrap(),
968            expected.checked_neg().unwrap()
969        );
970        assert_eq!(
971            spec.funding_payment_exact(quantity.checked_neg().unwrap(), mark, -100)
972                .unwrap(),
973            expected
974        );
975        let mut inverse = spec;
976        inverse.linear = false;
977        inverse.inverse = true;
978        let inverse_payment = inverse
979            .funding_payment_exact(
980                ExactDecimal::parse("10").unwrap(),
981                ExactDecimal::parse("10000").unwrap(),
982                100,
983            )
984            .unwrap();
985        assert_eq!(inverse_payment, ExactDecimal::parse("0.00001").unwrap());
986    }
987
988    #[test]
989    fn inverse_contract_uses_settlement_currency_notional_and_pnl() {
990        let mut spec = spec(TradingProduct::Perpetual);
991        spec.instrument = InstrumentId::parse("BTC/USD:BTC.BYBIT").unwrap();
992        spec.base_currency = "BTC".into();
993        spec.quote_currency = "USD".into();
994        spec.settlement_currency = "BTC".into();
995        spec.contract_size = SCALE;
996        spec.linear = false;
997        spec.inverse = true;
998        spec.validate().unwrap();
999        let ten_contracts = 10 * SCALE;
1000        let entry = 10_000 * SCALE;
1001        let mark = 11_000 * SCALE;
1002        assert_eq!(spec.notional(ten_contracts, entry).unwrap(), SCALE / 1_000);
1003        assert_eq!(
1004            spec.unrealized_pnl(ten_contracts, entry, mark).unwrap(),
1005            90_909
1006        );
1007        assert_eq!(
1008            spec.initial_margin(ten_contracts, entry, 10).unwrap(),
1009            100_000
1010        );
1011    }
1012
1013    #[test]
1014    fn order_policy_rejects_invalid_spot_and_hedge_combinations() {
1015        let spot = spec(TradingProduct::Spot);
1016        let mut policy = OrderPolicy::default();
1017        assert!(policy.validate_for(&spot).is_ok());
1018        policy.leverage = 2;
1019        assert!(policy.validate_for(&spot).is_err());
1020
1021        let derivative = spec(TradingProduct::Perpetual);
1022        policy = OrderPolicy {
1023            position_mode: PositionMode::OneWay,
1024            position_side: PositionSide::Long,
1025            ..OrderPolicy::default()
1026        };
1027        assert!(policy.validate_for(&derivative).is_err());
1028    }
1029
1030    #[test]
1031    fn order_spec_rejects_unaligned_quantity_and_price_without_rounding() {
1032        let mut instrument = spec(TradingProduct::Perpetual);
1033        instrument.qty_step = 10;
1034        instrument.min_qty = 20;
1035        instrument.price_tick = 5;
1036        assert!(instrument.validate_order(20, Some(100)).is_ok());
1037        assert!(instrument.validate_order(19, Some(100)).is_err());
1038        assert!(instrument.validate_order(25, Some(100)).is_err());
1039        assert!(instrument.validate_order(20, Some(101)).is_err());
1040    }
1041
1042    #[test]
1043    fn exact_market_rules_validate_sub_nano_orders_and_fills() {
1044        let mut instrument = spec(TradingProduct::Spot);
1045        instrument.instrument = InstrumentId::parse("TINY/USDT.BINANCE").unwrap();
1046        instrument.base_currency = "TINY".into();
1047        instrument.exact_rules = Some(ExactTradingRules {
1048            contract_size: ExactDecimal::parse("1").unwrap(),
1049            price_tick: ExactDecimal::parse("0.0000000001").unwrap(),
1050            quantity_step: ExactDecimal::parse("0.0000000001").unwrap(),
1051            minimum_quantity: ExactDecimal::parse("0.0000000001").unwrap(),
1052            minimum_notional: ExactDecimal::ZERO,
1053        });
1054        let encoded = serde_json::to_string(&instrument).unwrap();
1055        let decoded: TradingInstrumentSpec = serde_json::from_str(&encoded).unwrap();
1056        assert_eq!(decoded, instrument);
1057
1058        let quantity = ExactDecimal::parse("0.0000000003").unwrap();
1059        let price = ExactDecimal::parse("0.0000000004").unwrap();
1060        assert!(instrument
1061            .validate_exact_order_with_reference(quantity, Some(price), Some(price))
1062            .is_ok());
1063        assert!(instrument.validate_exact_fill(quantity, price).is_ok());
1064        assert!(instrument
1065            .validate_exact_order_with_reference(
1066                ExactDecimal::parse("0.00000000031").unwrap(),
1067                Some(price),
1068                Some(price),
1069            )
1070            .is_err());
1071        assert!(instrument
1072            .validate_exact_fill(quantity, ExactDecimal::parse("0.00000000041").unwrap())
1073            .is_err());
1074        assert_eq!(
1075            instrument
1076                .notional_exact(quantity, price)
1077                .unwrap()
1078                .to_string(),
1079            "0.000000000000000001"
1080        );
1081    }
1082
1083    #[test]
1084    fn quote_budget_sizing_floors_to_lot_step_and_never_exceeds_budget() {
1085        let mut instrument = spec(TradingProduct::Spot);
1086        instrument.instrument = InstrumentId::parse("MEME/USDT.BINANCE").unwrap();
1087        instrument.base_currency = "MEME".into();
1088        instrument.exact_rules = Some(ExactTradingRules {
1089            contract_size: ExactDecimal::ONE,
1090            price_tick: ExactDecimal::parse("0.01").unwrap(),
1091            quantity_step: ExactDecimal::parse("0.003").unwrap(),
1092            minimum_quantity: ExactDecimal::parse("0.003").unwrap(),
1093            minimum_notional: ExactDecimal::ZERO,
1094        });
1095
1096        let budget = ExactDecimal::parse("10").unwrap();
1097        let price = ExactDecimal::parse("3").unwrap();
1098        let quantity = instrument
1099            .base_quantity_for_quote_budget(budget, price)
1100            .unwrap();
1101        let cost = instrument
1102            .quote_cash_exact(quantity, price, DecimalRounding::AwayFromZero)
1103            .unwrap();
1104
1105        assert_eq!(quantity, ExactDecimal::parse("3.333").unwrap());
1106        assert_eq!(cost, ExactDecimal::parse("9.999").unwrap());
1107        assert!(cost.checked_cmp(budget).unwrap().is_le());
1108        assert_eq!(
1109            instrument
1110                .floor_exact_quantity_to_step(ExactDecimal::parse("0.5").unwrap())
1111                .unwrap(),
1112            ExactDecimal::parse("0.498").unwrap()
1113        );
1114    }
1115
1116    #[test]
1117    fn low_price_spot_instrument_keeps_small_ticks_and_exact_notional() {
1118        let mut instrument = spec(TradingProduct::Spot);
1119        instrument.instrument = InstrumentId::parse("PEPE/USDT.BINANCE").unwrap();
1120        instrument.base_currency = "PEPE".into();
1121        instrument.price_tick = 10;
1122        instrument.qty_step = 1_000;
1123        instrument.min_qty = 1_000;
1124        instrument.min_notional_raw = 1_001;
1125        instrument.validate().unwrap();
1126
1127        let one_token = SCALE;
1128        let one_micro_usdt = 1_000;
1129        assert!(instrument
1130            .validate_order(one_token, Some(one_micro_usdt))
1131            .is_err());
1132        assert!(instrument
1133            .validate_order(one_token + 1_000_000, Some(one_micro_usdt))
1134            .is_ok());
1135        assert!(instrument.validate_order(one_token, None).is_err());
1136        assert!(instrument
1137            .validate_order_with_reference(one_token + 1_000_000, None, Some(1_001))
1138            .is_ok());
1139        assert_eq!(
1140            instrument.notional(one_token, one_micro_usdt).unwrap(),
1141            1_000
1142        );
1143        assert!(instrument.validate_order(one_token, Some(1_001)).is_err());
1144    }
1145
1146    #[test]
1147    fn risk_notional_rounds_up_while_minimum_quote_check_rounds_down() {
1148        let instrument = spec(TradingProduct::Perpetual);
1149        // qty and price are each one legacy raw unit, so their exact product is below
1150        // the 1e-9 reporting grid. Exposure must not be understated; minimum-cost
1151        // validation must not accept an order by rounding its cost upward.
1152        assert_eq!(instrument.notional(1, 1).unwrap(), 1);
1153        assert_eq!(instrument.quote_notional(1, 1).unwrap(), 0);
1154        assert_eq!(instrument.initial_margin(1, 1, 10).unwrap(), 1);
1155        assert_eq!(instrument.maintenance_margin(1, 1).unwrap(), 1);
1156        assert_eq!(
1157            instrument
1158                .initial_margin_exact(
1159                    ExactDecimal::parse("0.000000001").unwrap(),
1160                    ExactDecimal::parse("0.000000001").unwrap(),
1161                    10,
1162                )
1163                .unwrap(),
1164            ExactDecimal::parse("0.000000000000000001").unwrap()
1165        );
1166    }
1167
1168    #[test]
1169    fn tiny_unrealized_losses_round_away_from_equity() {
1170        let instrument = spec(TradingProduct::Perpetual);
1171        // The exact loss is 1e-18, below the 1e-9 ledger reporting unit. Floor rounding
1172        // keeps the reported equity from overstating the account by dropping that loss.
1173        assert_eq!(instrument.unrealized_pnl(-1, 1, 2).unwrap(), -1);
1174        assert_eq!(instrument.unrealized_pnl(1, 1, 2).unwrap(), 0);
1175    }
1176
1177    #[test]
1178    fn exact_derivative_pnl_uses_decimal_contract_size_for_linear_and_inverse_products() {
1179        let mut linear = spec(TradingProduct::Perpetual);
1180        linear.exact_rules = Some(ExactTradingRules {
1181            contract_size: ExactDecimal::parse("0.001").unwrap(),
1182            price_tick: ExactDecimal::parse("0.01").unwrap(),
1183            quantity_step: ExactDecimal::parse("0.1").unwrap(),
1184            minimum_quantity: ExactDecimal::parse("0.1").unwrap(),
1185            minimum_notional: ExactDecimal::ZERO,
1186        });
1187        assert_eq!(
1188            linear
1189                .unrealized_pnl_exact(
1190                    ExactDecimal::parse("0.5").unwrap(),
1191                    ExactDecimal::parse("10000").unwrap(),
1192                    ExactDecimal::parse("11000").unwrap(),
1193                )
1194                .unwrap(),
1195            ExactDecimal::parse("0.5").unwrap()
1196        );
1197        assert_eq!(
1198            linear
1199                .unrealized_pnl_exact(
1200                    ExactDecimal::parse("-0.5").unwrap(),
1201                    ExactDecimal::parse("10000").unwrap(),
1202                    ExactDecimal::parse("11000").unwrap(),
1203                )
1204                .unwrap(),
1205            ExactDecimal::parse("-0.5").unwrap()
1206        );
1207
1208        let mut inverse = spec(TradingProduct::Perpetual);
1209        inverse.settlement_currency = "BTC".into();
1210        inverse.inverse = true;
1211        inverse.linear = false;
1212        inverse.exact_rules = Some(ExactTradingRules {
1213            contract_size: ExactDecimal::parse("100").unwrap(),
1214            price_tick: ExactDecimal::parse("0.01").unwrap(),
1215            quantity_step: ExactDecimal::parse("1").unwrap(),
1216            minimum_quantity: ExactDecimal::parse("1").unwrap(),
1217            minimum_notional: ExactDecimal::ZERO,
1218        });
1219        assert_eq!(
1220            inverse
1221                .unrealized_pnl_exact(
1222                    ExactDecimal::parse("2").unwrap(),
1223                    ExactDecimal::parse("10000").unwrap(),
1224                    ExactDecimal::parse("11000").unwrap(),
1225                )
1226                .unwrap(),
1227            ExactDecimal::parse("0.001818181818181818").unwrap()
1228        );
1229    }
1230
1231    #[test]
1232    fn exact_intermediates_avoid_legacy_product_overflow_when_result_fits() {
1233        let instrument = spec(TradingProduct::Perpetual);
1234        assert_eq!(instrument.notional(i128::MAX, SCALE).unwrap(), i128::MAX);
1235        assert_eq!(
1236            instrument.quote_notional(i128::MAX, SCALE).unwrap(),
1237            i128::MAX
1238        );
1239    }
1240
1241    #[test]
1242    fn margin_state_exposes_available_and_liquidation_boundary() {
1243        let healthy = MarginState {
1244            collateral: Money::from_i64(100),
1245            initial_margin: Money::from_i64(20),
1246            maintenance_margin: Money::from_i64(30),
1247            ..MarginState::default()
1248        };
1249        assert_eq!(
1250            healthy.available().unwrap().raw(),
1251            Money::from_i64(80).raw()
1252        );
1253        assert!(healthy.equity().unwrap().raw() > healthy.maintenance_margin.raw());
1254        let mut bad = healthy;
1255        bad.unrealized_pnl = Money::from_i64(-70);
1256        assert!(bad.equity().unwrap().raw() <= bad.maintenance_margin.raw());
1257    }
1258}