nautilus-derive 0.58.0

Derive integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! HTTP payload models and JSON-RPC envelope types for the Derive REST API.
//!
//! Envelope types (`JsonRpcRequest`, `JsonRpcResponse`, `JsonRpcError`) cover
//! the wire framing shared with the WebSocket transport. Payload structs below
//! mirror the response shapes generated by Derive's upstream Rust SDK at
//! [`derivexyz/cockpit`](https://github.com/derivexyz/cockpit/tree/master/orderbook-types/src/generated),
//! adapted to project conventions:
//!
//! - `bigdecimal::BigDecimal` -> [`rust_decimal::Decimal`] via the project's
//!   `deserialize_decimal` / `deserialize_optional_decimal` functions.
//! - Hot-path string identifiers (`instrument_name`, `currency`) -> [`Ustr`]
//!   for interning across decoded messages.
//! - `uuid::Uuid` fields kept as [`String`] to avoid a fresh dep when only a
//!   couple of methods carry one.

use std::collections::HashMap;

use nautilus_core::serialization::{deserialize_decimal, deserialize_optional_decimal};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use ustr::Ustr;

use crate::common::{
    enums::{
        DeriveAssetType, DeriveInstrumentType, DeriveLiquidityRole, DeriveMarginType,
        DeriveOptionKind, DeriveOrderCancelReason, DeriveOrderSide, DeriveOrderStatus,
        DeriveOrderType, DeriveTimeInForce, DeriveTriggerPriceType, DeriveTriggerType,
        DeriveTxStatus,
    },
    parse::{deserialize_derive_decimal, deserialize_optional_derive_decimal},
};

/// Outbound JSON-RPC request frame. Used as-is by the WebSocket transport; the
/// REST transport addresses the method by URL path and sends only `params` on
/// the wire, but keeps the same `id` for telemetry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcRequest<P> {
    /// JSON-RPC version tag; constant `"2.0"`.
    pub jsonrpc: &'static str,
    /// Correlator chosen by the client.
    pub id: u64,
    /// Method name (e.g. `public/get_instruments`).
    pub method: &'static str,
    /// Method-specific params payload.
    pub params: P,
}

impl<P> JsonRpcRequest<P> {
    /// Constructs a `2.0` request with the given correlator, method, and params.
    #[must_use]
    pub fn new(id: u64, method: &'static str, params: P) -> Self {
        Self {
            jsonrpc: "2.0",
            id,
            method,
            params,
        }
    }
}

/// Inbound JSON-RPC response frame. Exactly one of `result` or `error` is set
/// by the venue.
#[derive(Debug, Clone, Deserialize)]
pub struct JsonRpcResponse<R> {
    /// Correlator echoing the request `id`. The Derive REST API may omit this
    /// for some endpoints, hence `Option`.
    #[serde(default, deserialize_with = "deserialize_optional_jsonrpc_id")]
    pub id: Option<u64>,
    /// Result payload on success.
    #[serde(default = "Option::default")]
    pub result: Option<R>,
    /// Error payload on failure.
    #[serde(default)]
    pub error: Option<JsonRpcError>,
}

fn deserialize_optional_jsonrpc_id<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Option::<Value>::deserialize(deserializer)?;
    match value {
        None | Some(Value::Null) => Ok(None),
        Some(Value::Number(number)) => number
            .as_u64()
            .map(Some)
            .ok_or_else(|| serde::de::Error::custom("JSON-RPC id must be an unsigned integer")),
        Some(Value::String(value)) => Ok(value.parse::<u64>().ok()),
        Some(other) => Err(serde::de::Error::custom(format!(
            "JSON-RPC id must be an unsigned integer or string, was {other}"
        ))),
    }
}

/// JSON-RPC error object as returned by Derive on failed requests.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct JsonRpcError {
    /// Numeric error code defined by the venue.
    pub code: i64,
    /// Human-readable error message.
    pub message: String,
    /// Optional structured diagnostic payload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

/// Option-specific fields appearing on `public/get_instruments` and legacy
/// full ticker payloads when the instrument is an option.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveOptionPublicDetails {
    /// Option expiry as a UNIX timestamp in seconds.
    pub expiry: i64,
    /// Underlying index identifier (e.g. `"ETH-USD"`).
    pub index: Ustr,
    /// Call or put.
    pub option_type: DeriveOptionKind,
    /// Final settlement price, populated after expiry.
    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
    pub settlement_price: Option<Decimal>,
    /// Strike price in quote currency.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub strike: Decimal,
}

/// Perp-specific fields appearing on `public/get_instruments` and legacy full
/// ticker payloads when the instrument is a perpetual.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePerpPublicDetails {
    /// Cumulative funding accrued since contract inception.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub aggregate_funding: Decimal,
    /// Current funding rate per funding interval.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub funding_rate: Decimal,
    /// Underlying index identifier (e.g. `"ETH-USD"`).
    pub index: Ustr,
    /// Maximum allowable funding rate per hour.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub max_rate_per_hour: Decimal,
    /// Minimum allowable funding rate per hour.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub min_rate_per_hour: Decimal,
    /// Static interest-rate component of the funding curve.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub static_interest_rate: Decimal,
}

/// Instrument definition returned by `public/get_instruments`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveInstrument {
    /// Minimum increment of the `amount` field for orders.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub amount_step: Decimal,
    /// On-chain address of the base asset.
    pub base_asset_address: Ustr,
    /// Sub-id of the base asset within the asset module (decimal string).
    pub base_asset_sub_id: Ustr,
    /// Underlying currency (e.g. `"ETH"`).
    pub base_currency: Ustr,
    /// Base flat fee in USD.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub base_fee: Decimal,
    /// Canonical instrument name (e.g. `"ETH-PERP"`, `"ETH-20250627-3500-C"`).
    pub instrument_name: Ustr,
    /// Instrument category.
    pub instrument_type: DeriveInstrumentType,
    /// Whether the instrument is currently tradable.
    pub is_active: bool,
    /// Maker fee rate (fraction).
    #[serde(deserialize_with = "deserialize_decimal")]
    pub maker_fee_rate: Decimal,
    /// Optional cap on the mark-price-derived fee rate.
    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
    pub mark_price_fee_rate_cap: Option<Decimal>,
    /// Maximum allowed order amount.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub maximum_amount: Decimal,
    /// Minimum allowed order amount.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub minimum_amount: Decimal,
    /// Option-specific details (populated when `instrument_type == option`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub option_details: Option<DeriveOptionPublicDetails>,
    /// Perp-specific details (populated when `instrument_type == perp`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perp_details: Option<DerivePerpPublicDetails>,
    /// Quote currency (e.g. `"USDC"`).
    pub quote_currency: Ustr,
    /// Scheduled activation timestamp (UNIX ms; 0 if already active).
    pub scheduled_activation: i64,
    /// Scheduled deactivation timestamp (UNIX ms; `i64::MAX` if none).
    pub scheduled_deactivation: i64,
    /// Taker fee rate (fraction).
    #[serde(deserialize_with = "deserialize_decimal")]
    pub taker_fee_rate: Decimal,
    /// Minimum price increment.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub tick_size: Decimal,
}

/// 24-hour rolling trading statistics embedded in ticker payloads.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveAggregateTradingStats {
    /// Total contract volume over the last 24 hours.
    #[serde(alias = "c", deserialize_with = "deserialize_decimal")]
    pub contract_volume: Decimal,
    /// Highest trade price in the last 24 hours.
    #[serde(alias = "h", deserialize_with = "deserialize_decimal")]
    pub high: Decimal,
    /// Lowest trade price in the last 24 hours.
    #[serde(alias = "l", deserialize_with = "deserialize_decimal")]
    pub low: Decimal,
    /// Number of trades over the last 24 hours.
    #[serde(alias = "n", deserialize_with = "deserialize_decimal")]
    pub num_trades: Decimal,
    /// Current total open interest.
    #[serde(alias = "oi", deserialize_with = "deserialize_decimal")]
    pub open_interest: Decimal,
    /// 24-hour percentage price change.
    #[serde(alias = "p", deserialize_with = "deserialize_decimal")]
    pub percent_change: Decimal,
    /// 24-hour USD price change.
    #[serde(alias = "pr", deserialize_with = "deserialize_decimal")]
    pub usd_change: Decimal,
}

/// Option pricing greeks and implied volatilities (option tickers only).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveOptionPricing {
    /// Implied volatility of the current best ask.
    #[serde(alias = "ai", deserialize_with = "deserialize_decimal")]
    pub ask_iv: Decimal,
    /// Implied volatility of the current best bid.
    #[serde(alias = "bi", deserialize_with = "deserialize_decimal")]
    pub bid_iv: Decimal,
    /// Option delta.
    #[serde(alias = "d", deserialize_with = "deserialize_decimal")]
    pub delta: Decimal,
    /// Forward price used in pricing.
    #[serde(alias = "f", deserialize_with = "deserialize_decimal")]
    pub forward_price: Decimal,
    /// Option gamma.
    #[serde(alias = "g", deserialize_with = "deserialize_decimal")]
    pub gamma: Decimal,
    /// Implied volatility of the option.
    #[serde(alias = "i", deserialize_with = "deserialize_decimal")]
    pub iv: Decimal,
    /// Mark price of the option.
    #[serde(alias = "m", deserialize_with = "deserialize_decimal")]
    pub mark_price: Decimal,
    /// Option rho.
    #[serde(alias = "r", deserialize_with = "deserialize_decimal")]
    pub rho: Decimal,
    /// Option theta.
    #[serde(alias = "t", deserialize_with = "deserialize_decimal")]
    pub theta: Decimal,
    /// Option vega.
    #[serde(alias = "v", deserialize_with = "deserialize_decimal")]
    pub vega: Decimal,
}

/// Current ticker snapshot returned by `public/get_tickers` and `ticker_slim`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveTickerSnapshot {
    /// Instrument identifier, injected from the `tickers` map key.
    #[serde(default)]
    pub instrument_name: Ustr,
    /// Best ask amount.
    #[serde(
        rename = "A",
        alias = "best_ask_amount",
        deserialize_with = "deserialize_decimal"
    )]
    pub best_ask_amount: Decimal,
    /// Best ask price.
    #[serde(
        rename = "a",
        alias = "best_ask_price",
        deserialize_with = "deserialize_decimal"
    )]
    pub best_ask_price: Decimal,
    /// Best bid amount.
    #[serde(
        rename = "B",
        alias = "best_bid_amount",
        deserialize_with = "deserialize_decimal"
    )]
    pub best_bid_amount: Decimal,
    /// Best bid price.
    #[serde(
        rename = "b",
        alias = "best_bid_price",
        deserialize_with = "deserialize_decimal"
    )]
    pub best_bid_price: Decimal,
    /// Current hourly funding rate for perpetuals.
    #[serde(
        rename = "f",
        alias = "funding_rate",
        default,
        deserialize_with = "deserialize_optional_decimal"
    )]
    pub funding_rate: Option<Decimal>,
    /// Current oracle index price for the underlying.
    #[serde(
        rename = "I",
        alias = "index_price",
        deserialize_with = "deserialize_decimal"
    )]
    pub index_price: Decimal,
    /// Current mark price.
    #[serde(
        rename = "M",
        alias = "mark_price",
        deserialize_with = "deserialize_decimal"
    )]
    pub mark_price: Decimal,
    /// Maximum allowed price.
    #[serde(
        rename = "maxp",
        alias = "max_price",
        deserialize_with = "deserialize_decimal"
    )]
    pub max_price: Decimal,
    /// Minimum allowed price.
    #[serde(
        rename = "minp",
        alias = "min_price",
        deserialize_with = "deserialize_decimal"
    )]
    pub min_price: Decimal,
    /// Option pricing greeks (options only).
    #[serde(default)]
    pub option_pricing: Option<DeriveOptionPricing>,
    /// 24-hour rolling statistics.
    #[serde(default)]
    pub stats: Option<DeriveAggregateTradingStats>,
    /// Ticker timestamp (UNIX ms).
    #[serde(rename = "t", alias = "timestamp")]
    pub timestamp: i64,
}

/// Result returned by `public/get_tickers`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveTickersResult {
    /// Ticker snapshots keyed by instrument name.
    pub tickers: HashMap<String, DeriveTickerSnapshot>,
}

/// Legacy full ticker snapshot pushed on the deprecated WS
/// `ticker.{instrument_name}.{interval}` channel.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveTicker {
    /// Minimum order amount increment.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub amount_step: Decimal,
    /// On-chain address of the base asset.
    pub base_asset_address: Ustr,
    /// Sub-id of the base asset within the asset module (decimal string).
    pub base_asset_sub_id: Ustr,
    /// Underlying currency.
    pub base_currency: Ustr,
    /// Base flat fee in USD.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub base_fee: Decimal,
    /// Best ask amount.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub best_ask_amount: Decimal,
    /// Best ask price.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub best_ask_price: Decimal,
    /// Best bid amount.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub best_bid_amount: Decimal,
    /// Best bid price.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub best_bid_price: Decimal,
    /// Current oracle index price for the underlying.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub index_price: Decimal,
    /// Instrument identifier.
    pub instrument_name: Ustr,
    /// Instrument category.
    pub instrument_type: DeriveInstrumentType,
    /// Whether the instrument is currently tradable.
    pub is_active: bool,
    /// Maker fee rate.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub maker_fee_rate: Decimal,
    /// Current mark price.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub mark_price: Decimal,
    /// Optional fee-rate cap derived from mark price.
    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
    pub mark_price_fee_rate_cap: Option<Decimal>,
    /// Maximum allowed price.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub max_price: Decimal,
    /// Maximum order amount.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub maximum_amount: Decimal,
    /// Minimum allowed price.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub min_price: Decimal,
    /// Minimum order amount.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub minimum_amount: Decimal,
    /// Option-specific reference data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub option_details: Option<DeriveOptionPublicDetails>,
    /// Option pricing greeks (options only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub option_pricing: Option<DeriveOptionPricing>,
    /// Perp-specific reference data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perp_details: Option<DerivePerpPublicDetails>,
    /// Quote currency.
    pub quote_currency: Ustr,
    /// Scheduled activation timestamp (UNIX ms).
    pub scheduled_activation: i64,
    /// Scheduled deactivation timestamp (UNIX ms).
    pub scheduled_deactivation: i64,
    /// 24-hour rolling statistics. Populated by the WebSocket ticker channel.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stats: Option<DeriveAggregateTradingStats>,
    /// Taker fee rate.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub taker_fee_rate: Decimal,
    /// Minimum price increment.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub tick_size: Decimal,
    /// Ticker timestamp (UNIX ms).
    pub timestamp: i64,
}

/// Order record returned by `private/order`, `private/get_orders`,
/// `private/get_order_history`, and the `{subaccount_id}.orders` WS channel.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveOrder {
    /// Order amount in base units.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub amount: Decimal,
    /// Average fill price.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub average_price: Decimal,
    /// Cancel reason; [`DeriveOrderCancelReason::Empty`] when not cancelled.
    pub cancel_reason: DeriveOrderCancelReason,
    /// Creation timestamp (UNIX ms).
    pub creation_timestamp: i64,
    /// Order side.
    pub direction: DeriveOrderSide,
    /// Cumulative filled amount.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub filled_amount: Decimal,
    /// Instrument identifier.
    pub instrument_name: Ustr,
    /// Whether this order was generated via `private/transfer_position`.
    pub is_transfer: bool,
    /// Free-form user label.
    pub label: Ustr,
    /// Last update timestamp (UNIX ms).
    pub last_update_timestamp: i64,
    /// Limit price in quote currency.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub limit_price: Decimal,
    /// Max fee in quote currency signed into the order.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub max_fee: Decimal,
    /// Whether MMP tags this order.
    pub mmp: bool,
    /// Order nonce.
    pub nonce: i64,
    /// Total fees paid against this order.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub order_fee: Decimal,
    /// Venue-assigned order ID (UUID-shaped).
    pub order_id: String,
    /// Order status.
    pub order_status: DeriveOrderStatus,
    /// Order type.
    pub order_type: DeriveOrderType,
    /// RFQ quote ID when the order is an RFQ execution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote_id: Option<String>,
    /// Replaced order ID when this order resulted from a replace.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replaced_order_id: Option<String>,
    /// 65-byte order signature, `0x`-prefixed hex.
    pub signature: String,
    /// Signature expiry (UNIX seconds).
    pub signature_expiry_sec: i64,
    /// Session-key signer address.
    pub signer: Ustr,
    /// Owning subaccount.
    pub subaccount_id: i64,
    /// Time-in-force.
    pub time_in_force: DeriveTimeInForce,
    /// Trigger price for trigger orders.
    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
    pub trigger_price: Option<Decimal>,
    /// Trigger price source for trigger orders.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_price_type: Option<DeriveTriggerPriceType>,
    /// Trigger rejection text when the trigger worker cannot submit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_reject_message: Option<String>,
    /// Stop-loss or take-profit trigger flag.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_type: Option<DeriveTriggerType>,
}

/// Result envelope returned by `private/order`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveOrderResult {
    /// Accepted order.
    pub order: DeriveOrder,
    /// Trades generated synchronously by the submission, when any.
    #[serde(default)]
    pub trades: Vec<DeriveTrade>,
}

/// Result envelope returned by `private/replace`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveReplaceResult {
    /// Newly accepted replacement order.
    pub order: DeriveOrder,
    /// Cancelled stale order, omitted by some responses and mocks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancelled_order: Option<DeriveOrder>,
}

/// Empty result returned by state-changing cancel endpoints.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct DeriveEmptyResult {}

impl<'de> Deserialize<'de> for DeriveEmptyResult {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        match Value::deserialize(deserializer)? {
            Value::Null | Value::Object(_) => Ok(Self {}),
            Value::String(value) if value == "ok" => Ok(Self {}),
            other => Err(serde::de::Error::custom(format!(
                "empty Derive result must be an object, null, or \"ok\", was {other}"
            ))),
        }
    }
}

/// Position record returned by `private/get_positions` and embedded in
/// `private/get_subaccount` responses.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePosition {
    /// Signed position amount; positive = long, negative = short.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub amount: Decimal,
    /// Average entry price over the lifetime of the position.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub average_price: Decimal,
    /// Position opening timestamp (UNIX ms).
    pub creation_timestamp: i64,
    /// Cumulative funding accrued by this position (perps only).
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub cumulative_funding: Decimal,
    /// Position delta (with respect to forward for options).
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub delta: Decimal,
    /// Position gamma (zero for non-options).
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub gamma: Decimal,
    /// Current oracle index price for the underlying.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub index_price: Decimal,
    /// USD initial margin requirement for this position.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub initial_margin: Decimal,
    /// Instrument identifier (same as the base asset name).
    pub instrument_name: Ustr,
    /// Instrument category.
    pub instrument_type: DeriveInstrumentType,
    /// Effective leverage (perps only).
    #[serde(default, deserialize_with = "deserialize_optional_derive_decimal")]
    pub leverage: Option<Decimal>,
    /// Index price at which the position would liquidate.
    #[serde(default, deserialize_with = "deserialize_optional_derive_decimal")]
    pub liquidation_price: Option<Decimal>,
    /// USD maintenance margin requirement.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub maintenance_margin: Decimal,
    /// Current mark price.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub mark_price: Decimal,
    /// USD mark-to-market value of the position.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub mark_value: Decimal,
    /// Net USD settled from this position.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub net_settlements: Decimal,
    /// USD margin held against open orders touching this asset.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub open_orders_margin: Decimal,
    /// Funding not yet settled into cash balance (perps only).
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub pending_funding: Decimal,
    /// Realized PnL booked on this position.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub realized_pnl: Decimal,
    /// Position theta (zero for non-options).
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub theta: Decimal,
    /// Unrealized PnL.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub unrealized_pnl: Decimal,
    /// Position vega (zero for non-options).
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub vega: Decimal,
}

/// Collateral row inside a `private/get_subaccount` response.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveCollateral {
    /// Collateral amount.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub amount: Decimal,
    /// Asset name (e.g. `"ETH"`, `"USDC"`).
    pub asset_name: Ustr,
    /// Asset category.
    pub asset_type: DeriveAssetType,
    /// Cumulative interest earned or paid.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub cumulative_interest: Decimal,
    /// Underlying currency.
    pub currency: Ustr,
    /// USD initial margin credit from this collateral.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub initial_margin: Decimal,
    /// USD maintenance margin credit.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub maintenance_margin: Decimal,
    /// Current mark price of the asset.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub mark_price: Decimal,
    /// USD value (`amount * mark_price`).
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub mark_value: Decimal,
    /// Interest not yet settled on-chain.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub pending_interest: Decimal,
}

/// Subaccount snapshot returned by `private/get_subaccount`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveSubaccount {
    /// Collateral rows contributing to margin.
    pub collaterals: Vec<DeriveCollateral>,
    /// Total initial margin credit from collaterals.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub collaterals_initial_margin: Decimal,
    /// Total maintenance margin credit from collaterals.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub collaterals_maintenance_margin: Decimal,
    /// Mark-to-market value of all collaterals.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub collaterals_value: Decimal,
    /// Subaccount currency (e.g. `"USDC"`).
    pub currency: Ustr,
    /// USD initial margin requirement.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub initial_margin: Decimal,
    /// Whether the subaccount is mid-liquidation.
    pub is_under_liquidation: bool,
    /// Free-form subaccount label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// USD maintenance margin requirement.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub maintenance_margin: Decimal,
    /// Margining mode (standard, portfolio, or PMRM v2).
    pub margin_type: DeriveMarginType,
    /// Open orders held by the subaccount.
    pub open_orders: Vec<DeriveOrder>,
    /// USD margin held against open orders.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub open_orders_margin: Decimal,
    /// Open positions held by the subaccount.
    pub positions: Vec<DerivePosition>,
    /// USD initial margin requirement attributable to positions.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub positions_initial_margin: Decimal,
    /// USD maintenance margin requirement attributable to positions.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub positions_maintenance_margin: Decimal,
    /// Mark-to-market value of positions.
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub positions_value: Decimal,
    /// Subaccount identifier.
    pub subaccount_id: i64,
    /// Total subaccount value (collateral + positions).
    #[serde(deserialize_with = "deserialize_derive_decimal")]
    pub subaccount_value: Decimal,
}

/// Private trade record returned by `private/get_trade_history` and the
/// `{subaccount_id}.trades` WS channel.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveTrade {
    /// Trade side.
    pub direction: DeriveOrderSide,
    /// Underlying index price at the time of the trade.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub index_price: Decimal,
    /// Instrument identifier.
    pub instrument_name: Ustr,
    /// Whether this trade was generated via `private/transfer_position`.
    pub is_transfer: bool,
    /// Free-form user label inherited from the order.
    pub label: Ustr,
    /// Maker / taker role of the user.
    pub liquidity_role: DeriveLiquidityRole,
    /// Mark price at the time of the trade.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub mark_price: Decimal,
    /// Originating order ID.
    pub order_id: String,
    /// RFQ quote ID when relevant.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote_id: Option<String>,
    /// Realized PnL booked by this trade.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub realized_pnl: Decimal,
    /// Owning subaccount.
    pub subaccount_id: i64,
    /// Trade timestamp (UNIX ms).
    pub timestamp: i64,
    /// Filled amount on this trade.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub trade_amount: Decimal,
    /// Fee charged for this trade.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub trade_fee: Decimal,
    /// Trade identifier.
    pub trade_id: String,
    /// Trade execution price.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub trade_price: Decimal,
    /// On-chain settlement tx hash, absent until settlement starts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tx_hash: Option<String>,
    /// On-chain settlement status.
    pub tx_status: DeriveTxStatus,
    /// Owning wallet address, absent in pending order responses.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wallet: Option<Ustr>,
}

/// Public trade record returned by `public/get_trade_history` and the
/// `trades.{instrument_type}.{currency}` WS channel.
///
/// The public WS feed strips private fields (subaccount, wallet, settlement
/// metadata, role, fee, PnL) and only carries values visible to every market
/// participant. Those fields are modelled as `Option` so the same struct can
/// deserialize both the HTTP shape (richer, when the caller has account
/// context) and the WS shape (slim).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePublicTrade {
    /// Trade side.
    pub direction: DeriveOrderSide,
    /// Underlying index price at the time of the trade.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub index_price: Decimal,
    /// Instrument identifier.
    pub instrument_name: Ustr,
    /// Maker / taker role of the aggressor. Only populated when the caller has
    /// account context; absent on the public WS feed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub liquidity_role: Option<DeriveLiquidityRole>,
    /// Mark price at the time of the trade.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub mark_price: Decimal,
    /// RFQ quote ID when relevant.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote_id: Option<String>,
    /// RFQ session ID when the trade originated from a request-for-quote.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rfq_id: Option<String>,
    /// Realized PnL attributed to the caller. Absent on the public WS feed.
    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
    pub realized_pnl: Option<Decimal>,
    /// Aggressor subaccount. Absent on the public WS feed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subaccount_id: Option<i64>,
    /// Trade timestamp (UNIX ms).
    pub timestamp: i64,
    /// Filled amount.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub trade_amount: Decimal,
    /// Fee charged to the caller. Absent on the public WS feed.
    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
    pub trade_fee: Option<Decimal>,
    /// Trade identifier.
    pub trade_id: String,
    /// Execution price.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub trade_price: Decimal,
    /// On-chain settlement tx hash. Absent on the public WS feed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tx_hash: Option<String>,
    /// On-chain settlement status. Absent on the public WS feed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tx_status: Option<DeriveTxStatus>,
    /// Aggressor wallet address. Absent on the public WS feed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wallet: Option<Ustr>,
}

/// Pagination metadata attached to listing endpoints.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePaginationInfo {
    /// Total number of items across all pages.
    pub count: i64,
    /// Number of pages available.
    pub num_pages: i64,
}

/// Paginated `private/get_orders` result envelope.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveOrdersResult {
    /// Orders on the current page.
    pub orders: Vec<DeriveOrder>,
    /// Pagination metadata.
    pub pagination: DerivePaginationInfo,
    /// Owning subaccount.
    pub subaccount_id: i64,
}

/// `private/get_open_orders` result envelope.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveOpenOrdersResult {
    /// Currently open orders.
    pub orders: Vec<DeriveOrder>,
    /// Owning subaccount.
    pub subaccount_id: i64,
}

/// Paginated `private/get_trade_history` result envelope.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeriveTradesResult {
    /// Trades on the current page.
    pub trades: Vec<DeriveTrade>,
    /// Pagination metadata.
    pub pagination: DerivePaginationInfo,
    /// Owning subaccount.
    pub subaccount_id: i64,
}

/// Paginated `public/get_trade_history` result envelope.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePublicTradesResult {
    /// Trades on the current page.
    pub trades: Vec<DerivePublicTrade>,
    /// Pagination metadata.
    pub pagination: DerivePaginationInfo,
}

/// OHLCV candle returned by `public/get_tradingview_chart_data`.
///
/// The venue ships the `result` field as a flat array of these records; the
/// HTTP client deserializes that array directly into `Vec<DerivePublicCandle>`.
/// Timestamps are UNIX **seconds** (not milliseconds, as on the trade and
/// funding endpoints).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePublicCandle {
    /// Open price for the bucket.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub open_price: Decimal,
    /// High price for the bucket.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub high_price: Decimal,
    /// Low price for the bucket.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub low_price: Decimal,
    /// Close price for the bucket.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub close_price: Decimal,
    /// Notional volume in USD over the bucket.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub volume_usd: Decimal,
    /// Base-asset volume (contracts) over the bucket.
    #[serde(deserialize_with = "deserialize_decimal")]
    pub volume_contracts: Decimal,
    /// Sample timestamp (UNIX seconds).
    pub timestamp: i64,
    /// Bucket start timestamp (UNIX seconds); regularly spaced by `period`.
    pub timestamp_bucket: i64,
}

/// Funding rate sample returned by `public/get_funding_rate_history`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePublicFundingRate {
    /// Funding rate observed at `timestamp` (fraction per funding interval).
    #[serde(deserialize_with = "deserialize_decimal")]
    pub funding_rate: Decimal,
    /// Sample timestamp (UNIX ms).
    pub timestamp: i64,
}

/// `public/get_funding_rate_history` result envelope.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePublicFundingRateHistoryResult {
    /// Funding rate samples ordered oldest to newest.
    pub funding_rate_history: Vec<DerivePublicFundingRate>,
}

/// `private/get_positions` result envelope.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DerivePositionsResult {
    /// Positions held by the subaccount.
    pub positions: Vec<DerivePosition>,
    /// Owning subaccount.
    pub subaccount_id: i64,
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use rstest::rstest;
    use serde_json::{Value, json};

    use super::*;

    fn data_path() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_data")
    }

    fn load_json(filename: &str) -> Value {
        let content = std::fs::read_to_string(data_path().join(filename))
            .unwrap_or_else(|_| panic!("failed to read {filename}"));
        serde_json::from_str(&content).expect("invalid json")
    }

    #[rstest]
    fn test_request_serializes_with_jsonrpc_version_tag() {
        let req = JsonRpcRequest::new(7, "public/get_instruments", json!({"currency": "ETH"}));
        let wire = serde_json::to_value(&req).unwrap();
        assert_eq!(wire["jsonrpc"], "2.0");
        assert_eq!(wire["id"], 7);
        assert_eq!(wire["method"], "public/get_instruments");
        assert_eq!(wire["params"]["currency"], "ETH");
    }

    #[rstest]
    fn test_response_decodes_success_envelope() {
        let body = json!({"id": 1, "result": {"instruments": []}});
        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
        assert_eq!(resp.id, Some(1));
        assert!(resp.error.is_none());
        assert!(resp.result.is_some());
    }

    #[rstest]
    fn test_response_decodes_error_envelope() {
        let body = json!({
            "id": 9,
            "error": {"code": -32600, "message": "Invalid Request"}
        });
        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
        assert_eq!(resp.id, Some(9));
        assert!(resp.result.is_none());
        let err = resp.error.expect("error present");
        assert_eq!(err.code, -32600);
        assert_eq!(err.message, "Invalid Request");
        assert!(err.data.is_none());
    }

    #[rstest]
    fn test_response_decodes_error_envelope_with_data_field() {
        let body = json!({
            "id": 9,
            "error": {
                "code": -32602,
                "message": "Invalid params",
                "data": {"field": "currency"},
            }
        });
        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
        let err = resp.error.expect("error present");
        assert_eq!(err.data, Some(json!({"field": "currency"})));
    }

    #[rstest]
    fn test_response_tolerates_missing_id() {
        let body = json!({"result": {"ok": true}});
        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
        assert!(resp.id.is_none());
        assert!(resp.result.is_some());
    }

    #[rstest]
    fn test_response_tolerates_string_id() {
        let body = json!({"id": "e3c970c6-94aa-420c-b6db-d0f585a7fde9", "result": {"ok": true}});
        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
        assert!(resp.id.is_none());
        assert!(resp.result.is_some());
    }

    #[rstest]
    fn test_response_decodes_numeric_string_id() {
        let body = json!({"id": "42", "result": {"ok": true}});
        let resp: JsonRpcResponse<Value> = serde_json::from_value(body).unwrap();
        assert_eq!(resp.id, Some(42));
        assert!(resp.result.is_some());
    }

    #[rstest]
    fn test_instrument_decodes_perp_with_perp_details() {
        let body = load_json("perps/instrument_eth.json");
        let instrument: DeriveInstrument = serde_json::from_value(body).unwrap();
        assert_eq!(instrument.instrument_name.as_str(), "ETH-PERP");
        assert_eq!(instrument.instrument_type, DeriveInstrumentType::Perp);
        assert!(instrument.option_details.is_none());
        let perp = instrument.perp_details.expect("perp details present");
        assert_eq!(perp.index, "ETH-USD");
    }

    #[rstest]
    fn test_instrument_decodes_option_with_option_details() {
        let mut body = load_json("options/instrument_eth.json");
        body["scheduled_activation"] = json!(0);
        let instrument: DeriveInstrument = serde_json::from_value(body).unwrap();
        let option = instrument.option_details.expect("option details present");
        assert_eq!(option.option_type, DeriveOptionKind::Call);
        assert_eq!(option.strike.to_string(), "3500");
        assert!(option.settlement_price.is_none());
    }

    #[rstest]
    fn test_order_decodes_partially_filled_market_order() {
        // Distinct `amount` and `filled_amount` so a struct-field swap is
        // detectable. Every Ustr-typed field has a unique value so a serde
        // rename or field-order regression surfaces against a single fixture.
        let body = load_json("perps/http_order_eth_partially_filled.json");
        let order: DeriveOrder = serde_json::from_value(body).unwrap();
        assert_eq!(order.amount.to_string(), "2.0");
        assert_eq!(order.filled_amount.to_string(), "1.5");
        assert_eq!(order.average_price.to_string(), "3500.25");
        assert_eq!(order.order_status, DeriveOrderStatus::Filled);
        assert_eq!(order.cancel_reason, DeriveOrderCancelReason::Empty);
        assert_eq!(order.direction, DeriveOrderSide::Buy);
        assert_eq!(order.time_in_force, DeriveTimeInForce::Ioc);
        assert_eq!(order.order_type, DeriveOrderType::Market);
        assert_eq!(order.instrument_name.as_str(), "ETH-PERP");
        assert_eq!(order.label.as_str(), "alpha-strategy");
        assert_eq!(order.signer.as_str(), "0xsigner");
        assert_eq!(order.order_id, "abc-123");
        assert_eq!(order.subaccount_id, 42);
        assert_eq!(order.signature_expiry_sec, 1_700_001_000);
        assert!(!order.mmp);
        assert!(!order.is_transfer);
        assert!(order.quote_id.is_none());
        assert!(order.replaced_order_id.is_none());
    }

    #[rstest]
    fn test_position_decodes_perp_with_optional_leverage() {
        // Distinct decimal values per field so a struct-field swap surfaces.
        let body = load_json("perps/http_position_eth.json");
        let position: DerivePosition = serde_json::from_value(body).unwrap();
        assert_eq!(position.instrument_type, DeriveInstrumentType::Perp);
        assert_eq!(position.instrument_name.as_str(), "ETH-PERP");
        assert_eq!(position.amount.to_string(), "-2");
        assert_eq!(position.delta.to_string(), "-2");
        assert_eq!(position.gamma.to_string(), "0.1");
        assert_eq!(position.theta.to_string(), "-0.3");
        assert_eq!(position.vega.to_string(), "0.5");
        assert_eq!(position.unrealized_pnl.to_string(), "8");
        assert_eq!(position.mark_value.to_string(), "-7008");
        assert_eq!(
            position.leverage.as_ref().map(ToString::to_string),
            Some("5.0".into()),
        );
        assert_eq!(
            position.liquidation_price.as_ref().map(ToString::to_string),
            Some("4200".into()),
        );
    }

    #[rstest]
    fn test_subaccount_decodes_with_collaterals_and_open_orders() {
        let body = load_json("common/http_subaccount_usdc.json");
        let subaccount: DeriveSubaccount = serde_json::from_value(body).unwrap();
        assert_eq!(subaccount.subaccount_id, 42);
        assert_eq!(subaccount.margin_type, DeriveMarginType::Pm);
        assert_eq!(subaccount.collaterals.len(), 1);
        assert_eq!(subaccount.collaterals[0].asset_type, DeriveAssetType::Erc20);
        assert!(!subaccount.is_under_liquidation);
    }

    #[rstest]
    fn test_subaccount_decodes_high_scale_decimal_values() {
        let body = load_json("common/http_subaccount_high_scale.json");
        let subaccount: DeriveSubaccount = serde_json::from_value(body).unwrap();
        let position = &subaccount.positions[0];

        assert_eq!(
            subaccount.initial_margin.to_string(),
            "0.1234567890123456789012345679",
        );
        assert_eq!(
            subaccount.collaterals[0].amount.to_string(),
            "0.1234567890123456789012345679",
        );
        assert_eq!(
            position.pending_funding.to_string(),
            "0.1234567890123456789012345679",
        );
        assert_eq!(
            position.leverage.as_ref().map(ToString::to_string),
            Some("5.1234567890123456789012345679".into()),
        );
        assert_eq!(
            position.liquidation_price.as_ref().map(ToString::to_string),
            Some("4200.1234567890123456789012346".into()),
        );
    }

    #[rstest]
    fn test_public_trade_round_trips() {
        let body = load_json("perps/http_public_trade_eth_sell.json");
        let trade: DerivePublicTrade = serde_json::from_value(body).unwrap();
        assert_eq!(trade.direction, DeriveOrderSide::Sell);
        assert_eq!(trade.tx_status, Some(DeriveTxStatus::Settled));
        let reserialized = serde_json::to_value(&trade).unwrap();
        assert_eq!(reserialized["instrument_name"], "ETH-PERP");
        assert_eq!(reserialized["liquidity_role"], "taker");
    }

    #[rstest]
    fn test_orders_result_envelope_decodes() {
        let body = json!({
            "orders": [],
            "pagination": {"count": 0, "num_pages": 0},
            "subaccount_id": 42,
        });
        let result: DeriveOrdersResult = serde_json::from_value(body).unwrap();
        assert!(result.orders.is_empty());
        assert_eq!(result.subaccount_id, 42);
        assert_eq!(result.pagination.count, 0);
    }

    fn perp_ticker_json() -> Value {
        load_json("perps/http_ticker_eth_snapshot.json")
    }

    #[rstest]
    fn test_ticker_decodes_perp_snapshot() {
        let ticker: DeriveTicker = serde_json::from_value(perp_ticker_json()).unwrap();
        assert_eq!(ticker.instrument_name.as_str(), "ETH-PERP");
        assert_eq!(ticker.instrument_type, DeriveInstrumentType::Perp);
        assert_eq!(ticker.mark_price.to_string(), "3500.5");
        assert_eq!(ticker.best_bid_price.to_string(), "3499.5");
        assert_eq!(ticker.best_ask_price.to_string(), "3501.0");
        assert_eq!(ticker.timestamp, 1_700_000_000_000);
        assert!(ticker.option_details.is_none());
        assert!(ticker.option_pricing.is_none());
        let perp = ticker.perp_details.expect("perp details present");
        assert_eq!(perp.index.as_str(), "ETH-USD");
        assert_eq!(perp.funding_rate.to_string(), "0.0002");
        let stats = ticker
            .stats
            .as_ref()
            .expect("WS ticker fixture includes stats");
        assert_eq!(stats.contract_volume.to_string(), "12345.6");
        assert_eq!(stats.high.to_string(), "3600");
        assert_eq!(stats.num_trades.to_string(), "789");
    }

    #[rstest]
    fn test_ticker_decodes_option_snapshot_with_greeks() {
        let body = load_json("options/http_ticker_eth_snapshot.json");
        let ticker: DeriveTicker = serde_json::from_value(body).unwrap();
        assert_eq!(ticker.instrument_type, DeriveInstrumentType::Option);
        assert!(ticker.perp_details.is_none());
        let option = ticker.option_details.expect("option details present");
        assert_eq!(option.option_type, DeriveOptionKind::Call);
        assert_eq!(option.strike.to_string(), "3500");
        assert!(option.settlement_price.is_none());
        let greeks = ticker.option_pricing.expect("option pricing present");
        assert_eq!(greeks.delta.to_string(), "0.55");
        assert_eq!(greeks.gamma.to_string(), "0.0008");
        assert_eq!(greeks.theta.to_string(), "-2.1");
        assert_eq!(greeks.vega.to_string(), "4.5");
        assert_eq!(greeks.iv.to_string(), "0.60");
        assert_eq!(greeks.forward_price.to_string(), "3505");
    }

    #[rstest]
    fn test_private_trade_decodes_with_order_link() {
        // Asserts the fields that distinguish DeriveTrade from DerivePublicTrade
        // (order_id, label, is_transfer, realized_pnl) plus the Ustr-typed
        // wallet and the typed enum fields.
        let body = load_json("perps/http_private_trade_eth.json");
        let trade: DeriveTrade = serde_json::from_value(body).unwrap();
        assert_eq!(trade.direction, DeriveOrderSide::Buy);
        assert_eq!(trade.liquidity_role, DeriveLiquidityRole::Maker);
        assert_eq!(trade.tx_status, DeriveTxStatus::Settled);
        assert_eq!(trade.instrument_name.as_str(), "ETH-PERP");
        assert_eq!(trade.label.as_str(), "alpha-strategy");
        assert_eq!(trade.wallet.as_ref().map(Ustr::as_str), Some("0xwallet"));
        assert_eq!(trade.order_id, "order-abc");
        assert_eq!(trade.trade_id, "trade-xyz");
        assert_eq!(trade.subaccount_id, 42);
        assert_eq!(trade.realized_pnl.to_string(), "12.5");
        assert_eq!(trade.trade_amount.to_string(), "0.5");
        assert_eq!(trade.trade_price.to_string(), "3499.0");
        assert!(!trade.is_transfer);
        assert!(trade.quote_id.is_none());
        assert_eq!(trade.tx_hash.as_deref(), Some("0xhash"));
    }

    #[rstest]
    fn test_order_result_decodes_pending_trade_with_null_tx_hash() {
        let mut body = load_json("spot/http_submit_order_response_mainnet.json");
        let mut trade = load_json("perps/http_private_trade_eth.json");
        trade["tx_hash"] = Value::Null;
        trade["tx_status"] = json!("requested");
        trade.as_object_mut().unwrap().remove("wallet");
        body["result"]["trades"] = json!([trade]);

        let result: DeriveOrderResult =
            serde_json::from_value(body["result"].clone()).expect("result decodes");

        assert_eq!(result.trades.len(), 1);
        assert!(result.trades[0].tx_hash.is_none());
        assert_eq!(result.trades[0].tx_status, DeriveTxStatus::Requested);
        assert!(result.trades[0].wallet.is_none());
    }

    #[rstest]
    fn test_empty_result_decodes_cancel_ack_shapes() {
        let object: DeriveEmptyResult = serde_json::from_value(json!({})).unwrap();
        let ok_string: DeriveEmptyResult = serde_json::from_value(json!("ok")).unwrap();
        let null_value: DeriveEmptyResult = serde_json::from_value(Value::Null).unwrap();

        assert_eq!(object, DeriveEmptyResult {});
        assert_eq!(ok_string, DeriveEmptyResult {});
        assert_eq!(null_value, DeriveEmptyResult {});
    }

    #[rstest]
    fn test_trades_result_envelope_decodes() {
        let body = load_json("perps/http_trades_result_eth.json");
        let result: DeriveTradesResult = serde_json::from_value(body).unwrap();
        assert_eq!(result.trades.len(), 1);
        assert_eq!(result.subaccount_id, 7);
        assert_eq!(result.pagination.count, 1);
        assert_eq!(result.pagination.num_pages, 1);
        assert_eq!(result.trades[0].trade_id, "t-1");
    }

    #[rstest]
    fn test_public_trades_result_envelope_decodes() {
        let body = load_json("perps/http_public_trades_result_eth.json");
        let result: DerivePublicTradesResult = serde_json::from_value(body).unwrap();
        assert_eq!(result.trades.len(), 1);
        assert_eq!(result.pagination.count, 1);
        assert_eq!(result.trades[0].trade_id, "pub-1");
    }

    #[rstest]
    fn test_public_funding_rate_history_result_envelope_decodes() {
        let body = load_json("perps/http_public_funding_rate_history_eth.json");
        let result: DerivePublicFundingRateHistoryResult = serde_json::from_value(body).unwrap();
        assert_eq!(result.funding_rate_history.len(), 3);
        let first = &result.funding_rate_history[0];
        assert_eq!(first.funding_rate.to_string(), "0.00012");
        assert_eq!(first.timestamp, 1_700_000_000_000);
        assert_eq!(
            result.funding_rate_history.last().unwrap().timestamp,
            1_700_007_200_000,
        );
    }

    #[rstest]
    fn test_public_candles_decode_array() {
        // The venue ships `result` as a flat array; the HTTP client decodes
        // directly into `Vec<DerivePublicCandle>`. The fixture mirrors that
        // wire shape.
        let body = load_json("perps/http_public_candles_eth.json");
        let candles: Vec<DerivePublicCandle> = serde_json::from_value(body).unwrap();
        assert_eq!(candles.len(), 3);
        let first = &candles[0];
        assert_eq!(first.open_price.to_string(), "3500.0");
        assert_eq!(first.high_price.to_string(), "3501.5");
        assert_eq!(first.low_price.to_string(), "3499.0");
        assert_eq!(first.close_price.to_string(), "3501.0");
        assert_eq!(first.volume_usd.to_string(), "12345.6");
        assert_eq!(first.volume_contracts.to_string(), "3.527");
        // Distinct `timestamp` vs `timestamp_bucket` so a field-swap mutation
        // in any downstream parser is detectable.
        assert_eq!(first.timestamp, 1_700_000_007);
        assert_eq!(first.timestamp_bucket, 1_700_000_000);
        assert_eq!(candles.last().unwrap().timestamp_bucket, 1_700_001_800);
    }

    #[rstest]
    fn test_positions_result_envelope_decodes() {
        let body = load_json("perps/http_positions_result_eth.json");
        let result: DerivePositionsResult = serde_json::from_value(body).unwrap();
        assert_eq!(result.positions.len(), 1);
        assert_eq!(result.subaccount_id, 42);
        assert_eq!(result.positions[0].instrument_name.as_str(), "ETH-PERP");
        assert!(result.positions[0].leverage.is_none());
        assert!(result.positions[0].liquidation_price.is_none());
    }
}