Skip to main content

nautilus_derive/http/
models.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! HTTP payload models and JSON-RPC envelope types for the Derive REST API.
17//!
18//! Envelope types (`JsonRpcRequest`, `JsonRpcResponse`, `JsonRpcError`) cover
19//! the wire framing shared with the WebSocket transport. Payload structs below
20//! mirror the response shapes generated by Derive's upstream Rust SDK at
21//! [`derivexyz/cockpit`](https://github.com/derivexyz/cockpit/tree/master/orderbook-types/src/generated),
22//! adapted to project conventions:
23//!
24//! - `bigdecimal::BigDecimal` -> [`rust_decimal::Decimal`]. Required account and order
25//!   financial fields, private fill amount/price/fee, public trade amount/price,
26//!   ticker mark/index prices, candles, and funding history use strict raw-token decimal decoding;
27//!   other fields retain `deserialize_decimal` / `deserialize_optional_decimal`.
28//! - Hot-path string identifiers (`instrument_name`, `currency`) -> [`Ustr`]
29//!   for interning across decoded messages.
30//! - `uuid::Uuid` fields kept as [`String`] to avoid a fresh dep when only a
31//!   couple of methods carry one.
32
33use std::collections::HashMap;
34
35#[cfg(test)]
36use nautilus_core::string::secret::REDACTED;
37use nautilus_core::{
38    Params,
39    serialization::{
40        deserialize_decimal_token,
41        deserialize_optional_decimal_token as deserialize_optional_decimal,
42        serialize_decimal_as_str,
43    },
44    string::secret::SecretString,
45};
46use rust_decimal::Decimal;
47use serde::{Deserialize, Serialize};
48use serde_json::{Value, value::RawValue};
49use ustr::Ustr;
50
51use crate::common::{
52    enums::{
53        DeriveAssetType, DeriveInstrumentType, DeriveLiquidityRole, DeriveOptionKind,
54        DeriveOrderCancelReason, DeriveOrderSide, DeriveOrderStatus, DeriveOrderType,
55        DeriveTimeInForce, DeriveTriggerPriceType, DeriveTriggerType,
56    },
57    parse::{deserialize_decimal, deserialize_salvaged_vec, salvage_rows},
58};
59
60/// Outbound JSON-RPC request frame. Used as-is by the WebSocket transport; the
61/// REST transport addresses the method by URL path and sends only `params` on
62/// the wire, but keeps the same `id` for telemetry.
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct JsonRpcRequest<P> {
65    /// JSON-RPC version tag; constant `"2.0"`.
66    pub jsonrpc: &'static str,
67    /// Correlator chosen by the client.
68    pub id: u64,
69    /// Method name (e.g. `public/get_all_instruments`).
70    pub method: &'static str,
71    /// Method-specific params payload.
72    pub params: P,
73}
74
75impl<P> JsonRpcRequest<P> {
76    /// Constructs a `2.0` request with the given correlator, method, and params.
77    #[must_use]
78    pub fn new(id: u64, method: &'static str, params: P) -> Self {
79        Self {
80            jsonrpc: "2.0",
81            id,
82            method,
83            params,
84        }
85    }
86}
87
88/// Inbound JSON-RPC response frame. Exactly one of `result` or `error` is set
89/// by the venue.
90#[derive(Debug, Clone, Deserialize)]
91#[serde(bound(deserialize = "R: Deserialize<'de>"))]
92pub struct JsonRpcResponse<R> {
93    /// Correlator echoing the request `id`. The Derive REST API may omit this
94    /// for some endpoints, hence `Option`.
95    #[serde(default, deserialize_with = "deserialize_optional_jsonrpc_id")]
96    pub id: Option<u64>,
97    /// Result payload on success.
98    #[serde(default, deserialize_with = "deserialize_present_jsonrpc_result")]
99    pub result: Option<R>,
100    /// Error payload on failure.
101    #[serde(default)]
102    pub error: Option<JsonRpcError>,
103}
104
105fn deserialize_present_jsonrpc_result<'de, D, R>(deserializer: D) -> Result<Option<R>, D::Error>
106where
107    D: serde::Deserializer<'de>,
108    R: Deserialize<'de>,
109{
110    R::deserialize(deserializer).map(Some)
111}
112
113fn deserialize_optional_jsonrpc_id<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
114where
115    D: serde::Deserializer<'de>,
116{
117    let value = Option::<Value>::deserialize(deserializer)?;
118    match value {
119        None | Some(Value::Null) => Ok(None),
120        Some(Value::Number(number)) => number
121            .as_u64()
122            .map(Some)
123            .ok_or_else(|| serde::de::Error::custom("JSON-RPC id must be an unsigned integer")),
124        Some(Value::String(value)) => Ok(value.parse::<u64>().ok()),
125        Some(other) => Err(serde::de::Error::custom(format!(
126            "JSON-RPC id must be an unsigned integer or string, was {other}"
127        ))),
128    }
129}
130
131/// JSON-RPC error object as returned by Derive on failed requests.
132#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
133pub struct JsonRpcError {
134    /// Numeric error code defined by the venue.
135    pub code: i64,
136    /// Human-readable error message.
137    pub message: String,
138    /// Optional structured diagnostic payload.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub data: Option<Value>,
141}
142
143/// Option-specific fields appearing on `public/get_all_instruments` and legacy
144/// full ticker payloads when the instrument is an option.
145#[derive(Clone, Debug, Serialize, Deserialize)]
146pub struct DeriveOptionPublicDetails {
147    /// Option expiry as a UNIX timestamp in seconds.
148    pub expiry: i64,
149    /// Underlying index identifier (e.g. `"ETH-USD"`).
150    pub index: Ustr,
151    /// Call or put.
152    pub option_type: DeriveOptionKind,
153    /// Final settlement price, populated after expiry.
154    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
155    pub settlement_price: Option<Decimal>,
156    /// Strike price in quote currency.
157    #[serde(deserialize_with = "deserialize_decimal")]
158    pub strike: Decimal,
159}
160
161/// Perp-specific fields appearing on `public/get_all_instruments` and legacy full
162/// ticker payloads when the instrument is a perpetual.
163#[derive(Clone, Debug, Serialize, Deserialize)]
164pub struct DerivePerpPublicDetails {
165    /// Cumulative funding accrued since contract inception.
166    #[serde(deserialize_with = "deserialize_decimal")]
167    pub aggregate_funding: Decimal,
168    /// Current funding rate per funding interval.
169    #[serde(deserialize_with = "deserialize_decimal")]
170    pub funding_rate: Decimal,
171    /// Underlying index identifier (e.g. `"ETH-USD"`).
172    pub index: Ustr,
173    /// Maximum allowable funding rate per hour.
174    #[serde(deserialize_with = "deserialize_decimal")]
175    pub max_rate_per_hour: Decimal,
176    /// Minimum allowable funding rate per hour.
177    #[serde(deserialize_with = "deserialize_decimal")]
178    pub min_rate_per_hour: Decimal,
179    /// Legacy static interest-rate component, absent from API v3 definitions.
180    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
181    pub static_interest_rate: Option<Decimal>,
182}
183
184/// Instrument definition returned by `public/get_all_instruments`.
185#[derive(Clone, Debug, Serialize, Deserialize)]
186#[serde(remote = "Self")]
187pub struct DeriveInstrument {
188    /// Minimum increment of the `amount` field for orders.
189    #[serde(deserialize_with = "deserialize_decimal")]
190    pub amount_step: Decimal,
191    /// On-chain address of the base asset.
192    pub base_asset_address: Ustr,
193    /// Sub-id of the base asset within the asset module (decimal string).
194    pub base_asset_sub_id: Ustr,
195    /// Underlying currency (e.g. `"ETH"`).
196    pub base_currency: Ustr,
197    /// Base flat fee in USD.
198    #[serde(deserialize_with = "deserialize_decimal")]
199    pub base_fee: Decimal,
200    /// Canonical instrument name (e.g. `"ETH-PERP"`, `"ETH-20250627-3500-C"`).
201    pub instrument_name: Ustr,
202    /// Instrument category.
203    pub instrument_type: DeriveInstrumentType,
204    /// Whether the instrument is currently tradable.
205    pub is_active: bool,
206    /// Maker fee rate (fraction).
207    #[serde(deserialize_with = "deserialize_decimal")]
208    pub maker_fee_rate: Decimal,
209    /// Optional cap on the mark-price-derived fee rate.
210    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
211    pub mark_price_fee_rate_cap: Option<Decimal>,
212    /// Maximum allowed order amount.
213    #[serde(deserialize_with = "deserialize_decimal")]
214    pub maximum_amount: Decimal,
215    /// Venue-reported minimum contracts or tokens per trade.
216    /// Taker orders can fill below this value.
217    #[serde(deserialize_with = "deserialize_decimal")]
218    pub minimum_amount: Decimal,
219    /// Option-specific details (populated when `instrument_type == option`).
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub option_details: Option<DeriveOptionPublicDetails>,
222    /// Perp-specific details (populated when `instrument_type == perp`).
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub perp_details: Option<DerivePerpPublicDetails>,
225    /// Quote currency (e.g. `"USDC"`).
226    pub quote_currency: Ustr,
227    /// Scheduled activation timestamp (UNIX seconds).
228    pub scheduled_activation: i64,
229    /// Scheduled deactivation timestamp (UNIX seconds; `i64::MAX` if none).
230    pub scheduled_deactivation: i64,
231    /// Taker fee rate (fraction).
232    #[serde(deserialize_with = "deserialize_decimal")]
233    pub taker_fee_rate: Decimal,
234    /// Minimum price increment.
235    #[serde(deserialize_with = "deserialize_decimal")]
236    pub tick_size: Decimal,
237    /// Original instrument response fields, before typed decoding or normalization.
238    #[serde(skip)]
239    pub raw: Option<Params>,
240}
241
242impl<'de> Deserialize<'de> for DeriveInstrument {
243    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
244        let raw = Box::<RawValue>::deserialize(deserializer)?;
245        let mut typed = serde_json::Deserializer::from_str(raw.get());
246
247        // The remote derive decodes the typed fields without calling this implementation
248        let mut instrument = Self::deserialize(&mut typed).map_err(serde::de::Error::custom)?;
249        instrument.raw = Some(serde_json::from_str(raw.get()).map_err(serde::de::Error::custom)?);
250        Ok(instrument)
251    }
252}
253
254impl Serialize for DeriveInstrument {
255    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
256        Self::serialize(self, serializer)
257    }
258}
259
260/// 24-hour rolling trading statistics embedded in ticker payloads.
261#[derive(Clone, Debug, Serialize, Deserialize)]
262pub struct DeriveAggregateTradingStats {
263    /// Total contract volume over the last 24 hours.
264    #[serde(alias = "c", deserialize_with = "deserialize_decimal")]
265    pub contract_volume: Decimal,
266    /// Highest trade price in the last 24 hours.
267    #[serde(alias = "h", deserialize_with = "deserialize_decimal")]
268    pub high: Decimal,
269    /// Lowest trade price in the last 24 hours.
270    #[serde(alias = "l", deserialize_with = "deserialize_decimal")]
271    pub low: Decimal,
272    /// Number of trades over the last 24 hours.
273    #[serde(alias = "n", deserialize_with = "deserialize_decimal")]
274    pub num_trades: Decimal,
275    /// Current total open interest.
276    #[serde(alias = "oi", deserialize_with = "deserialize_decimal")]
277    pub open_interest: Decimal,
278    /// 24-hour percentage price change.
279    #[serde(alias = "p", deserialize_with = "deserialize_decimal")]
280    pub percent_change: Decimal,
281    /// 24-hour premium volume in USD (legacy field name).
282    #[serde(alias = "pr", deserialize_with = "deserialize_decimal")]
283    pub usd_change: Decimal,
284}
285
286/// Option pricing greeks and implied volatilities (option tickers only).
287#[derive(Clone, Debug, Serialize, Deserialize)]
288pub struct DeriveOptionPricing {
289    /// Implied volatility of the current best ask.
290    #[serde(alias = "ai", deserialize_with = "deserialize_decimal")]
291    pub ask_iv: Decimal,
292    /// Implied volatility of the current best bid.
293    #[serde(alias = "bi", deserialize_with = "deserialize_decimal")]
294    pub bid_iv: Decimal,
295    /// Option delta.
296    #[serde(alias = "d", deserialize_with = "deserialize_decimal")]
297    pub delta: Decimal,
298    /// Forward price used in pricing.
299    #[serde(alias = "f", deserialize_with = "deserialize_decimal")]
300    pub forward_price: Decimal,
301    /// Option gamma.
302    #[serde(alias = "g", deserialize_with = "deserialize_decimal")]
303    pub gamma: Decimal,
304    /// Implied volatility of the option.
305    #[serde(alias = "i", deserialize_with = "deserialize_decimal")]
306    pub iv: Decimal,
307    /// Mark price of the option.
308    #[serde(alias = "m", deserialize_with = "deserialize_decimal")]
309    pub mark_price: Decimal,
310    /// Option rho.
311    #[serde(alias = "r", deserialize_with = "deserialize_decimal")]
312    pub rho: Decimal,
313    /// Option theta.
314    #[serde(alias = "t", deserialize_with = "deserialize_decimal")]
315    pub theta: Decimal,
316    /// Option vega.
317    #[serde(alias = "v", deserialize_with = "deserialize_decimal")]
318    pub vega: Decimal,
319}
320
321/// Current ticker snapshot returned by `public/get_tickers` and `ticker_slim`.
322#[derive(Clone, Debug, Serialize, Deserialize)]
323pub struct DeriveTickerSnapshot {
324    /// Instrument identifier, injected from the `tickers` map key.
325    #[serde(default)]
326    pub instrument_name: Ustr,
327    /// Best ask amount.
328    #[serde(
329        rename = "A",
330        alias = "best_ask_amount",
331        deserialize_with = "deserialize_decimal"
332    )]
333    pub best_ask_amount: Decimal,
334    /// Best ask price.
335    #[serde(
336        rename = "a",
337        alias = "best_ask_price",
338        deserialize_with = "deserialize_decimal"
339    )]
340    pub best_ask_price: Decimal,
341    /// Best bid amount.
342    #[serde(
343        rename = "B",
344        alias = "best_bid_amount",
345        deserialize_with = "deserialize_decimal"
346    )]
347    pub best_bid_amount: Decimal,
348    /// Best bid price.
349    #[serde(
350        rename = "b",
351        alias = "best_bid_price",
352        deserialize_with = "deserialize_decimal"
353    )]
354    pub best_bid_price: Decimal,
355    /// Current hourly funding rate for perpetuals.
356    #[serde(
357        rename = "f",
358        alias = "funding_rate",
359        default,
360        deserialize_with = "deserialize_optional_decimal"
361    )]
362    pub funding_rate: Option<Decimal>,
363    /// Current oracle index price for the underlying.
364    #[serde(
365        rename = "I",
366        alias = "index_price",
367        deserialize_with = "deserialize_decimal_token"
368    )]
369    pub index_price: Decimal,
370    /// Current mark price.
371    #[serde(
372        rename = "M",
373        alias = "mark_price",
374        deserialize_with = "deserialize_decimal_token"
375    )]
376    pub mark_price: Decimal,
377    /// Maximum allowed price.
378    #[serde(
379        rename = "maxp",
380        alias = "max_price",
381        deserialize_with = "deserialize_decimal"
382    )]
383    pub max_price: Decimal,
384    /// Minimum allowed price.
385    #[serde(
386        rename = "minp",
387        alias = "min_price",
388        deserialize_with = "deserialize_decimal"
389    )]
390    pub min_price: Decimal,
391    /// Option pricing greeks (options only).
392    #[serde(default)]
393    pub option_pricing: Option<DeriveOptionPricing>,
394    /// 24-hour rolling statistics.
395    #[serde(default)]
396    pub stats: Option<DeriveAggregateTradingStats>,
397    /// Ticker timestamp (UNIX ms).
398    #[serde(rename = "t", alias = "timestamp")]
399    pub timestamp: i64,
400}
401
402/// Result returned by `public/get_tickers`.
403#[derive(Clone, Debug, Serialize, Deserialize)]
404pub struct DeriveTickersResult {
405    /// Ticker snapshots keyed by instrument name.
406    pub tickers: HashMap<String, DeriveTickerSnapshot>,
407}
408
409/// Legacy full ticker snapshot pushed on the deprecated WS
410/// `ticker.{instrument_name}.{interval}` channel.
411#[derive(Clone, Debug, Serialize, Deserialize)]
412pub struct DeriveTicker {
413    /// Minimum order amount increment.
414    #[serde(deserialize_with = "deserialize_decimal")]
415    pub amount_step: Decimal,
416    /// On-chain address of the base asset.
417    pub base_asset_address: Ustr,
418    /// Sub-id of the base asset within the asset module (decimal string).
419    pub base_asset_sub_id: Ustr,
420    /// Underlying currency.
421    pub base_currency: Ustr,
422    /// Base flat fee in USD.
423    #[serde(deserialize_with = "deserialize_decimal")]
424    pub base_fee: Decimal,
425    /// Best ask amount.
426    #[serde(deserialize_with = "deserialize_decimal")]
427    pub best_ask_amount: Decimal,
428    /// Best ask price.
429    #[serde(deserialize_with = "deserialize_decimal")]
430    pub best_ask_price: Decimal,
431    /// Best bid amount.
432    #[serde(deserialize_with = "deserialize_decimal")]
433    pub best_bid_amount: Decimal,
434    /// Best bid price.
435    #[serde(deserialize_with = "deserialize_decimal")]
436    pub best_bid_price: Decimal,
437    /// Current oracle index price for the underlying.
438    #[serde(deserialize_with = "deserialize_decimal_token")]
439    pub index_price: Decimal,
440    /// Instrument identifier.
441    pub instrument_name: Ustr,
442    /// Instrument category.
443    pub instrument_type: DeriveInstrumentType,
444    /// Whether the instrument is currently tradable.
445    pub is_active: bool,
446    /// Maker fee rate.
447    #[serde(deserialize_with = "deserialize_decimal")]
448    pub maker_fee_rate: Decimal,
449    /// Current mark price.
450    #[serde(deserialize_with = "deserialize_decimal_token")]
451    pub mark_price: Decimal,
452    /// Optional fee-rate cap derived from mark price.
453    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
454    pub mark_price_fee_rate_cap: Option<Decimal>,
455    /// Maximum allowed price.
456    #[serde(deserialize_with = "deserialize_decimal")]
457    pub max_price: Decimal,
458    /// Maximum order amount.
459    #[serde(deserialize_with = "deserialize_decimal")]
460    pub maximum_amount: Decimal,
461    /// Minimum allowed price.
462    #[serde(deserialize_with = "deserialize_decimal")]
463    pub min_price: Decimal,
464    /// Minimum order amount.
465    #[serde(deserialize_with = "deserialize_decimal")]
466    pub minimum_amount: Decimal,
467    /// Option-specific reference data.
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub option_details: Option<DeriveOptionPublicDetails>,
470    /// Option pricing greeks (options only).
471    #[serde(default, skip_serializing_if = "Option::is_none")]
472    pub option_pricing: Option<DeriveOptionPricing>,
473    /// Perp-specific reference data.
474    #[serde(default, skip_serializing_if = "Option::is_none")]
475    pub perp_details: Option<DerivePerpPublicDetails>,
476    /// Quote currency.
477    pub quote_currency: Ustr,
478    /// Scheduled activation timestamp (UNIX seconds).
479    pub scheduled_activation: i64,
480    /// Scheduled deactivation timestamp (UNIX seconds; `i64::MAX` if none).
481    pub scheduled_deactivation: i64,
482    /// 24-hour rolling statistics. Populated by the WebSocket ticker channel.
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub stats: Option<DeriveAggregateTradingStats>,
485    /// Taker fee rate.
486    #[serde(deserialize_with = "deserialize_decimal")]
487    pub taker_fee_rate: Decimal,
488    /// Minimum price increment.
489    #[serde(deserialize_with = "deserialize_decimal")]
490    pub tick_size: Decimal,
491    /// Ticker timestamp (UNIX ms).
492    pub timestamp: i64,
493}
494
495/// Order record returned by `private/order`, `private/get_open_orders`,
496/// `private/get_order_history`, and the `{subaccount_id}.orders` WS channel.
497#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct DeriveOrder {
499    /// Order amount in base units.
500    #[serde(deserialize_with = "deserialize_decimal_token")]
501    pub amount: Decimal,
502    /// Average fill price.
503    #[serde(deserialize_with = "deserialize_decimal_token")]
504    pub average_price: Decimal,
505    /// Cancel reason; [`DeriveOrderCancelReason::Empty`] when not cancelled.
506    #[serde(default = "cancel_reason_empty")]
507    pub cancel_reason: DeriveOrderCancelReason,
508    /// Creation timestamp (UNIX ms).
509    pub creation_timestamp: i64,
510    /// Order side.
511    pub direction: DeriveOrderSide,
512    /// Cumulative filled amount.
513    #[serde(deserialize_with = "deserialize_decimal_token")]
514    pub filled_amount: Decimal,
515    /// Instrument identifier.
516    pub instrument_name: Ustr,
517    /// Whether this order was generated via `private/transfer_position`.
518    pub is_transfer: bool,
519    /// Free-form user label.
520    #[serde(default)]
521    pub label: Ustr,
522    /// Last update timestamp (UNIX ms).
523    pub last_update_timestamp: i64,
524    /// Limit price in quote currency.
525    #[serde(deserialize_with = "deserialize_decimal_token")]
526    pub limit_price: Decimal,
527    /// Max fee in quote currency signed into the order.
528    #[serde(deserialize_with = "deserialize_decimal_token")]
529    pub max_fee: Decimal,
530    /// Whether MMP tags this order.
531    pub mmp: bool,
532    /// Order UNIX nanosecond nonce, encoded as a decimal string.
533    #[serde(
534        serialize_with = "crate::signing::nonce::serialize_nonce",
535        deserialize_with = "crate::signing::nonce::deserialize_nonce"
536    )]
537    pub nonce: u64,
538    /// Total fees paid against this order.
539    #[serde(deserialize_with = "deserialize_decimal_token")]
540    pub order_fee: Decimal,
541    /// Venue-assigned order ID (UUID-shaped).
542    pub order_id: String,
543    /// Order status.
544    pub order_status: DeriveOrderStatus,
545    /// Order type.
546    pub order_type: DeriveOrderType,
547    /// RFQ quote ID when the order is an RFQ execution.
548    #[serde(default, skip_serializing_if = "Option::is_none")]
549    pub quote_id: Option<String>,
550    /// Replaced order ID when this order resulted from a replace.
551    #[serde(default, skip_serializing_if = "Option::is_none")]
552    pub replaced_order_id: Option<String>,
553    /// 65-byte order signature, `0x`-prefixed hex.
554    pub signature: SecretString,
555    /// Signature expiry (UNIX seconds).
556    pub signature_expiry_sec: i64,
557    /// Session-key signer address.
558    pub signer: Ustr,
559    /// Owning subaccount.
560    pub subaccount_id: i64,
561    /// Time-in-force.
562    pub time_in_force: DeriveTimeInForce,
563    /// Trigger price for trigger orders.
564    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
565    pub trigger_price: Option<Decimal>,
566    /// Trigger price source for trigger orders.
567    #[serde(default, skip_serializing_if = "Option::is_none")]
568    pub trigger_price_type: Option<DeriveTriggerPriceType>,
569    /// Trigger rejection text when the trigger worker cannot submit.
570    #[serde(default, skip_serializing_if = "Option::is_none")]
571    pub trigger_reject_message: Option<String>,
572    /// Stop-loss or take-profit trigger flag.
573    #[serde(default, skip_serializing_if = "Option::is_none")]
574    pub trigger_type: Option<DeriveTriggerType>,
575}
576
577/// Result envelope returned by `private/order`.
578#[derive(Clone, Debug, Serialize, Deserialize)]
579pub struct DeriveOrderResult {
580    /// Accepted order.
581    pub order: DeriveOrder,
582    /// Trades generated synchronously by the submission, when any.
583    #[serde(default, deserialize_with = "deserialize_salvaged_vec")]
584    pub trades: Vec<DeriveTrade>,
585}
586
587/// Result envelope returned by `private/replace`.
588#[derive(Clone, Debug, Serialize, Deserialize)]
589pub struct DeriveReplaceResult {
590    /// Newly accepted replacement order, absent when cancellation succeeded but creation failed.
591    #[serde(default, skip_serializing_if = "Option::is_none")]
592    pub order: Option<DeriveOrder>,
593    /// Cancelled stale order, omitted by some responses and mocks.
594    #[serde(default, skip_serializing_if = "Option::is_none")]
595    pub cancelled_order: Option<DeriveOrder>,
596    /// Replacement creation error after the stale order was cancelled.
597    #[serde(default, skip_serializing_if = "Option::is_none")]
598    pub create_order_error: Option<JsonRpcError>,
599}
600
601/// Confirmed outcome returned by `private/replace`.
602#[derive(Clone, Debug)]
603pub enum DeriveReplaceOutcome {
604    /// The stale order was cancelled and the replacement was accepted.
605    Replaced(DeriveOrder),
606    /// The stale order was cancelled but replacement creation failed.
607    Canceled {
608        /// Cancelled stale order returned by the venue.
609        cancelled_order: DeriveOrder,
610        /// Structured error returned by replacement creation.
611        create_order_error: JsonRpcError,
612    },
613}
614
615impl DeriveReplaceResult {
616    /// Validates the response shape and cancellation identity.
617    ///
618    /// # Errors
619    ///
620    /// Returns an error if fields contradict each other, a cancellation record is unexpected, or
621    /// the replacement state is invalid.
622    pub(crate) fn into_outcome(
623        self,
624        expected_cancel_order_id: &str,
625        expected_replacement_label: &str,
626        expected_subaccount_id: u64,
627        expected_instrument: &str,
628    ) -> Result<DeriveReplaceOutcome, String> {
629        let validate_cancelled_order = |order: &DeriveOrder| {
630            if order.order_id != expected_cancel_order_id {
631                return Err(format!(
632                    "private/replace cancelled order {} did not match requested order {expected_cancel_order_id}",
633                    order.order_id,
634                ));
635            }
636
637            if order.order_status != DeriveOrderStatus::Cancelled {
638                return Err(format!(
639                    "private/replace cancellation record for {expected_cancel_order_id} had status {}",
640                    order.order_status,
641                ));
642            }
643
644            validate_replace_order_scope(
645                order,
646                expected_replacement_label,
647                expected_subaccount_id,
648                expected_instrument,
649            )
650        };
651
652        match (self.order, self.cancelled_order, self.create_order_error) {
653            (Some(order), cancelled_order, None) => {
654                if order.order_id == expected_cancel_order_id {
655                    return Err(format!(
656                        "private/replace returned the cancelled order {expected_cancel_order_id} as its replacement",
657                    ));
658                }
659
660                if !matches!(
661                    order.order_status,
662                    DeriveOrderStatus::Open | DeriveOrderStatus::Filled
663                ) {
664                    return Err(format!(
665                        "private/replace replacement {} had status {}",
666                        order.order_id, order.order_status,
667                    ));
668                }
669
670                validate_replace_order_scope(
671                    &order,
672                    expected_replacement_label,
673                    expected_subaccount_id,
674                    expected_instrument,
675                )?;
676
677                if let Some(cancelled_order) = cancelled_order.as_ref() {
678                    validate_cancelled_order(cancelled_order)?;
679                }
680
681                Ok(DeriveReplaceOutcome::Replaced(order))
682            }
683            (None, Some(cancelled_order), Some(create_order_error)) => {
684                validate_cancelled_order(&cancelled_order)?;
685                Ok(DeriveReplaceOutcome::Canceled {
686                    cancelled_order,
687                    create_order_error,
688                })
689            }
690            _ => Err("private/replace returned an inconsistent result".to_string()),
691        }
692    }
693}
694
695fn validate_replace_order_scope(
696    order: &DeriveOrder,
697    expected_replacement_label: &str,
698    expected_subaccount_id: u64,
699    expected_instrument: &str,
700) -> Result<(), String> {
701    if u64::try_from(order.subaccount_id).ok() != Some(expected_subaccount_id)
702        || order.instrument_name != expected_instrument
703    {
704        return Err(format!(
705            "private/replace order {} did not match requested account and instrument",
706            order.order_id
707        ));
708    }
709
710    if order.label != expected_replacement_label {
711        return Err(format!(
712            "private/replace order {} had label {}, expected {expected_replacement_label}",
713            order.order_id, order.label
714        ));
715    }
716
717    Ok(())
718}
719
720/// Result returned by `private/cancel_by_label`.
721#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
722pub struct DeriveCancelByLabelResult {
723    /// Confirmed count, or -1 for an unscoped acknowledgement requiring state confirmation.
724    pub cancelled_orders: i64,
725}
726
727/// Result returned by `private/cancel_by_instrument`.
728pub type DeriveCancelByInstrumentResult = DeriveCancelByLabelResult;
729
730/// Empty result returned by state-changing endpoints without a typed payload.
731#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
732pub struct DeriveEmptyResult {}
733
734impl<'de> Deserialize<'de> for DeriveEmptyResult {
735    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
736    where
737        D: serde::Deserializer<'de>,
738    {
739        match Value::deserialize(deserializer)? {
740            Value::Null | Value::Object(_) => Ok(Self {}),
741            Value::String(value) if value == "ok" => Ok(Self {}),
742            other => Err(serde::de::Error::custom(format!(
743                "empty Derive result must be an object, null, or \"ok\", was {other}"
744            ))),
745        }
746    }
747}
748
749/// Position record returned by `private/get_positions` and embedded in
750/// `private/get_subaccount` responses.
751#[derive(Clone, Debug, Serialize, Deserialize)]
752pub struct DerivePosition {
753    /// Signed position amount; positive = long, negative = short.
754    #[serde(deserialize_with = "deserialize_decimal_token")]
755    pub amount: Decimal,
756    /// Average entry price over the lifetime of the position;
757    /// includes opening fees for perpetuals and options.
758    #[serde(deserialize_with = "deserialize_decimal_token")]
759    pub average_price: Decimal,
760    /// Position opening timestamp (UNIX ms).
761    pub creation_timestamp: i64,
762    /// Cumulative funding accrued by this position (perps only).
763    #[serde(deserialize_with = "deserialize_decimal_token")]
764    pub cumulative_funding: Decimal,
765    /// Position delta (with respect to forward for options).
766    #[serde(deserialize_with = "deserialize_decimal_token")]
767    pub delta: Decimal,
768    /// Position gamma (zero for non-options).
769    #[serde(deserialize_with = "deserialize_decimal_token")]
770    pub gamma: Decimal,
771    /// Current oracle index price for the underlying.
772    #[serde(deserialize_with = "deserialize_decimal_token")]
773    pub index_price: Decimal,
774    /// Signed USD initial-health contribution, including mark-to-market value.
775    #[serde(deserialize_with = "deserialize_decimal_token")]
776    pub initial_margin: Decimal,
777    /// Instrument identifier (same as the base asset name).
778    pub instrument_name: Ustr,
779    /// Instrument category.
780    pub instrument_type: DeriveInstrumentType,
781    /// Effective leverage (perps only).
782    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
783    pub leverage: Option<Decimal>,
784    /// Index price at which the position would liquidate.
785    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
786    pub liquidation_price: Option<Decimal>,
787    /// Signed USD maintenance-health contribution, including mark-to-market value.
788    #[serde(deserialize_with = "deserialize_decimal_token")]
789    pub maintenance_margin: Decimal,
790    /// Current mark price.
791    #[serde(deserialize_with = "deserialize_decimal_token")]
792    pub mark_price: Decimal,
793    /// USD mark-to-market value of the position.
794    #[serde(deserialize_with = "deserialize_decimal_token")]
795    pub mark_value: Decimal,
796    /// Net USD settled from this position.
797    #[serde(deserialize_with = "deserialize_decimal_token")]
798    pub net_settlements: Decimal,
799    /// USD open-order margin contribution for this asset.
800    #[serde(deserialize_with = "deserialize_decimal_token")]
801    pub open_orders_margin: Decimal,
802    /// Funding not yet settled into cash balance (perps only).
803    #[serde(deserialize_with = "deserialize_decimal_token")]
804    pub pending_funding: Decimal,
805    /// Realized PnL booked on this position.
806    #[serde(deserialize_with = "deserialize_decimal_token")]
807    pub realized_pnl: Decimal,
808    /// Position theta (zero for non-options).
809    #[serde(deserialize_with = "deserialize_decimal_token")]
810    pub theta: Decimal,
811    /// Unrealized PnL.
812    #[serde(deserialize_with = "deserialize_decimal_token")]
813    pub unrealized_pnl: Decimal,
814    /// Position vega (zero for non-options).
815    #[serde(deserialize_with = "deserialize_decimal_token")]
816    pub vega: Decimal,
817}
818
819/// Collateral row inside a `private/get_subaccount` response.
820#[derive(Clone, Debug, Serialize, Deserialize)]
821pub struct DeriveCollateral {
822    /// Collateral amount.
823    #[serde(
824        deserialize_with = "deserialize_decimal_token",
825        serialize_with = "serialize_decimal_as_str"
826    )]
827    pub amount: Decimal,
828    /// Asset name (e.g. `"ETH"`, `"USDC"`).
829    pub asset_name: Ustr,
830    /// Asset category.
831    pub asset_type: DeriveAssetType,
832    /// Cumulative interest earned or paid.
833    #[serde(
834        deserialize_with = "deserialize_decimal_token",
835        serialize_with = "serialize_decimal_as_str"
836    )]
837    pub cumulative_interest: Decimal,
838    /// Underlying currency.
839    pub currency: Ustr,
840    /// USD initial margin credit from this collateral.
841    #[serde(
842        deserialize_with = "deserialize_decimal_token",
843        serialize_with = "serialize_decimal_as_str"
844    )]
845    pub initial_margin: Decimal,
846    /// USD maintenance margin credit.
847    #[serde(
848        deserialize_with = "deserialize_decimal_token",
849        serialize_with = "serialize_decimal_as_str"
850    )]
851    pub maintenance_margin: Decimal,
852    /// Current mark price of the asset.
853    #[serde(
854        deserialize_with = "deserialize_decimal_token",
855        serialize_with = "serialize_decimal_as_str"
856    )]
857    pub mark_price: Decimal,
858    /// USD value (`amount * mark_price`).
859    #[serde(
860        deserialize_with = "deserialize_decimal_token",
861        serialize_with = "serialize_decimal_as_str"
862    )]
863    pub mark_value: Decimal,
864    /// Interest not yet settled on-chain.
865    #[serde(
866        deserialize_with = "deserialize_decimal_token",
867        serialize_with = "serialize_decimal_as_str"
868    )]
869    pub pending_interest: Decimal,
870}
871
872/// Subaccount snapshot returned by `private/get_subaccount`.
873#[derive(Clone, Debug, Serialize, Deserialize)]
874pub struct DeriveSubaccount {
875    /// Collateral rows contributing to margin.
876    pub collaterals: Vec<DeriveCollateral>,
877    /// Total initial margin credit from collaterals.
878    #[serde(deserialize_with = "deserialize_decimal_token")]
879    pub collaterals_initial_margin: Decimal,
880    /// Total maintenance margin credit from collaterals.
881    #[serde(deserialize_with = "deserialize_decimal_token")]
882    pub collaterals_maintenance_margin: Decimal,
883    /// Mark-to-market value of all collaterals.
884    #[serde(deserialize_with = "deserialize_decimal_token")]
885    pub collaterals_value: Decimal,
886    /// Currencies covered by the subaccount manager.
887    pub currency: Vec<Ustr>,
888    /// Whether the venue failed to load the portfolio.
889    pub failed_to_fetch: bool,
890    /// Signed net initial margin health, excluding open-order reservations.
891    /// Negative health blocks risk-increasing trades.
892    #[serde(deserialize_with = "deserialize_decimal_token")]
893    pub initial_margin: Decimal,
894    /// Whether the subaccount is mid-liquidation.
895    pub is_under_liquidation: bool,
896    /// Free-form subaccount label.
897    #[serde(default, skip_serializing_if = "Option::is_none")]
898    pub label: Option<String>,
899    /// Signed net maintenance margin health; negative permits liquidation.
900    #[serde(deserialize_with = "deserialize_decimal_token")]
901    pub maintenance_margin: Decimal,
902    /// Venue manager identity.
903    pub manager_id: u32,
904    /// Open-ended venue margin model (for example `"SM"` or `"PM2"`).
905    pub margin_type: String,
906    /// Maintenance-margin credit from risk-universe loss socialization.
907    #[serde(deserialize_with = "deserialize_decimal_token")]
908    pub mm_credits: Decimal,
909    /// Open orders held by the subaccount.
910    pub open_orders: Vec<DeriveOrder>,
911    /// Signed USD open-order reservation, excluded from `initial_margin`.
912    #[serde(deserialize_with = "deserialize_decimal_token")]
913    pub open_orders_margin: Decimal,
914    /// Open positions held by the subaccount.
915    pub positions: Vec<DerivePosition>,
916    /// Signed USD initial-health contribution from positions, including mark-to-market value.
917    #[serde(deserialize_with = "deserialize_decimal_token")]
918    pub positions_initial_margin: Decimal,
919    /// Signed USD maintenance-health contribution from positions, including mark-to-market value.
920    #[serde(deserialize_with = "deserialize_decimal_token")]
921    pub positions_maintenance_margin: Decimal,
922    /// Mark-to-market value of positions.
923    #[serde(deserialize_with = "deserialize_decimal_token")]
924    pub positions_value: Decimal,
925    /// Maintenance-margin change after the next option expiry.
926    #[serde(deserialize_with = "deserialize_decimal_token")]
927    pub projected_margin_change: Decimal,
928    /// Risk universe containing the manager.
929    pub risk_universe_id: u32,
930    /// Subaccount identifier.
931    pub subaccount_id: i64,
932    /// Total subaccount value (collateral + positions).
933    #[serde(deserialize_with = "deserialize_decimal_token")]
934    pub subaccount_value: Decimal,
935    /// Pending vault-deposit reservations on the source subaccount.
936    pub vault_deposit_holds: Vec<DeriveVaultDepositHold>,
937}
938
939/// Pending vault-deposit reservation returned with a subaccount.
940#[derive(Debug, Clone, Serialize, Deserialize)]
941pub struct DeriveVaultDepositHold {
942    /// Reserved amount in native asset units.
943    #[serde(
944        deserialize_with = "deserialize_decimal_token",
945        serialize_with = "serialize_decimal_as_str"
946    )]
947    pub amount: Decimal,
948    /// Reserved asset.
949    pub asset_name: Ustr,
950    /// Asset currency.
951    pub currency: Ustr,
952    /// Target vault identifier.
953    pub vault_id: u64,
954}
955
956/// Private trade record returned by `private/get_trade_history` and the
957/// `{subaccount_id}.trades` WS channel.
958#[derive(Clone, Debug, Serialize, Deserialize)]
959pub struct DeriveTrade {
960    /// Trade side.
961    pub direction: DeriveOrderSide,
962    /// Underlying index price at the time of the trade.
963    #[serde(deserialize_with = "deserialize_decimal")]
964    pub index_price: Decimal,
965    /// Instrument identifier.
966    pub instrument_name: Ustr,
967    /// Whether this trade was generated via `private/transfer_position`.
968    pub is_transfer: bool,
969    /// Free-form user label inherited from the order.
970    #[serde(default)]
971    pub label: Ustr,
972    /// Maker / taker role of the user.
973    pub liquidity_role: DeriveLiquidityRole,
974    /// Mark price at the time of the trade.
975    #[serde(deserialize_with = "deserialize_decimal")]
976    pub mark_price: Decimal,
977    /// Originating order ID.
978    pub order_id: String,
979    /// RFQ quote ID when relevant.
980    #[serde(default, skip_serializing_if = "Option::is_none")]
981    pub quote_id: Option<String>,
982    /// Realized PnL booked by this trade.
983    #[serde(deserialize_with = "deserialize_decimal")]
984    pub realized_pnl: Decimal,
985    /// Owning subaccount.
986    pub subaccount_id: i64,
987    /// Trade timestamp (UNIX ms).
988    pub timestamp: i64,
989    /// Filled amount on this trade.
990    #[serde(deserialize_with = "deserialize_decimal_token")]
991    pub trade_amount: Decimal,
992    /// Fee charged for this trade.
993    #[serde(deserialize_with = "deserialize_decimal_token")]
994    pub trade_fee: Decimal,
995    /// Trade identifier.
996    pub trade_id: String,
997    /// Trade execution price.
998    #[serde(deserialize_with = "deserialize_decimal_token")]
999    pub trade_price: Decimal,
1000    /// Ethereum L1 batch transaction hash, absent before settlement.
1001    #[serde(default, skip_serializing_if = "Option::is_none")]
1002    pub tx_hash: Option<String>,
1003    /// Settlement batch stage when reported, independent of trade execution.
1004    #[serde(default, skip_serializing_if = "Option::is_none")]
1005    pub batch_status: Option<String>,
1006    /// Settlement operation identity, independent of the trade and order IDs.
1007    #[serde(default, skip_serializing_if = "Option::is_none")]
1008    pub op_uuid: Option<String>,
1009    /// Owning wallet address, absent in pending order responses.
1010    #[serde(default, skip_serializing_if = "Option::is_none")]
1011    pub wallet: Option<Ustr>,
1012}
1013
1014/// Public trade record returned by `public/get_trade_history` and the
1015/// `trades.{instrument_type}.{currency}` WS channel.
1016///
1017/// Public REST and WS rows carry participant roles and account detail. Optional
1018/// fields also accept sparse frames; settlement metadata does not gate trades.
1019#[derive(Clone, Debug, Serialize, Deserialize)]
1020pub struct DerivePublicTrade {
1021    /// Trade side.
1022    pub direction: DeriveOrderSide,
1023    /// Underlying index price at the time of the trade.
1024    #[serde(deserialize_with = "deserialize_decimal")]
1025    pub index_price: Decimal,
1026    /// Instrument identifier.
1027    pub instrument_name: Ustr,
1028    /// Role of this row's participant in the trade. The REST history endpoint
1029    /// returns one maker row and one taker row per trade under the same
1030    /// `trade_id`. Public WS rows also carry participant roles.
1031    #[serde(default, skip_serializing_if = "Option::is_none")]
1032    pub liquidity_role: Option<DeriveLiquidityRole>,
1033    /// Mark price at the time of the trade.
1034    #[serde(deserialize_with = "deserialize_decimal")]
1035    pub mark_price: Decimal,
1036    /// RFQ quote ID when relevant.
1037    #[serde(default, skip_serializing_if = "Option::is_none")]
1038    pub quote_id: Option<String>,
1039    /// RFQ session ID when the trade originated from a request-for-quote.
1040    #[serde(default, skip_serializing_if = "Option::is_none")]
1041    pub rfq_id: Option<String>,
1042    /// Realized PnL attributed to this participant, when supplied.
1043    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
1044    pub realized_pnl: Option<Decimal>,
1045    /// Participant subaccount, when supplied.
1046    #[serde(default, skip_serializing_if = "Option::is_none")]
1047    pub subaccount_id: Option<i64>,
1048    /// Trade timestamp (UNIX ms).
1049    pub timestamp: i64,
1050    /// Filled amount.
1051    #[serde(deserialize_with = "deserialize_decimal_token")]
1052    pub trade_amount: Decimal,
1053    /// Fee charged to this participant, when supplied.
1054    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
1055    pub trade_fee: Option<Decimal>,
1056    /// Trade identifier.
1057    pub trade_id: String,
1058    /// Execution price.
1059    #[serde(deserialize_with = "deserialize_decimal_token")]
1060    pub trade_price: Decimal,
1061    /// Ethereum L1 batch transaction hash from historical rows, when supplied.
1062    #[serde(default, skip_serializing_if = "Option::is_none")]
1063    pub tx_hash: Option<String>,
1064    /// Settlement batch stage from historical rows, when supplied.
1065    #[serde(default, skip_serializing_if = "Option::is_none")]
1066    pub batch_status: Option<String>,
1067    /// Settlement operation identity accepted when supplied.
1068    #[serde(default, skip_serializing_if = "Option::is_none")]
1069    pub op_uuid: Option<String>,
1070    /// Participant wallet address, when supplied.
1071    #[serde(default, skip_serializing_if = "Option::is_none")]
1072    pub wallet: Option<Ustr>,
1073}
1074
1075/// Pagination metadata attached to listing endpoints.
1076#[derive(Clone, Debug, Serialize, Deserialize)]
1077pub struct DerivePaginationInfo {
1078    /// Total number of items across all pages.
1079    pub count: i64,
1080    /// Number of pages available.
1081    pub num_pages: i64,
1082}
1083
1084#[derive(Debug, Clone, Deserialize)]
1085pub(crate) struct DeriveInstrumentsResult {
1086    pub(crate) instruments: Vec<DeriveInstrument>,
1087    pub(crate) pagination: DerivePaginationInfo,
1088}
1089
1090/// Paginated `private/get_orders` result envelope.
1091#[derive(Clone, Debug, Serialize, Deserialize)]
1092pub struct DeriveOrdersResult {
1093    /// Orders on the current page. Deliberately strict: reconciliation infers
1094    /// state from absence, so a dropped order row is worse than a loud failure.
1095    pub orders: Vec<DeriveOrder>,
1096    /// Pagination metadata.
1097    pub pagination: DerivePaginationInfo,
1098    /// Owning subaccount.
1099    pub subaccount_id: i64,
1100}
1101
1102/// `private/get_open_orders` result envelope.
1103#[derive(Clone, Debug, Serialize, Deserialize)]
1104pub struct DeriveOpenOrdersResult {
1105    /// Currently open orders. Deliberately strict: reconciliation infers
1106    /// state from absence, so a dropped order row is worse than a loud failure.
1107    pub orders: Vec<DeriveOrder>,
1108    /// Owning subaccount.
1109    pub subaccount_id: i64,
1110}
1111
1112/// Paginated `private/get_trade_history` result envelope.
1113#[derive(Clone, Debug, Serialize)]
1114pub struct DeriveTradesResult {
1115    /// Trades on the current page.
1116    pub trades: Vec<DeriveTrade>,
1117    /// Pagination metadata.
1118    pub pagination: DerivePaginationInfo,
1119    /// Owning subaccount.
1120    pub subaccount_id: i64,
1121    #[serde(skip)]
1122    pub(crate) records_complete: bool,
1123}
1124
1125impl<'de> Deserialize<'de> for DeriveTradesResult {
1126    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1127        #[derive(Deserialize)]
1128        struct TradePage {
1129            trades: Vec<Box<RawValue>>,
1130            pagination: DerivePaginationInfo,
1131            subaccount_id: i64,
1132        }
1133        #[derive(Deserialize)]
1134        struct TradeFee {
1135            #[serde(rename = "trade_fee", deserialize_with = "deserialize_decimal_token")]
1136            _trade_fee: Decimal,
1137        }
1138        let page = TradePage::deserialize(deserializer)?;
1139        for trade in &page.trades {
1140            if !trade.get().starts_with('{') {
1141                return Err(serde::de::Error::custom(
1142                    "private trade row must be an object",
1143                ));
1144            }
1145
1146            let _: TradeFee =
1147                serde_json::from_str(trade.get()).map_err(serde::de::Error::custom)?;
1148        }
1149
1150        let count = page.trades.len();
1151        let trades: Vec<DeriveTrade> = salvage_rows(page.trades);
1152        Ok(Self {
1153            records_complete: trades.len() == count,
1154            trades,
1155            pagination: page.pagination,
1156            subaccount_id: page.subaccount_id,
1157        })
1158    }
1159}
1160
1161/// Paginated `public/get_trade_history` result envelope.
1162#[derive(Clone, Debug, Serialize, Deserialize)]
1163pub struct DerivePublicTradesResult {
1164    /// Trades on the current page.
1165    pub trades: Vec<DerivePublicTrade>,
1166    /// Pagination metadata.
1167    pub pagination: DerivePaginationInfo,
1168}
1169
1170/// OHLCV candle returned by `public/get_tradingview_chart_data`.
1171///
1172/// The venue ships the `result` field as a flat array of these records; the
1173/// HTTP client deserializes that array directly into `Vec<DerivePublicCandle>`.
1174/// Timestamps are UNIX **seconds** (not milliseconds, as on the trade and
1175/// funding endpoints).
1176#[derive(Clone, Debug, Serialize, Deserialize)]
1177pub struct DerivePublicCandle {
1178    /// Open price for the bucket.
1179    #[serde(deserialize_with = "deserialize_decimal_token")]
1180    pub open_price: Decimal,
1181    /// High price for the bucket.
1182    #[serde(deserialize_with = "deserialize_decimal_token")]
1183    pub high_price: Decimal,
1184    /// Low price for the bucket.
1185    #[serde(deserialize_with = "deserialize_decimal_token")]
1186    pub low_price: Decimal,
1187    /// Close price for the bucket.
1188    #[serde(deserialize_with = "deserialize_decimal_token")]
1189    pub close_price: Decimal,
1190    /// Notional volume in USD over the bucket.
1191    #[serde(deserialize_with = "deserialize_decimal_token")]
1192    pub volume_usd: Decimal,
1193    /// Base-asset volume (contracts) over the bucket.
1194    #[serde(deserialize_with = "deserialize_decimal_token")]
1195    pub volume_contracts: Decimal,
1196    /// Sample timestamp (UNIX seconds).
1197    pub timestamp: i64,
1198    /// Bucket start timestamp (UNIX seconds); regularly spaced by `period`.
1199    pub timestamp_bucket: i64,
1200}
1201
1202/// Funding rate sample returned by `public/get_funding_rate_history`.
1203#[derive(Clone, Debug, Serialize, Deserialize)]
1204pub struct DerivePublicFundingRate {
1205    /// Funding rate observed at `timestamp` (fraction per funding interval).
1206    #[serde(deserialize_with = "deserialize_decimal_token")]
1207    pub funding_rate: Decimal,
1208    /// Sample timestamp (UNIX ms).
1209    pub timestamp: i64,
1210}
1211
1212/// `public/get_funding_rate_history` result envelope.
1213#[derive(Clone, Debug, Serialize, Deserialize)]
1214pub struct DerivePublicFundingRateHistoryResult {
1215    /// Funding rate samples in venue response order (currently newest to oldest).
1216    pub funding_rate_history: Vec<DerivePublicFundingRate>,
1217}
1218
1219/// `private/get_positions` result envelope.
1220#[derive(Clone, Debug, Serialize, Deserialize)]
1221pub struct DerivePositionsResult {
1222    /// Positions held by the subaccount. Deliberately strict: mass status
1223    /// synthesizes flat reports for instruments absent from this list, so a
1224    /// dropped position row would report "flat" for a position the venue
1225    /// still holds.
1226    pub positions: Vec<DerivePosition>,
1227    /// Owning subaccount.
1228    pub subaccount_id: i64,
1229}
1230
1231fn cancel_reason_empty() -> DeriveOrderCancelReason {
1232    DeriveOrderCancelReason::Empty
1233}
1234
1235#[cfg(test)]
1236mod tests {
1237    use std::path::PathBuf;
1238
1239    use nautilus_core::UnixNanos;
1240    use nautilus_model::identifiers::AccountId;
1241    use rstest::rstest;
1242    use serde_json::{Value, json};
1243
1244    use super::*;
1245
1246    fn data_path() -> PathBuf {
1247        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_data")
1248    }
1249
1250    fn load_json(filename: &str) -> Value {
1251        let content = std::fs::read_to_string(data_path().join(filename))
1252            .unwrap_or_else(|_| panic!("failed to read {filename}"));
1253        serde_json::from_str(&content).expect("invalid json")
1254    }
1255
1256    #[rstest]
1257    fn test_request_serializes_with_jsonrpc_version_tag() {
1258        let req = JsonRpcRequest::new(7, "public/get_instruments", json!({"currency": "ETH"}));
1259        let wire = serde_json::to_value(&req).unwrap();
1260        assert_eq!(wire["jsonrpc"], "2.0");
1261        assert_eq!(wire["id"], 7);
1262        assert_eq!(wire["method"], "public/get_instruments");
1263        assert_eq!(wire["params"]["currency"], "ETH");
1264    }
1265
1266    #[rstest]
1267    fn test_response_decodes_success_envelope() {
1268        let body = json!({"id": 1, "result": {"instruments": []}});
1269        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
1270        assert_eq!(resp.id, Some(1));
1271        assert!(resp.error.is_none());
1272        assert!(resp.result.is_some());
1273    }
1274
1275    #[rstest]
1276    fn test_response_decodes_error_envelope() {
1277        let body = json!({
1278            "id": 9,
1279            "error": {"code": -32600, "message": "Invalid Request"}
1280        });
1281        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
1282        assert_eq!(resp.id, Some(9));
1283        assert!(resp.result.is_none());
1284        let err = resp.error.expect("error present");
1285        assert_eq!(err.code, -32600);
1286        assert_eq!(err.message, "Invalid Request");
1287        assert!(err.data.is_none());
1288    }
1289
1290    #[rstest]
1291    fn test_response_decodes_error_envelope_with_data_field() {
1292        let body = json!({
1293            "id": 9,
1294            "error": {
1295                "code": -32602,
1296                "message": "Invalid params",
1297                "data": {"field": "currency"},
1298            }
1299        });
1300        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
1301        let err = resp.error.expect("error present");
1302        assert_eq!(err.data, Some(json!({"field": "currency"})));
1303    }
1304
1305    #[rstest]
1306    fn test_response_tolerates_missing_id() {
1307        let body = json!({"result": {"ok": true}});
1308        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
1309        assert!(resp.id.is_none());
1310        assert!(resp.result.is_some());
1311    }
1312
1313    #[rstest]
1314    fn test_response_tolerates_string_id() {
1315        let body = json!({"id": "e3c970c6-94aa-420c-b6db-d0f585a7fde9", "result": {"ok": true}});
1316        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
1317        assert!(resp.id.is_none());
1318        assert!(resp.result.is_some());
1319    }
1320
1321    #[rstest]
1322    fn test_response_decodes_numeric_string_id() {
1323        let body = json!({"id": "42", "result": {"ok": true}});
1324        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
1325        assert_eq!(resp.id, Some(42));
1326        assert!(resp.result.is_some());
1327    }
1328
1329    #[rstest]
1330    fn test_instrument_decodes_perp_with_perp_details() {
1331        let body = load_json("perps/instrument_eth.json");
1332        let instrument: DeriveInstrument = serde_json::from_value(body).unwrap();
1333        assert_eq!(instrument.instrument_name, "ETH-PERP");
1334        assert_eq!(instrument.instrument_type, DeriveInstrumentType::Perp);
1335        assert!(instrument.option_details.is_none());
1336        let perp = instrument.perp_details.expect("perp details present");
1337        assert_eq!(perp.index, "ETH-USD");
1338    }
1339
1340    #[rstest]
1341    fn test_instrument_decodes_option_with_option_details() {
1342        let mut body = load_json("options/instrument_eth.json");
1343        body["scheduled_activation"] = json!(0);
1344        let instrument: DeriveInstrument = serde_json::from_value(body).unwrap();
1345        let option = instrument.option_details.expect("option details present");
1346        assert_eq!(option.option_type, DeriveOptionKind::Call);
1347        assert_eq!(option.strike.to_string(), "3500");
1348        assert!(option.settlement_price.is_none());
1349    }
1350
1351    #[rstest]
1352    #[case(1_695_836_058_725_001_000)]
1353    #[case(u64::MAX)]
1354    fn test_order_nonce_string_round_trip(#[case] nonce: u64) {
1355        let mut body = load_json("perps/http_order_eth_partially_filled.json");
1356        body["nonce"] = json!(nonce.to_string());
1357        let order: DeriveOrder = serde_json::from_value(body).unwrap();
1358        let encoded = serde_json::to_value(&order).unwrap();
1359        let decoded: DeriveOrder = serde_json::from_value(encoded.clone()).unwrap();
1360        assert_eq!(order.nonce, nonce);
1361        assert_eq!(encoded["nonce"], nonce.to_string());
1362        assert_eq!(serde_json::to_value(decoded).unwrap(), encoded);
1363    }
1364
1365    #[rstest]
1366    #[case(json!(""))]
1367    #[case(json!("-1"))]
1368    #[case(json!("18446744073709551616"))]
1369    #[case(json!(1_695_836_058_725_001_000_u64))]
1370    fn test_order_nonce_rejects_invalid_wire_values(#[case] nonce: Value) {
1371        let mut body = load_json("perps/http_order_eth_partially_filled.json");
1372        body["nonce"] = nonce;
1373        assert!(serde_json::from_value::<DeriveOrder>(body).is_err());
1374    }
1375
1376    #[rstest]
1377    #[case(true, false)]
1378    #[case(false, true)]
1379    #[case(true, true)]
1380    fn test_order_defaults_optional_label_and_cancel_reason(
1381        #[case] omit_label: bool,
1382        #[case] omit_reason: bool,
1383    ) {
1384        let mut body = load_json("perps/http_order_eth_partially_filled.json");
1385        if omit_label {
1386            body["label"] = json!("");
1387        }
1388
1389        let expected: DeriveOrder = serde_json::from_value(body.clone()).unwrap();
1390        let fields = body.as_object_mut().unwrap();
1391        if omit_label {
1392            fields.remove("label");
1393        }
1394
1395        if omit_reason {
1396            fields.remove("cancel_reason");
1397        }
1398
1399        let order: DeriveOrder = serde_json::from_value(body).unwrap();
1400        assert_eq!(
1401            serde_json::to_value(order).unwrap(),
1402            serde_json::to_value(expected).unwrap()
1403        );
1404    }
1405
1406    #[rstest]
1407    fn test_order_decodes_partially_filled_market_order() {
1408        // Distinct `amount` and `filled_amount` so a struct-field swap is
1409        // detectable. Every Ustr-typed field has a unique value so a serde
1410        // rename or field-order regression surfaces against a single fixture.
1411        let body = load_json("perps/http_order_eth_partially_filled.json");
1412        let order: DeriveOrder = serde_json::from_value(body).unwrap();
1413        let debug = format!("{order:?}");
1414        assert_eq!(order.amount.to_string(), "2.0");
1415        assert_eq!(order.filled_amount.to_string(), "1.5");
1416        assert_eq!(order.average_price.to_string(), "3500.25");
1417        assert_eq!(order.order_status, DeriveOrderStatus::Filled);
1418        assert_eq!(order.cancel_reason, DeriveOrderCancelReason::Empty);
1419        assert_eq!(order.direction, DeriveOrderSide::Buy);
1420        assert_eq!(order.time_in_force, DeriveTimeInForce::Ioc);
1421        assert_eq!(order.order_type, DeriveOrderType::Market);
1422        assert_eq!(order.instrument_name, "ETH-PERP");
1423        assert_eq!(order.label, "alpha-strategy");
1424        assert_eq!(order.signer, "0xsigner");
1425        assert_eq!(order.order_id, "abc-123");
1426        assert_eq!(order.subaccount_id, 42);
1427        assert_eq!(order.signature_expiry_sec, 1_700_001_000);
1428        assert!(!order.mmp);
1429        assert!(!order.is_transfer);
1430        assert!(order.quote_id.is_none());
1431        assert!(order.replaced_order_id.is_none());
1432        assert!(debug.contains(REDACTED));
1433        assert!(!debug.contains("0xdead"));
1434    }
1435
1436    #[rstest]
1437    fn test_replace_result_decodes_canceled_without_replacement() {
1438        let mut cancelled_order = load_json("perps/http_order_eth_partially_filled.json");
1439        cancelled_order["order_id"] = json!("old-order");
1440        cancelled_order["order_status"] = json!("cancelled");
1441        cancelled_order["label"] = json!("replacement-label");
1442        let result: DeriveReplaceResult = serde_json::from_value(json!({
1443            "order": null,
1444            "cancelled_order": cancelled_order,
1445            "create_order_error": {
1446                "code": 10001,
1447                "message": "insufficient margin",
1448            },
1449        }))
1450        .unwrap();
1451
1452        let outcome = result
1453            .into_outcome("old-order", "replacement-label", 42, "ETH-PERP")
1454            .unwrap();
1455
1456        let DeriveReplaceOutcome::Canceled {
1457            cancelled_order,
1458            create_order_error,
1459        } = outcome
1460        else {
1461            panic!("expected canceled outcome");
1462        };
1463
1464        assert_eq!(cancelled_order.order_id, "old-order");
1465        assert_eq!(cancelled_order.order_status, DeriveOrderStatus::Cancelled);
1466        assert_eq!(create_order_error.code, 10001);
1467        assert_eq!(create_order_error.message, "insufficient margin");
1468        assert!(create_order_error.data.is_none());
1469    }
1470
1471    #[rstest]
1472    fn test_replace_result_rejects_non_cancelled_partial_record() {
1473        let mut cancelled_order = load_json("perps/http_order_eth_partially_filled.json");
1474        cancelled_order["order_id"] = json!("old-order");
1475        cancelled_order["order_status"] = json!("open");
1476        let result: DeriveReplaceResult = serde_json::from_value(json!({
1477            "order": null,
1478            "cancelled_order": cancelled_order,
1479            "create_order_error": {
1480                "code": 10001,
1481                "message": "insufficient margin",
1482            },
1483        }))
1484        .unwrap();
1485
1486        let error = result
1487            .into_outcome("old-order", "replacement-label", 42, "ETH-PERP")
1488            .unwrap_err();
1489        assert!(error.contains("had status open"));
1490    }
1491
1492    #[rstest]
1493    fn test_replace_result_rejects_mismatched_replacement_label() {
1494        let mut replacement_order = load_json("perps/http_order_eth_partially_filled.json");
1495        replacement_order["order_id"] = json!("new-order");
1496        replacement_order["order_status"] = json!("open");
1497        replacement_order["label"] = json!("wrong-label");
1498        let result: DeriveReplaceResult = serde_json::from_value(json!({
1499            "order": replacement_order,
1500            "cancelled_order": null,
1501            "create_order_error": null,
1502        }))
1503        .unwrap();
1504
1505        let error = result
1506            .into_outcome("old-order", "expected-label", 42, "ETH-PERP")
1507            .unwrap_err();
1508        assert!(error.contains("had label wrong-label, expected expected-label"));
1509    }
1510
1511    #[rstest]
1512    fn test_position_decodes_perp_with_optional_leverage() {
1513        // Distinct decimal values per field so a struct-field swap surfaces.
1514        let body = load_json("perps/http_position_eth.json");
1515        let position: DerivePosition = serde_json::from_value(body).unwrap();
1516        assert_eq!(position.instrument_type, DeriveInstrumentType::Perp);
1517        assert_eq!(position.instrument_name, "ETH-PERP");
1518        assert_eq!(position.amount.to_string(), "-2");
1519        assert_eq!(position.delta.to_string(), "-2");
1520        assert_eq!(position.gamma.to_string(), "0.1");
1521        assert_eq!(position.theta.to_string(), "-0.3");
1522        assert_eq!(position.vega.to_string(), "0.5");
1523        assert_eq!(position.unrealized_pnl.to_string(), "8");
1524        assert_eq!(position.mark_value.to_string(), "-7008");
1525        assert_eq!(
1526            position.leverage.as_ref().map(ToString::to_string),
1527            Some("5.0".into()),
1528        );
1529        assert_eq!(
1530            position.liquidation_price.as_ref().map(ToString::to_string),
1531            Some("4200".into()),
1532        );
1533    }
1534
1535    #[rstest]
1536    fn test_subaccount_decodes_with_collaterals_and_open_orders() {
1537        let body = load_json("common/http_subaccount_usdc.json");
1538        let subaccount: DeriveSubaccount = serde_json::from_value(body).unwrap();
1539        assert_eq!(subaccount.subaccount_id, 42);
1540        assert_eq!(subaccount.margin_type, "SM");
1541        assert_eq!(subaccount.collaterals.len(), 1);
1542        assert_eq!(subaccount.collaterals[0].asset_type, DeriveAssetType::Erc20);
1543        assert!(!subaccount.is_under_liquidation);
1544    }
1545
1546    #[rstest]
1547    #[case("currency")]
1548    #[case("manager_id")]
1549    #[case("risk_universe_id")]
1550    #[case("failed_to_fetch")]
1551    #[case("margin_type")]
1552    #[case("mm_credits")]
1553    #[case("projected_margin_change")]
1554    #[case("vault_deposit_holds")]
1555    #[case("positions_value")]
1556    #[case("positions")]
1557    #[case("open_orders")]
1558    fn test_subaccount_requires_complete_v3_envelope(#[case] field: &str) {
1559        let mut body = load_json("common/http_subaccount_pm2.json");
1560        body.as_object_mut().unwrap().remove(field);
1561
1562        assert!(serde_json::from_value::<DeriveSubaccount>(body).is_err());
1563    }
1564
1565    #[rstest]
1566    #[case(serde_json::Value::Null)]
1567    #[case(json!(""))]
1568    fn test_subaccount_rejects_null_or_empty_required_decimals(#[case] invalid: Value) {
1569        for field in [
1570            "initial_margin",
1571            "maintenance_margin",
1572            "positions_initial_margin",
1573            "positions_maintenance_margin",
1574            "positions_value",
1575            "open_orders_margin",
1576            "mm_credits",
1577            "projected_margin_change",
1578        ] {
1579            let mut body = load_json("common/http_subaccount_pm2.json");
1580            body[field] = invalid.clone();
1581            assert!(
1582                serde_json::from_value::<DeriveSubaccount>(body).is_err(),
1583                "{field}"
1584            );
1585        }
1586
1587        let mut body = load_json("common/http_subaccount_pm2.json");
1588        body["collaterals"][0]["amount"] = invalid;
1589        assert!(serde_json::from_value::<DeriveSubaccount>(body).is_err());
1590    }
1591
1592    #[rstest]
1593    #[case("amount")]
1594    #[case("average_price")]
1595    #[case("filled_amount")]
1596    #[case("limit_price")]
1597    #[case("max_fee")]
1598    #[case("order_fee")]
1599    fn test_subaccount_rejects_empty_or_null_order_decimal(#[case] field: &str) {
1600        for invalid in [Value::Null, json!("")] {
1601            let mut body = load_json("common/http_subaccount_pm2.json");
1602            let mut order = load_json("perps/http_order_eth_partially_filled.json");
1603            order[field] = invalid;
1604            body["open_orders"] = json!([order]);
1605
1606            assert!(
1607                serde_json::from_value::<DeriveSubaccount>(body).is_err(),
1608                "{field}"
1609            );
1610        }
1611    }
1612
1613    #[rstest]
1614    fn test_subaccount_decodes_high_scale_decimal_values() {
1615        let body = load_json("common/http_subaccount_high_scale.json");
1616        let subaccount: DeriveSubaccount = serde_json::from_value(body).unwrap();
1617        let position = &subaccount.positions[0];
1618
1619        assert_eq!(
1620            subaccount.initial_margin.to_string(),
1621            "0.1234567890123456789012345679",
1622        );
1623        assert_eq!(
1624            subaccount.collaterals[0].amount.to_string(),
1625            "0.1234567890123456789012345679",
1626        );
1627        assert_eq!(
1628            position.pending_funding.to_string(),
1629            "0.1234567890123456789012345679",
1630        );
1631        assert_eq!(
1632            position.leverage.as_ref().map(ToString::to_string),
1633            Some("5.1234567890123456789012345679".into()),
1634        );
1635        assert_eq!(
1636            position.liquidation_price.as_ref().map(ToString::to_string),
1637            Some("4200.1234567890123456789012346".into()),
1638        );
1639
1640        // Order rows nested in the snapshot carry the same high-scale values.
1641        let open_order = &subaccount.open_orders[0];
1642        assert_eq!(
1643            open_order.filled_amount.to_string(),
1644            "0.1234567890123456789012345679",
1645        );
1646        assert_eq!(
1647            open_order.max_fee.to_string(),
1648            "0.1234567890123456789012345679",
1649        );
1650    }
1651
1652    #[rstest]
1653    fn test_subaccount_retains_unknown_order_status_for_account_conversion() {
1654        let body = load_json("common/http_subaccount_unknown_variants.json");
1655        let subaccount: DeriveSubaccount = serde_json::from_value(body).unwrap();
1656        assert_eq!(subaccount.open_orders.len(), 2);
1657        assert_eq!(
1658            subaccount.open_orders[1].order_status,
1659            DeriveOrderStatus::Unknown
1660        );
1661        let mut modeled = subaccount.clone();
1662        modeled.open_orders[1].order_status = DeriveOrderStatus::Open;
1663        let expected = crate::http::parse::parse_derive_subaccount_to_balances(&modeled).unwrap();
1664        let actual = crate::http::parse::parse_derive_subaccount_to_balances(&subaccount).unwrap();
1665
1666        assert_eq!(actual, expected);
1667    }
1668
1669    #[rstest]
1670    fn test_subaccount_decodes_populated_vault_deposit_hold() {
1671        let mut body = load_json("common/http_subaccount_pm2.json");
1672        let hold = json!({
1673            "amount": "0.000000000123456789",
1674            "asset_name": "ETH",
1675            "currency": "ETH",
1676            "vault_id": 123,
1677        });
1678        body["vault_deposit_holds"] = json!([hold]);
1679
1680        let subaccount: DeriveSubaccount = serde_json::from_value(body).unwrap();
1681
1682        assert_eq!(
1683            serde_json::to_value(&subaccount.vault_deposit_holds).unwrap(),
1684            json!([hold])
1685        );
1686        assert_eq!(
1687            subaccount.vault_deposit_holds[0].amount.to_string(),
1688            "0.000000000123456789"
1689        );
1690    }
1691
1692    #[rstest]
1693    fn test_public_trade_round_trips() {
1694        let body = load_json("perps/http_public_trade_eth_sell.json");
1695        let trade: DerivePublicTrade = serde_json::from_value(body).unwrap();
1696        assert_eq!(trade.direction, DeriveOrderSide::Sell);
1697        assert_eq!(trade.batch_status.as_deref(), Some("Settled"));
1698        let reserialized = serde_json::to_value(&trade).unwrap();
1699        assert_eq!(reserialized["instrument_name"], "ETH-PERP");
1700        assert_eq!(reserialized["liquidity_role"], "taker");
1701    }
1702
1703    #[rstest]
1704    fn test_orders_result_envelope_decodes() {
1705        let body = json!({
1706            "orders": [],
1707            "pagination": {"count": 0, "num_pages": 0},
1708            "subaccount_id": 42,
1709        });
1710        let result: DeriveOrdersResult = serde_json::from_value(body).unwrap();
1711        assert!(result.orders.is_empty());
1712        assert_eq!(result.subaccount_id, 42);
1713        assert_eq!(result.pagination.count, 0);
1714    }
1715
1716    #[rstest]
1717    fn test_orders_result_decodes_unknown_variant_fields() {
1718        let body = load_json("perps/http_orders_result_eth_unknown_variants.json");
1719        let result: DeriveOrdersResult = serde_json::from_value(body).unwrap();
1720
1721        assert_eq!(result.orders.len(), 2);
1722        assert_eq!(result.orders[0].order_status, DeriveOrderStatus::Open);
1723        let unknowns = &result.orders[1];
1724        assert_eq!(unknowns.order_status, DeriveOrderStatus::Cancelled);
1725        assert_eq!(unknowns.cancel_reason, DeriveOrderCancelReason::Unknown);
1726        assert_eq!(unknowns.order_type, DeriveOrderType::Unknown);
1727        assert_eq!(unknowns.time_in_force, DeriveTimeInForce::Unknown);
1728        assert_eq!(unknowns.trigger_type, Some(DeriveTriggerType::Unknown));
1729        assert_eq!(
1730            unknowns.trigger_price_type,
1731            Some(DeriveTriggerPriceType::Unknown),
1732        );
1733    }
1734
1735    #[rstest]
1736    fn test_orders_result_retains_unknown_status_and_rejects_report_conversion() {
1737        let mut body = load_json("perps/http_orders_result_eth_unknown_variants.json");
1738        body["orders"][0]["order_status"] = json!("queued");
1739        let result: DeriveOrdersResult = serde_json::from_value(body).unwrap();
1740        assert_eq!(result.orders.len(), 2);
1741        assert_eq!(result.orders[0].order_status, DeriveOrderStatus::Unknown);
1742        let error = crate::http::parse::parse_derive_order_to_report(
1743            &result.orders[0],
1744            AccountId::from("DERIVE-001"),
1745            UnixNanos::from(17),
1746        )
1747        .unwrap_err();
1748        assert_eq!(error.to_string(), "unmodeled Derive order status");
1749    }
1750
1751    #[rstest]
1752    fn test_positions_result_fails_on_undecodable_row() {
1753        // Pins the deliberate strictness documented on the struct.
1754        let mut body = load_json("perps/http_positions_result_eth.json");
1755        body["positions"][0]["amount"] = json!({});
1756
1757        assert!(serde_json::from_value::<DerivePositionsResult>(body).is_err());
1758    }
1759
1760    fn perp_ticker_json() -> Value {
1761        load_json("perps/http_ticker_eth_snapshot.json")
1762    }
1763
1764    #[rstest]
1765    fn test_ticker_decodes_perp_snapshot() {
1766        let ticker: DeriveTicker = serde_json::from_value(perp_ticker_json()).unwrap();
1767        assert_eq!(ticker.instrument_name, "ETH-PERP");
1768        assert_eq!(ticker.instrument_type, DeriveInstrumentType::Perp);
1769        assert_eq!(ticker.mark_price.to_string(), "3500.5");
1770        assert_eq!(ticker.best_bid_price.to_string(), "3499.5");
1771        assert_eq!(ticker.best_ask_price.to_string(), "3501.0");
1772        assert_eq!(ticker.timestamp, 1_700_000_000_000);
1773        assert!(ticker.option_details.is_none());
1774        assert!(ticker.option_pricing.is_none());
1775        let perp = ticker.perp_details.expect("perp details present");
1776        assert_eq!(perp.index, "ETH-USD");
1777        assert_eq!(perp.funding_rate.to_string(), "0.0002");
1778        let stats = ticker
1779            .stats
1780            .as_ref()
1781            .expect("WS ticker fixture includes stats");
1782        assert_eq!(stats.contract_volume.to_string(), "12345.6");
1783        assert_eq!(stats.high.to_string(), "3600");
1784        assert_eq!(stats.num_trades.to_string(), "789");
1785    }
1786
1787    #[rstest]
1788    fn test_ticker_decodes_option_snapshot_with_greeks() {
1789        let body = load_json("options/http_ticker_eth_snapshot.json");
1790        let ticker: DeriveTicker = serde_json::from_value(body).unwrap();
1791        assert_eq!(ticker.instrument_type, DeriveInstrumentType::Option);
1792        assert!(ticker.perp_details.is_none());
1793        let option = ticker.option_details.expect("option details present");
1794        assert_eq!(option.option_type, DeriveOptionKind::Call);
1795        assert_eq!(option.strike.to_string(), "3500");
1796        assert!(option.settlement_price.is_none());
1797        let greeks = ticker.option_pricing.expect("option pricing present");
1798        assert_eq!(greeks.delta.to_string(), "0.55");
1799        assert_eq!(greeks.gamma.to_string(), "0.0008");
1800        assert_eq!(greeks.theta.to_string(), "-2.1");
1801        assert_eq!(greeks.vega.to_string(), "4.5");
1802        assert_eq!(greeks.iv.to_string(), "0.60");
1803        assert_eq!(greeks.forward_price.to_string(), "3505");
1804    }
1805
1806    #[rstest]
1807    fn test_private_trade_decodes_with_order_link() {
1808        // Asserts the fields that distinguish DeriveTrade from DerivePublicTrade
1809        // (order_id, label, is_transfer, realized_pnl) plus the Ustr-typed
1810        // wallet and the typed enum fields.
1811        let body = load_json("perps/http_private_trade_eth.json");
1812        let trade: DeriveTrade = serde_json::from_value(body).unwrap();
1813        assert_eq!(trade.direction, DeriveOrderSide::Buy);
1814        assert_eq!(trade.liquidity_role, DeriveLiquidityRole::Maker);
1815        assert_eq!(trade.batch_status.as_deref(), Some("Settled"));
1816        assert_eq!(trade.instrument_name, "ETH-PERP");
1817        assert_eq!(trade.label, "alpha-strategy");
1818        assert_eq!(trade.wallet.as_ref().map(Ustr::as_str), Some("0xwallet"));
1819        assert_eq!(trade.order_id, "order-abc");
1820        assert_eq!(trade.trade_id, "trade-xyz");
1821        assert_eq!(trade.subaccount_id, 42);
1822        assert_eq!(trade.realized_pnl.to_string(), "12.5");
1823        assert_eq!(trade.trade_amount.to_string(), "0.5");
1824        assert_eq!(trade.trade_price.to_string(), "3499.0");
1825        assert!(!trade.is_transfer);
1826        assert!(trade.quote_id.is_none());
1827        assert_eq!(trade.tx_hash.as_deref(), Some("0xhash"));
1828    }
1829
1830    #[rstest]
1831    #[case("trade_amount", "0.5")]
1832    #[case("trade_price", "3499.0")]
1833    #[case("trade_fee", "0.02")]
1834    fn test_native_trade_numeric_tokens_preserve_exact_value(
1835        #[case] field: &str,
1836        #[case] original: &str,
1837        #[values(
1838            ("1234567.123456789012", rust_decimal_macros::dec!(1234567.123456789012)),
1839            ("1.234567890123456789e-10", rust_decimal_macros::dec!(0.0000000001234567890123456789))
1840        )]
1841        (token, expected): (&str, Decimal),
1842    ) {
1843        let fixture = include_str!("../../test_data/perps/http_private_trade_eth.json");
1844        let row = fixture.replace(
1845            &format!("\"{field}\": \"{original}\""),
1846            &format!("\"{field}\": {token}"),
1847        );
1848        assert_ne!(row, fixture);
1849        let direct: DeriveTrade = serde_json::from_str(&row).unwrap();
1850        let page = serde_json::to_string(&serde_json::json!({
1851            "pagination": {"count": 1, "num_pages": 1},
1852            "subaccount_id": 42,
1853        }))
1854        .unwrap();
1855        let page = format!("{},\"trades\":[{row}]}}", page.trim_end_matches('}'));
1856        let page: DeriveTradesResult = serde_json::from_str(&page).unwrap();
1857        let subscription: crate::websocket::DeriveTradesSubscriptionData =
1858            serde_json::from_str(&format!("[{row}]")).unwrap();
1859
1860        assert_eq!(page.trades.len(), 1);
1861        assert_eq!(subscription.trades.len(), 1);
1862        assert!(page.records_complete);
1863
1864        for trade in [&direct, &page.trades[0], &subscription.trades[0]] {
1865            assert_eq!(
1866                trade.trade_amount,
1867                if field == "trade_amount" {
1868                    expected
1869                } else {
1870                    rust_decimal_macros::dec!(0.5)
1871                }
1872            );
1873            assert_eq!(
1874                trade.trade_price,
1875                if field == "trade_price" {
1876                    expected
1877                } else {
1878                    rust_decimal_macros::dec!(3499.0)
1879                }
1880            );
1881            assert_eq!(
1882                trade.trade_fee,
1883                if field == "trade_fee" {
1884                    expected
1885                } else {
1886                    rust_decimal_macros::dec!(0.02)
1887                }
1888            );
1889            assert_eq!(
1890                serde_json::to_value(trade).unwrap(),
1891                serde_json::to_value(&direct).unwrap()
1892            );
1893        }
1894    }
1895
1896    #[rstest]
1897    fn test_v3_trade_rest_and_private_subscription_schema_parity() {
1898        let native: Vec<Value> = serde_json::from_str(include_str!(
1899            "../../test_data/perps/http_trades_v3_native.json"
1900        ))
1901        .unwrap();
1902        let stages: Vec<Value> = serde_json::from_str(include_str!(
1903            "../../test_data/common/trade_batch_stages.json"
1904        ))
1905        .unwrap();
1906
1907        for stage in stages {
1908            let mut row = native[0].clone();
1909            row["batch_status"] = stage.clone();
1910            row["op_uuid"] = Value::Null;
1911            row["tx_hash"] = Value::Null;
1912            let result: DeriveTradesResult = serde_json::from_value(json!({
1913                "trades": [row.clone()], "pagination": {"count": 1, "num_pages": 1},
1914                "subaccount_id": 42,
1915            }))
1916            .unwrap();
1917            let subscription: crate::websocket::DeriveTradesSubscriptionData =
1918                serde_json::from_value(json!([row])).unwrap();
1919            assert_eq!(result.trades.len(), 1);
1920            assert_eq!(subscription.trades.len(), 1);
1921            let rest = &result.trades[0];
1922            let ws = &subscription.trades[0];
1923            assert_eq!(
1924                serde_json::to_value(rest).unwrap(),
1925                serde_json::to_value(ws).unwrap()
1926            );
1927            assert_eq!(rest.batch_status.as_deref(), stage.as_str());
1928            assert_eq!(rest.op_uuid, None);
1929            assert_eq!(rest.tx_hash, None);
1930            assert_eq!(rest.trade_fee, rust_decimal_macros::dec!(0.087052478068));
1931            assert_eq!(rest.trade_id, "pm2-held-fixture-trade-close");
1932            assert_eq!(rest.order_id, "pm2-held-fixture-order-close");
1933        }
1934
1935        let mut row = native[1].clone();
1936        row.as_object_mut().unwrap().remove("batch_status");
1937        row.as_object_mut().unwrap().remove("op_uuid");
1938        row.as_object_mut().unwrap().remove("tx_hash");
1939        row.as_object_mut().unwrap().remove("label");
1940        let early: DeriveTrade = serde_json::from_value(row).unwrap();
1941        assert_eq!(early.batch_status, None);
1942        assert_eq!(early.op_uuid, None);
1943        assert_eq!(early.tx_hash, None);
1944        assert_eq!(early.label, Ustr::from(""));
1945    }
1946
1947    #[rstest]
1948    #[case("trade_amount")]
1949    #[case("trade_price")]
1950    #[case("trade_fee")]
1951    fn test_v3_required_execution_decimals_reject_invalid_values(
1952        #[case] field: &str,
1953        #[values("null", "empty", "missing")] invalid: &str,
1954    ) {
1955        let mut row = load_json("perps/http_private_trade_eth.json");
1956        match invalid {
1957            "null" => row[field] = Value::Null,
1958            "empty" => row[field] = json!(""),
1959            "missing" => {
1960                row.as_object_mut().unwrap().remove(field);
1961            }
1962            _ => unreachable!(),
1963        }
1964
1965        assert!(serde_json::from_value::<DeriveTrade>(row.clone()).is_err());
1966        let rest = serde_json::from_value::<DeriveTradesResult>(json!({
1967            "trades": [row.clone()], "pagination": {"count": 1, "num_pages": 1}, "subaccount_id": 42,
1968        }));
1969        let ws: crate::websocket::DeriveTradesSubscriptionData =
1970            serde_json::from_value(json!([row.clone()])).unwrap();
1971        let mut order = load_json("spot/http_submit_order_response_mainnet.json")["result"].clone();
1972        order["trades"] = json!([row.clone()]);
1973        let order_result: DeriveOrderResult = serde_json::from_value(order).unwrap();
1974
1975        if field == "trade_fee" {
1976            assert!(rest.is_err());
1977        } else {
1978            let rest = rest.unwrap();
1979            assert_eq!(rest.trades.len(), 0);
1980            assert!(!rest.records_complete);
1981        }
1982
1983        assert_eq!(ws.trades.len(), 0);
1984        assert_eq!(order_result.trades.len(), 0);
1985        assert!(
1986            serde_json::from_value::<crate::websocket::DeriveTradesSubscriptionData>(row.clone())
1987                .is_err()
1988        );
1989
1990        if field != "trade_fee" {
1991            assert!(serde_json::from_value::<DerivePublicTrade>(row.clone()).is_err());
1992            let valid = load_json("perps/http_public_trade_eth_sell.json");
1993            assert!(
1994                serde_json::from_value::<DerivePublicTradesResult>(json!({
1995                    "trades": [valid, row.clone()],
1996                    "pagination": {"count": 2, "num_pages": 1},
1997                }))
1998                .is_err()
1999            );
2000            let payload: crate::websocket::WsSubscriptionPayload = serde_json::from_str(
2001                &json!({"channel": "trades.perp.ETH", "data": [valid, row]}).to_string(),
2002            )
2003            .unwrap();
2004            assert!(crate::websocket::parse_public_ws_data(&payload).is_err());
2005        }
2006    }
2007
2008    #[rstest]
2009    #[case(json!("0"))]
2010    #[case(json!(0))]
2011    fn test_v3_execution_fee_accepts_explicit_zero(#[case] fee: Value) {
2012        let mut row = load_json("perps/http_private_trade_eth.json");
2013        row["trade_fee"] = fee;
2014        let trade: DeriveTrade = serde_json::from_value(row).unwrap();
2015        assert_eq!(trade.trade_fee, Decimal::ZERO);
2016        assert_eq!(trade.trade_amount, rust_decimal_macros::dec!(0.5));
2017        assert_eq!(trade.trade_price, rust_decimal_macros::dec!(3499));
2018    }
2019
2020    #[rstest]
2021    fn test_private_trade_decodes_high_scale_decimal_values() {
2022        let mut body = load_json("perps/http_private_trade_eth.json");
2023        body["trade_fee"] = json!("1.234567890123456789012345678912345e-1");
2024        body["realized_pnl"] = json!("0.1234567890123456789012345678912345");
2025
2026        let trade: DeriveTrade = serde_json::from_value(body).unwrap();
2027
2028        assert_eq!(
2029            trade.trade_fee.to_string(),
2030            "0.1234567890123456789012345679"
2031        );
2032        assert_eq!(
2033            trade.realized_pnl.to_string(),
2034            "0.1234567890123456789012345679",
2035        );
2036    }
2037
2038    #[rstest]
2039    fn test_order_result_decodes_pending_trade_with_null_tx_hash() {
2040        let mut body = load_json("spot/http_submit_order_response_mainnet.json");
2041        let mut trade = load_json("perps/http_private_trade_eth.json");
2042        trade["tx_hash"] = Value::Null;
2043        trade["batch_status"] = Value::Null;
2044        trade.as_object_mut().unwrap().remove("wallet");
2045        body["result"]["trades"] = json!([trade]);
2046
2047        let result: DeriveOrderResult =
2048            serde_json::from_value(body["result"].clone()).expect("result decodes");
2049
2050        assert_eq!(result.trades.len(), 1);
2051        assert!(result.trades[0].tx_hash.is_none());
2052        assert_eq!(result.trades[0].batch_status, None);
2053        assert!(result.trades[0].wallet.is_none());
2054    }
2055
2056    #[rstest]
2057    fn test_empty_result_decodes_cancel_ack_shapes() {
2058        let object: DeriveEmptyResult = serde_json::from_value(json!({})).unwrap();
2059        let ok_string: DeriveEmptyResult = serde_json::from_value(json!("ok")).unwrap();
2060        let null_envelope: JsonRpcResponse<DeriveEmptyResult> =
2061            serde_json::from_value(json!({"id": 1, "result": null})).unwrap();
2062
2063        assert_eq!(object, DeriveEmptyResult {});
2064        assert_eq!(ok_string, DeriveEmptyResult {});
2065        assert_eq!(null_envelope.result, Some(DeriveEmptyResult {}));
2066    }
2067
2068    #[rstest]
2069    #[case("common/ws_cancel_by_label_zero.json", 0)]
2070    #[case("common/ws_cancel_by_label_nonzero.json", 2)]
2071    fn test_cancel_order_by_label_result_decodes_count(
2072        #[case] filename: &str,
2073        #[case] expected: i64,
2074    ) {
2075        let response: JsonRpcResponse<DeriveCancelByLabelResult> =
2076            serde_json::from_value(load_json(filename)).expect("response decodes");
2077
2078        assert_eq!(response.result.unwrap().cancelled_orders, expected);
2079    }
2080
2081    #[rstest]
2082    fn test_order_result_preserves_trades_with_unknown_status() {
2083        let mut order = load_json("perps/http_order_eth_partially_filled.json");
2084        order["order_status"] = serde_json::json!("future-status");
2085        let trade = load_json("perps/http_private_trade_eth.json");
2086        let result: DeriveOrderResult = serde_json::from_value(serde_json::json!({
2087            "order": order, "trades": [trade],
2088        }))
2089        .unwrap();
2090        assert_eq!(result.trades.len(), 1);
2091        assert_eq!(
2092            serde_json::to_value(&result.trades[0]).unwrap(),
2093            serde_json::to_value(serde_json::from_value::<DeriveTrade>(trade).unwrap()).unwrap()
2094        );
2095    }
2096
2097    #[rstest]
2098    fn test_trades_result_envelope_decodes() {
2099        let body = load_json("perps/http_trades_result_eth.json");
2100        let result: DeriveTradesResult = serde_json::from_value(body).unwrap();
2101        assert_eq!(result.trades.len(), 1);
2102        assert_eq!(result.subaccount_id, 7);
2103        assert_eq!(result.pagination.count, 1);
2104        assert_eq!(result.pagination.num_pages, 1);
2105        assert_eq!(result.trades[0].trade_id, "t-1");
2106        assert!(result.records_complete);
2107    }
2108
2109    #[rstest]
2110    fn test_trades_result_salvages_unknown_variant_rows() {
2111        let body = load_json("perps/http_trades_result_eth_unknown_variants.json");
2112        let result: DeriveTradesResult = serde_json::from_value(body).unwrap();
2113
2114        // The `short`-direction row is undecodable and skipped; the rest survive.
2115        assert_eq!(result.trades.len(), 2);
2116        assert_eq!(result.trades[0].trade_id, "t-1");
2117        let unknowns = &result.trades[1];
2118        assert_eq!(unknowns.trade_id, "t-2");
2119        assert_eq!(unknowns.liquidity_role, DeriveLiquidityRole::Unknown);
2120        assert!(!result.records_complete);
2121    }
2122
2123    #[rstest]
2124    #[case(json!("invalid-fee"))]
2125    #[case(json!(""))]
2126    #[case(Value::Null)]
2127    fn test_trades_result_rejects_undecodable_fee(#[case] fee: Value) {
2128        let mut body = load_json("perps/http_trades_result_eth.json");
2129        let mut bad = body["trades"][0].clone();
2130        bad["trade_id"] = json!("bad-fee-row");
2131        bad["trade_fee"] = fee;
2132        body["trades"].as_array_mut().unwrap().push(bad);
2133        assert!(serde_json::from_value::<DeriveTradesResult>(body).is_err());
2134    }
2135
2136    #[rstest]
2137    #[case(serde_json::json!(["0.1"]))]
2138    #[case(serde_json::json!(0.1))]
2139    #[case(serde_json::Value::Null)]
2140    fn test_trades_result_rejects_non_object_fee_rows(#[case] row: Value) {
2141        let result = serde_json::from_value::<DeriveTradesResult>(json!({
2142            "trades": [row],
2143            "pagination": {"count": 1, "num_pages": 1},
2144            "subaccount_id": 42,
2145        }));
2146
2147        assert_eq!(
2148            result.unwrap_err().to_string(),
2149            "private trade row must be an object"
2150        );
2151    }
2152
2153    #[rstest]
2154    fn test_trades_result_preserves_unknown_batch_metadata() {
2155        let mut body = load_json("perps/http_trades_result_eth.json");
2156        body["trades"][0]["batch_status"] = json!("FutureStage");
2157
2158        let result: DeriveTradesResult = serde_json::from_value(body).unwrap();
2159
2160        assert_eq!(result.trades.len(), 1);
2161        assert_eq!(
2162            result.trades[0].batch_status.as_deref(),
2163            Some("FutureStage")
2164        );
2165    }
2166
2167    #[rstest]
2168    fn test_public_trades_result_envelope_decodes() {
2169        let body = load_json("perps/http_public_trades_result_eth.json");
2170        let result: DerivePublicTradesResult = serde_json::from_value(body).unwrap();
2171        assert_eq!(result.trades.len(), 1);
2172        assert_eq!(result.pagination.count, 1);
2173        assert_eq!(result.trades[0].trade_id, "pub-1");
2174    }
2175
2176    #[rstest]
2177    fn test_public_funding_rate_history_result_envelope_decodes() {
2178        let body = load_json("perps/http_public_funding_rate_history_eth.json");
2179        let result: DerivePublicFundingRateHistoryResult = serde_json::from_value(body).unwrap();
2180        assert_eq!(result.funding_rate_history.len(), 3);
2181        let first = &result.funding_rate_history[0];
2182        assert_eq!(first.funding_rate.to_string(), "0.00012");
2183        assert_eq!(first.timestamp, 1_700_000_000_000);
2184        assert_eq!(
2185            result.funding_rate_history.last().unwrap().timestamp,
2186            1_700_007_200_000,
2187        );
2188    }
2189
2190    #[rstest]
2191    #[case("index_price")]
2192    #[case("mark_price")]
2193    fn test_required_ticker_decimals_reject_missing_tokens(
2194        #[case] field: &str,
2195        #[values(Value::Null, json!(""))] invalid: Value,
2196    ) {
2197        let mut ticker = load_json("perps/http_ticker_eth_snapshot.json");
2198        ticker[field] = invalid.clone();
2199        assert!(serde_json::from_value::<DeriveTicker>(ticker.clone()).is_err());
2200        assert!(serde_json::from_value::<DeriveTickerSnapshot>(ticker).is_err());
2201
2202        let mut slim = load_json("perps/ws_ticker_slim_eth.json")["instrument_ticker"].clone();
2203        slim[if field == "index_price" { "I" } else { "M" }] = invalid;
2204        assert!(serde_json::from_value::<DeriveTickerSnapshot>(slim).is_err());
2205    }
2206
2207    #[rstest]
2208    #[case("open_price")]
2209    #[case("high_price")]
2210    #[case("low_price")]
2211    #[case("close_price")]
2212    #[case("volume_usd")]
2213    #[case("volume_contracts")]
2214    fn test_required_candle_decimals_reject_missing_tokens(
2215        #[case] field: &str,
2216        #[values(Value::Null, json!(""))] invalid: Value,
2217    ) {
2218        let mut candle = load_json("perps/http_public_candles_eth.json")[0].clone();
2219        candle[field] = invalid;
2220        assert!(serde_json::from_value::<DerivePublicCandle>(candle).is_err());
2221    }
2222
2223    #[rstest]
2224    fn test_required_funding_decimal_rejects_missing_tokens(
2225        #[values(Value::Null, json!(""))] invalid: Value,
2226    ) {
2227        let mut rates = load_json("perps/http_public_funding_rate_history_eth.json");
2228        rates["funding_rate_history"][0]["funding_rate"] = invalid;
2229        assert!(serde_json::from_value::<DerivePublicFundingRateHistoryResult>(rates).is_err());
2230    }
2231
2232    #[rstest]
2233    fn test_required_market_data_decimals_preserve_zero(
2234        #[values(json!(0), json!("0"))] zero: Value,
2235    ) {
2236        let mut ticker = load_json("perps/http_ticker_eth_snapshot.json");
2237        ticker["index_price"] = zero.clone();
2238        ticker["mark_price"] = zero.clone();
2239        let full: DeriveTicker = serde_json::from_value(ticker.clone()).unwrap();
2240        let snapshot: DeriveTickerSnapshot = serde_json::from_value(ticker).unwrap();
2241        let mut candle = load_json("perps/http_public_candles_eth.json")[0].clone();
2242        for field in [
2243            "open_price",
2244            "high_price",
2245            "low_price",
2246            "close_price",
2247            "volume_usd",
2248            "volume_contracts",
2249        ] {
2250            candle[field] = zero.clone();
2251        }
2252
2253        let candle: DerivePublicCandle = serde_json::from_value(candle).unwrap();
2254        let mut rates = load_json("perps/http_public_funding_rate_history_eth.json");
2255        rates["funding_rate_history"][0]["funding_rate"] = zero;
2256        let rates: DerivePublicFundingRateHistoryResult = serde_json::from_value(rates).unwrap();
2257
2258        assert_eq!(full.index_price, Decimal::ZERO);
2259        assert_eq!(full.mark_price, Decimal::ZERO);
2260        assert_eq!(snapshot.index_price, Decimal::ZERO);
2261        assert_eq!(snapshot.mark_price, Decimal::ZERO);
2262        assert_eq!(candle.open_price, Decimal::ZERO);
2263        assert_eq!(candle.high_price, Decimal::ZERO);
2264        assert_eq!(candle.low_price, Decimal::ZERO);
2265        assert_eq!(candle.close_price, Decimal::ZERO);
2266        assert_eq!(candle.volume_usd, Decimal::ZERO);
2267        assert_eq!(candle.volume_contracts, Decimal::ZERO);
2268        assert_eq!(rates.funding_rate_history[0].funding_rate, Decimal::ZERO);
2269    }
2270
2271    #[rstest]
2272    fn test_public_candles_decode_array() {
2273        // The venue ships `result` as a flat array; the HTTP client decodes
2274        // directly into `Vec<DerivePublicCandle>`. The fixture mirrors that
2275        // wire shape.
2276        let body = load_json("perps/http_public_candles_eth.json");
2277        let candles: Vec<DerivePublicCandle> = serde_json::from_value(body).unwrap();
2278        assert_eq!(candles.len(), 3);
2279        let first = &candles[0];
2280        assert_eq!(first.open_price.to_string(), "3500.0");
2281        assert_eq!(first.high_price.to_string(), "3501.5");
2282        assert_eq!(first.low_price.to_string(), "3499.0");
2283        assert_eq!(first.close_price.to_string(), "3501.0");
2284        assert_eq!(first.volume_usd.to_string(), "12345.6");
2285        assert_eq!(first.volume_contracts.to_string(), "3.527");
2286        // Distinct `timestamp` vs `timestamp_bucket` so a field-swap mutation
2287        // in any downstream parser is detectable.
2288        assert_eq!(first.timestamp, 1_700_000_007);
2289        assert_eq!(first.timestamp_bucket, 1_700_000_000);
2290        assert_eq!(candles.last().unwrap().timestamp_bucket, 1_700_001_800);
2291    }
2292
2293    #[rstest]
2294    fn test_positions_result_envelope_decodes() {
2295        let body = load_json("perps/http_positions_result_eth.json");
2296        let result: DerivePositionsResult = serde_json::from_value(body).unwrap();
2297        assert_eq!(result.positions.len(), 1);
2298        assert_eq!(result.subaccount_id, 42);
2299        assert_eq!(result.positions[0].instrument_name, "ETH-PERP");
2300        assert!(result.positions[0].leverage.is_none());
2301        assert!(result.positions[0].liquidation_price.is_none());
2302    }
2303}