1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct JsonRpcRequest<P> {
65 pub jsonrpc: &'static str,
67 pub id: u64,
69 pub method: &'static str,
71 pub params: P,
73}
74
75impl<P> JsonRpcRequest<P> {
76 #[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#[derive(Debug, Clone, Deserialize)]
91#[serde(bound(deserialize = "R: Deserialize<'de>"))]
92pub struct JsonRpcResponse<R> {
93 #[serde(default, deserialize_with = "deserialize_optional_jsonrpc_id")]
96 pub id: Option<u64>,
97 #[serde(default, deserialize_with = "deserialize_present_jsonrpc_result")]
99 pub result: Option<R>,
100 #[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#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
133pub struct JsonRpcError {
134 pub code: i64,
136 pub message: String,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub data: Option<Value>,
141}
142
143#[derive(Clone, Debug, Serialize, Deserialize)]
146pub struct DeriveOptionPublicDetails {
147 pub expiry: i64,
149 pub index: Ustr,
151 pub option_type: DeriveOptionKind,
153 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
155 pub settlement_price: Option<Decimal>,
156 #[serde(deserialize_with = "deserialize_decimal")]
158 pub strike: Decimal,
159}
160
161#[derive(Clone, Debug, Serialize, Deserialize)]
164pub struct DerivePerpPublicDetails {
165 #[serde(deserialize_with = "deserialize_decimal")]
167 pub aggregate_funding: Decimal,
168 #[serde(deserialize_with = "deserialize_decimal")]
170 pub funding_rate: Decimal,
171 pub index: Ustr,
173 #[serde(deserialize_with = "deserialize_decimal")]
175 pub max_rate_per_hour: Decimal,
176 #[serde(deserialize_with = "deserialize_decimal")]
178 pub min_rate_per_hour: Decimal,
179 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
181 pub static_interest_rate: Option<Decimal>,
182}
183
184#[derive(Clone, Debug, Serialize, Deserialize)]
186#[serde(remote = "Self")]
187pub struct DeriveInstrument {
188 #[serde(deserialize_with = "deserialize_decimal")]
190 pub amount_step: Decimal,
191 pub base_asset_address: Ustr,
193 pub base_asset_sub_id: Ustr,
195 pub base_currency: Ustr,
197 #[serde(deserialize_with = "deserialize_decimal")]
199 pub base_fee: Decimal,
200 pub instrument_name: Ustr,
202 pub instrument_type: DeriveInstrumentType,
204 pub is_active: bool,
206 #[serde(deserialize_with = "deserialize_decimal")]
208 pub maker_fee_rate: Decimal,
209 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
211 pub mark_price_fee_rate_cap: Option<Decimal>,
212 #[serde(deserialize_with = "deserialize_decimal")]
214 pub maximum_amount: Decimal,
215 #[serde(deserialize_with = "deserialize_decimal")]
218 pub minimum_amount: Decimal,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub option_details: Option<DeriveOptionPublicDetails>,
222 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub perp_details: Option<DerivePerpPublicDetails>,
225 pub quote_currency: Ustr,
227 pub scheduled_activation: i64,
229 pub scheduled_deactivation: i64,
231 #[serde(deserialize_with = "deserialize_decimal")]
233 pub taker_fee_rate: Decimal,
234 #[serde(deserialize_with = "deserialize_decimal")]
236 pub tick_size: Decimal,
237 #[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 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#[derive(Clone, Debug, Serialize, Deserialize)]
262pub struct DeriveAggregateTradingStats {
263 #[serde(alias = "c", deserialize_with = "deserialize_decimal")]
265 pub contract_volume: Decimal,
266 #[serde(alias = "h", deserialize_with = "deserialize_decimal")]
268 pub high: Decimal,
269 #[serde(alias = "l", deserialize_with = "deserialize_decimal")]
271 pub low: Decimal,
272 #[serde(alias = "n", deserialize_with = "deserialize_decimal")]
274 pub num_trades: Decimal,
275 #[serde(alias = "oi", deserialize_with = "deserialize_decimal")]
277 pub open_interest: Decimal,
278 #[serde(alias = "p", deserialize_with = "deserialize_decimal")]
280 pub percent_change: Decimal,
281 #[serde(alias = "pr", deserialize_with = "deserialize_decimal")]
283 pub usd_change: Decimal,
284}
285
286#[derive(Clone, Debug, Serialize, Deserialize)]
288pub struct DeriveOptionPricing {
289 #[serde(alias = "ai", deserialize_with = "deserialize_decimal")]
291 pub ask_iv: Decimal,
292 #[serde(alias = "bi", deserialize_with = "deserialize_decimal")]
294 pub bid_iv: Decimal,
295 #[serde(alias = "d", deserialize_with = "deserialize_decimal")]
297 pub delta: Decimal,
298 #[serde(alias = "f", deserialize_with = "deserialize_decimal")]
300 pub forward_price: Decimal,
301 #[serde(alias = "g", deserialize_with = "deserialize_decimal")]
303 pub gamma: Decimal,
304 #[serde(alias = "i", deserialize_with = "deserialize_decimal")]
306 pub iv: Decimal,
307 #[serde(alias = "m", deserialize_with = "deserialize_decimal")]
309 pub mark_price: Decimal,
310 #[serde(alias = "r", deserialize_with = "deserialize_decimal")]
312 pub rho: Decimal,
313 #[serde(alias = "t", deserialize_with = "deserialize_decimal")]
315 pub theta: Decimal,
316 #[serde(alias = "v", deserialize_with = "deserialize_decimal")]
318 pub vega: Decimal,
319}
320
321#[derive(Clone, Debug, Serialize, Deserialize)]
323pub struct DeriveTickerSnapshot {
324 #[serde(default)]
326 pub instrument_name: Ustr,
327 #[serde(
329 rename = "A",
330 alias = "best_ask_amount",
331 deserialize_with = "deserialize_decimal"
332 )]
333 pub best_ask_amount: Decimal,
334 #[serde(
336 rename = "a",
337 alias = "best_ask_price",
338 deserialize_with = "deserialize_decimal"
339 )]
340 pub best_ask_price: Decimal,
341 #[serde(
343 rename = "B",
344 alias = "best_bid_amount",
345 deserialize_with = "deserialize_decimal"
346 )]
347 pub best_bid_amount: Decimal,
348 #[serde(
350 rename = "b",
351 alias = "best_bid_price",
352 deserialize_with = "deserialize_decimal"
353 )]
354 pub best_bid_price: Decimal,
355 #[serde(
357 rename = "f",
358 alias = "funding_rate",
359 default,
360 deserialize_with = "deserialize_optional_decimal"
361 )]
362 pub funding_rate: Option<Decimal>,
363 #[serde(
365 rename = "I",
366 alias = "index_price",
367 deserialize_with = "deserialize_decimal_token"
368 )]
369 pub index_price: Decimal,
370 #[serde(
372 rename = "M",
373 alias = "mark_price",
374 deserialize_with = "deserialize_decimal_token"
375 )]
376 pub mark_price: Decimal,
377 #[serde(
379 rename = "maxp",
380 alias = "max_price",
381 deserialize_with = "deserialize_decimal"
382 )]
383 pub max_price: Decimal,
384 #[serde(
386 rename = "minp",
387 alias = "min_price",
388 deserialize_with = "deserialize_decimal"
389 )]
390 pub min_price: Decimal,
391 #[serde(default)]
393 pub option_pricing: Option<DeriveOptionPricing>,
394 #[serde(default)]
396 pub stats: Option<DeriveAggregateTradingStats>,
397 #[serde(rename = "t", alias = "timestamp")]
399 pub timestamp: i64,
400}
401
402#[derive(Clone, Debug, Serialize, Deserialize)]
404pub struct DeriveTickersResult {
405 pub tickers: HashMap<String, DeriveTickerSnapshot>,
407}
408
409#[derive(Clone, Debug, Serialize, Deserialize)]
412pub struct DeriveTicker {
413 #[serde(deserialize_with = "deserialize_decimal")]
415 pub amount_step: Decimal,
416 pub base_asset_address: Ustr,
418 pub base_asset_sub_id: Ustr,
420 pub base_currency: Ustr,
422 #[serde(deserialize_with = "deserialize_decimal")]
424 pub base_fee: Decimal,
425 #[serde(deserialize_with = "deserialize_decimal")]
427 pub best_ask_amount: Decimal,
428 #[serde(deserialize_with = "deserialize_decimal")]
430 pub best_ask_price: Decimal,
431 #[serde(deserialize_with = "deserialize_decimal")]
433 pub best_bid_amount: Decimal,
434 #[serde(deserialize_with = "deserialize_decimal")]
436 pub best_bid_price: Decimal,
437 #[serde(deserialize_with = "deserialize_decimal_token")]
439 pub index_price: Decimal,
440 pub instrument_name: Ustr,
442 pub instrument_type: DeriveInstrumentType,
444 pub is_active: bool,
446 #[serde(deserialize_with = "deserialize_decimal")]
448 pub maker_fee_rate: Decimal,
449 #[serde(deserialize_with = "deserialize_decimal_token")]
451 pub mark_price: Decimal,
452 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
454 pub mark_price_fee_rate_cap: Option<Decimal>,
455 #[serde(deserialize_with = "deserialize_decimal")]
457 pub max_price: Decimal,
458 #[serde(deserialize_with = "deserialize_decimal")]
460 pub maximum_amount: Decimal,
461 #[serde(deserialize_with = "deserialize_decimal")]
463 pub min_price: Decimal,
464 #[serde(deserialize_with = "deserialize_decimal")]
466 pub minimum_amount: Decimal,
467 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub option_details: Option<DeriveOptionPublicDetails>,
470 #[serde(default, skip_serializing_if = "Option::is_none")]
472 pub option_pricing: Option<DeriveOptionPricing>,
473 #[serde(default, skip_serializing_if = "Option::is_none")]
475 pub perp_details: Option<DerivePerpPublicDetails>,
476 pub quote_currency: Ustr,
478 pub scheduled_activation: i64,
480 pub scheduled_deactivation: i64,
482 #[serde(default, skip_serializing_if = "Option::is_none")]
484 pub stats: Option<DeriveAggregateTradingStats>,
485 #[serde(deserialize_with = "deserialize_decimal")]
487 pub taker_fee_rate: Decimal,
488 #[serde(deserialize_with = "deserialize_decimal")]
490 pub tick_size: Decimal,
491 pub timestamp: i64,
493}
494
495#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct DeriveOrder {
499 #[serde(deserialize_with = "deserialize_decimal_token")]
501 pub amount: Decimal,
502 #[serde(deserialize_with = "deserialize_decimal_token")]
504 pub average_price: Decimal,
505 #[serde(default = "cancel_reason_empty")]
507 pub cancel_reason: DeriveOrderCancelReason,
508 pub creation_timestamp: i64,
510 pub direction: DeriveOrderSide,
512 #[serde(deserialize_with = "deserialize_decimal_token")]
514 pub filled_amount: Decimal,
515 pub instrument_name: Ustr,
517 pub is_transfer: bool,
519 #[serde(default)]
521 pub label: Ustr,
522 pub last_update_timestamp: i64,
524 #[serde(deserialize_with = "deserialize_decimal_token")]
526 pub limit_price: Decimal,
527 #[serde(deserialize_with = "deserialize_decimal_token")]
529 pub max_fee: Decimal,
530 pub mmp: bool,
532 #[serde(
534 serialize_with = "crate::signing::nonce::serialize_nonce",
535 deserialize_with = "crate::signing::nonce::deserialize_nonce"
536 )]
537 pub nonce: u64,
538 #[serde(deserialize_with = "deserialize_decimal_token")]
540 pub order_fee: Decimal,
541 pub order_id: String,
543 pub order_status: DeriveOrderStatus,
545 pub order_type: DeriveOrderType,
547 #[serde(default, skip_serializing_if = "Option::is_none")]
549 pub quote_id: Option<String>,
550 #[serde(default, skip_serializing_if = "Option::is_none")]
552 pub replaced_order_id: Option<String>,
553 pub signature: SecretString,
555 pub signature_expiry_sec: i64,
557 pub signer: Ustr,
559 pub subaccount_id: i64,
561 pub time_in_force: DeriveTimeInForce,
563 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
565 pub trigger_price: Option<Decimal>,
566 #[serde(default, skip_serializing_if = "Option::is_none")]
568 pub trigger_price_type: Option<DeriveTriggerPriceType>,
569 #[serde(default, skip_serializing_if = "Option::is_none")]
571 pub trigger_reject_message: Option<String>,
572 #[serde(default, skip_serializing_if = "Option::is_none")]
574 pub trigger_type: Option<DeriveTriggerType>,
575}
576
577#[derive(Clone, Debug, Serialize, Deserialize)]
579pub struct DeriveOrderResult {
580 pub order: DeriveOrder,
582 #[serde(default, deserialize_with = "deserialize_salvaged_vec")]
584 pub trades: Vec<DeriveTrade>,
585}
586
587#[derive(Clone, Debug, Serialize, Deserialize)]
589pub struct DeriveReplaceResult {
590 #[serde(default, skip_serializing_if = "Option::is_none")]
592 pub order: Option<DeriveOrder>,
593 #[serde(default, skip_serializing_if = "Option::is_none")]
595 pub cancelled_order: Option<DeriveOrder>,
596 #[serde(default, skip_serializing_if = "Option::is_none")]
598 pub create_order_error: Option<JsonRpcError>,
599}
600
601#[derive(Clone, Debug)]
603pub enum DeriveReplaceOutcome {
604 Replaced(DeriveOrder),
606 Canceled {
608 cancelled_order: DeriveOrder,
610 create_order_error: JsonRpcError,
612 },
613}
614
615impl DeriveReplaceResult {
616 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
722pub struct DeriveCancelByLabelResult {
723 pub cancelled_orders: i64,
725}
726
727pub type DeriveCancelByInstrumentResult = DeriveCancelByLabelResult;
729
730#[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#[derive(Clone, Debug, Serialize, Deserialize)]
752pub struct DerivePosition {
753 #[serde(deserialize_with = "deserialize_decimal_token")]
755 pub amount: Decimal,
756 #[serde(deserialize_with = "deserialize_decimal_token")]
759 pub average_price: Decimal,
760 pub creation_timestamp: i64,
762 #[serde(deserialize_with = "deserialize_decimal_token")]
764 pub cumulative_funding: Decimal,
765 #[serde(deserialize_with = "deserialize_decimal_token")]
767 pub delta: Decimal,
768 #[serde(deserialize_with = "deserialize_decimal_token")]
770 pub gamma: Decimal,
771 #[serde(deserialize_with = "deserialize_decimal_token")]
773 pub index_price: Decimal,
774 #[serde(deserialize_with = "deserialize_decimal_token")]
776 pub initial_margin: Decimal,
777 pub instrument_name: Ustr,
779 pub instrument_type: DeriveInstrumentType,
781 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
783 pub leverage: Option<Decimal>,
784 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
786 pub liquidation_price: Option<Decimal>,
787 #[serde(deserialize_with = "deserialize_decimal_token")]
789 pub maintenance_margin: Decimal,
790 #[serde(deserialize_with = "deserialize_decimal_token")]
792 pub mark_price: Decimal,
793 #[serde(deserialize_with = "deserialize_decimal_token")]
795 pub mark_value: Decimal,
796 #[serde(deserialize_with = "deserialize_decimal_token")]
798 pub net_settlements: Decimal,
799 #[serde(deserialize_with = "deserialize_decimal_token")]
801 pub open_orders_margin: Decimal,
802 #[serde(deserialize_with = "deserialize_decimal_token")]
804 pub pending_funding: Decimal,
805 #[serde(deserialize_with = "deserialize_decimal_token")]
807 pub realized_pnl: Decimal,
808 #[serde(deserialize_with = "deserialize_decimal_token")]
810 pub theta: Decimal,
811 #[serde(deserialize_with = "deserialize_decimal_token")]
813 pub unrealized_pnl: Decimal,
814 #[serde(deserialize_with = "deserialize_decimal_token")]
816 pub vega: Decimal,
817}
818
819#[derive(Clone, Debug, Serialize, Deserialize)]
821pub struct DeriveCollateral {
822 #[serde(
824 deserialize_with = "deserialize_decimal_token",
825 serialize_with = "serialize_decimal_as_str"
826 )]
827 pub amount: Decimal,
828 pub asset_name: Ustr,
830 pub asset_type: DeriveAssetType,
832 #[serde(
834 deserialize_with = "deserialize_decimal_token",
835 serialize_with = "serialize_decimal_as_str"
836 )]
837 pub cumulative_interest: Decimal,
838 pub currency: Ustr,
840 #[serde(
842 deserialize_with = "deserialize_decimal_token",
843 serialize_with = "serialize_decimal_as_str"
844 )]
845 pub initial_margin: Decimal,
846 #[serde(
848 deserialize_with = "deserialize_decimal_token",
849 serialize_with = "serialize_decimal_as_str"
850 )]
851 pub maintenance_margin: Decimal,
852 #[serde(
854 deserialize_with = "deserialize_decimal_token",
855 serialize_with = "serialize_decimal_as_str"
856 )]
857 pub mark_price: Decimal,
858 #[serde(
860 deserialize_with = "deserialize_decimal_token",
861 serialize_with = "serialize_decimal_as_str"
862 )]
863 pub mark_value: Decimal,
864 #[serde(
866 deserialize_with = "deserialize_decimal_token",
867 serialize_with = "serialize_decimal_as_str"
868 )]
869 pub pending_interest: Decimal,
870}
871
872#[derive(Clone, Debug, Serialize, Deserialize)]
874pub struct DeriveSubaccount {
875 pub collaterals: Vec<DeriveCollateral>,
877 #[serde(deserialize_with = "deserialize_decimal_token")]
879 pub collaterals_initial_margin: Decimal,
880 #[serde(deserialize_with = "deserialize_decimal_token")]
882 pub collaterals_maintenance_margin: Decimal,
883 #[serde(deserialize_with = "deserialize_decimal_token")]
885 pub collaterals_value: Decimal,
886 pub currency: Vec<Ustr>,
888 pub failed_to_fetch: bool,
890 #[serde(deserialize_with = "deserialize_decimal_token")]
893 pub initial_margin: Decimal,
894 pub is_under_liquidation: bool,
896 #[serde(default, skip_serializing_if = "Option::is_none")]
898 pub label: Option<String>,
899 #[serde(deserialize_with = "deserialize_decimal_token")]
901 pub maintenance_margin: Decimal,
902 pub manager_id: u32,
904 pub margin_type: String,
906 #[serde(deserialize_with = "deserialize_decimal_token")]
908 pub mm_credits: Decimal,
909 pub open_orders: Vec<DeriveOrder>,
911 #[serde(deserialize_with = "deserialize_decimal_token")]
913 pub open_orders_margin: Decimal,
914 pub positions: Vec<DerivePosition>,
916 #[serde(deserialize_with = "deserialize_decimal_token")]
918 pub positions_initial_margin: Decimal,
919 #[serde(deserialize_with = "deserialize_decimal_token")]
921 pub positions_maintenance_margin: Decimal,
922 #[serde(deserialize_with = "deserialize_decimal_token")]
924 pub positions_value: Decimal,
925 #[serde(deserialize_with = "deserialize_decimal_token")]
927 pub projected_margin_change: Decimal,
928 pub risk_universe_id: u32,
930 pub subaccount_id: i64,
932 #[serde(deserialize_with = "deserialize_decimal_token")]
934 pub subaccount_value: Decimal,
935 pub vault_deposit_holds: Vec<DeriveVaultDepositHold>,
937}
938
939#[derive(Debug, Clone, Serialize, Deserialize)]
941pub struct DeriveVaultDepositHold {
942 #[serde(
944 deserialize_with = "deserialize_decimal_token",
945 serialize_with = "serialize_decimal_as_str"
946 )]
947 pub amount: Decimal,
948 pub asset_name: Ustr,
950 pub currency: Ustr,
952 pub vault_id: u64,
954}
955
956#[derive(Clone, Debug, Serialize, Deserialize)]
959pub struct DeriveTrade {
960 pub direction: DeriveOrderSide,
962 #[serde(deserialize_with = "deserialize_decimal")]
964 pub index_price: Decimal,
965 pub instrument_name: Ustr,
967 pub is_transfer: bool,
969 #[serde(default)]
971 pub label: Ustr,
972 pub liquidity_role: DeriveLiquidityRole,
974 #[serde(deserialize_with = "deserialize_decimal")]
976 pub mark_price: Decimal,
977 pub order_id: String,
979 #[serde(default, skip_serializing_if = "Option::is_none")]
981 pub quote_id: Option<String>,
982 #[serde(deserialize_with = "deserialize_decimal")]
984 pub realized_pnl: Decimal,
985 pub subaccount_id: i64,
987 pub timestamp: i64,
989 #[serde(deserialize_with = "deserialize_decimal_token")]
991 pub trade_amount: Decimal,
992 #[serde(deserialize_with = "deserialize_decimal_token")]
994 pub trade_fee: Decimal,
995 pub trade_id: String,
997 #[serde(deserialize_with = "deserialize_decimal_token")]
999 pub trade_price: Decimal,
1000 #[serde(default, skip_serializing_if = "Option::is_none")]
1002 pub tx_hash: Option<String>,
1003 #[serde(default, skip_serializing_if = "Option::is_none")]
1005 pub batch_status: Option<String>,
1006 #[serde(default, skip_serializing_if = "Option::is_none")]
1008 pub op_uuid: Option<String>,
1009 #[serde(default, skip_serializing_if = "Option::is_none")]
1011 pub wallet: Option<Ustr>,
1012}
1013
1014#[derive(Clone, Debug, Serialize, Deserialize)]
1020pub struct DerivePublicTrade {
1021 pub direction: DeriveOrderSide,
1023 #[serde(deserialize_with = "deserialize_decimal")]
1025 pub index_price: Decimal,
1026 pub instrument_name: Ustr,
1028 #[serde(default, skip_serializing_if = "Option::is_none")]
1032 pub liquidity_role: Option<DeriveLiquidityRole>,
1033 #[serde(deserialize_with = "deserialize_decimal")]
1035 pub mark_price: Decimal,
1036 #[serde(default, skip_serializing_if = "Option::is_none")]
1038 pub quote_id: Option<String>,
1039 #[serde(default, skip_serializing_if = "Option::is_none")]
1041 pub rfq_id: Option<String>,
1042 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
1044 pub realized_pnl: Option<Decimal>,
1045 #[serde(default, skip_serializing_if = "Option::is_none")]
1047 pub subaccount_id: Option<i64>,
1048 pub timestamp: i64,
1050 #[serde(deserialize_with = "deserialize_decimal_token")]
1052 pub trade_amount: Decimal,
1053 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
1055 pub trade_fee: Option<Decimal>,
1056 pub trade_id: String,
1058 #[serde(deserialize_with = "deserialize_decimal_token")]
1060 pub trade_price: Decimal,
1061 #[serde(default, skip_serializing_if = "Option::is_none")]
1063 pub tx_hash: Option<String>,
1064 #[serde(default, skip_serializing_if = "Option::is_none")]
1066 pub batch_status: Option<String>,
1067 #[serde(default, skip_serializing_if = "Option::is_none")]
1069 pub op_uuid: Option<String>,
1070 #[serde(default, skip_serializing_if = "Option::is_none")]
1072 pub wallet: Option<Ustr>,
1073}
1074
1075#[derive(Clone, Debug, Serialize, Deserialize)]
1077pub struct DerivePaginationInfo {
1078 pub count: i64,
1080 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#[derive(Clone, Debug, Serialize, Deserialize)]
1092pub struct DeriveOrdersResult {
1093 pub orders: Vec<DeriveOrder>,
1096 pub pagination: DerivePaginationInfo,
1098 pub subaccount_id: i64,
1100}
1101
1102#[derive(Clone, Debug, Serialize, Deserialize)]
1104pub struct DeriveOpenOrdersResult {
1105 pub orders: Vec<DeriveOrder>,
1108 pub subaccount_id: i64,
1110}
1111
1112#[derive(Clone, Debug, Serialize)]
1114pub struct DeriveTradesResult {
1115 pub trades: Vec<DeriveTrade>,
1117 pub pagination: DerivePaginationInfo,
1119 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#[derive(Clone, Debug, Serialize, Deserialize)]
1163pub struct DerivePublicTradesResult {
1164 pub trades: Vec<DerivePublicTrade>,
1166 pub pagination: DerivePaginationInfo,
1168}
1169
1170#[derive(Clone, Debug, Serialize, Deserialize)]
1177pub struct DerivePublicCandle {
1178 #[serde(deserialize_with = "deserialize_decimal_token")]
1180 pub open_price: Decimal,
1181 #[serde(deserialize_with = "deserialize_decimal_token")]
1183 pub high_price: Decimal,
1184 #[serde(deserialize_with = "deserialize_decimal_token")]
1186 pub low_price: Decimal,
1187 #[serde(deserialize_with = "deserialize_decimal_token")]
1189 pub close_price: Decimal,
1190 #[serde(deserialize_with = "deserialize_decimal_token")]
1192 pub volume_usd: Decimal,
1193 #[serde(deserialize_with = "deserialize_decimal_token")]
1195 pub volume_contracts: Decimal,
1196 pub timestamp: i64,
1198 pub timestamp_bucket: i64,
1200}
1201
1202#[derive(Clone, Debug, Serialize, Deserialize)]
1204pub struct DerivePublicFundingRate {
1205 #[serde(deserialize_with = "deserialize_decimal_token")]
1207 pub funding_rate: Decimal,
1208 pub timestamp: i64,
1210}
1211
1212#[derive(Clone, Debug, Serialize, Deserialize)]
1214pub struct DerivePublicFundingRateHistoryResult {
1215 pub funding_rate_history: Vec<DerivePublicFundingRate>,
1217}
1218
1219#[derive(Clone, Debug, Serialize, Deserialize)]
1221pub struct DerivePositionsResult {
1222 pub positions: Vec<DerivePosition>,
1227 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 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 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 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 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 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 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 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 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}