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