deribit-mcp 1.0.0

MCP (Model Context Protocol) server for Deribit trading platform
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
//! `Trading` tool family.
//!
//! All tools in this module have [`ToolClass::Trading`]. The registry
//! refuses to register them unless **both** `DERIBIT_CLIENT_ID` /
//! `DERIBIT_CLIENT_SECRET` credentials are configured **and**
//! `--allow-trading` is passed (ADR-0010); `--max-order-usd` caps
//! notional size in a future v0.4-04 step.
//!
//! v0.4-01 ships:
//!
//! - `place_order` — buy / sell with the full Deribit order parameter
//!   surface (limit / market / stop / take, optional time-in-force,
//!   trigger, post-only / reduce-only / mmp flags, `valid_until`).
//!
//! [`ToolClass::Trading`]: super::ToolClass::Trading

use std::sync::Arc;

use rmcp::model::Tool;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::schema::{parse_input as parse, schema_for};
use super::{ToolClass, ToolEntry, ToolHandlerFn, ToolRegistry};
use crate::context::AdapterContext;
use crate::error::AdapterError;

/// Register every `Trading` tool with the registry.
pub fn register(registry: &mut ToolRegistry) {
    registry.insert(place_order_tool());
    registry.insert(edit_order_tool());
    registry.insert(cancel_order_tool());
    registry.insert(cancel_all_by_currency_tool());
    registry.insert(cancel_all_by_instrument_tool());
}

// ----- place_order ---------------------------------------------------

/// Buy or sell.
///
/// Closed-set enum kept local to the adapter so the JSON wire shape
/// (`"buy"` / `"sell"`) stays stable independent of any future
/// rename in the upstream `deribit-http` `OrderSide`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Side {
    /// Buy.
    Buy,
    /// Sell.
    Sell,
}

/// Order type accepted by `place_order`.
///
/// One-to-one with the upstream `deribit_http::model::order::OrderType`
/// variants the adapter supports. `TrailingStop` is not exposed yet —
/// it lacks adapter-side validation rules and ships once v0.4 stabilises.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PlaceOrderType {
    /// Limit order. Requires `price`.
    Limit,
    /// Market order.
    Market,
    /// Stop limit. Requires `price`, `trigger_price`, `trigger`.
    StopLimit,
    /// Stop market. Requires `trigger_price`, `trigger`.
    StopMarket,
    /// Take-profit limit. Requires `price`, `trigger_price`, `trigger`.
    TakeLimit,
    /// Take-profit market. Requires `trigger_price`, `trigger`.
    TakeMarket,
    /// Market-limit order — market with limit-price protection.
    MarketLimit,
}

/// Time-in-force.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PlaceTimeInForce {
    /// Default. Resting until cancelled.
    GoodTilCancelled,
    /// Expires at end of trading day.
    GoodTilDay,
    /// Fully fill immediately or cancel.
    FillOrKill,
    /// Fill what is possible immediately, cancel the rest.
    ImmediateOrCancel,
}

/// Trigger reference price for stop / take variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PlaceTrigger {
    /// Index price.
    IndexPrice,
    /// Mark price.
    MarkPrice,
    /// Last traded price.
    LastPrice,
}

/// `place_order` input.
///
/// Mirrors the parameters Deribit's `/private/buy` and
/// `/private/sell` endpoints accept. Adapter-side validation runs
/// before the upstream call: required-fields-by-order-type, finite
/// numeric values, strictly positive `amount` / `price`.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct PlaceOrderInput {
    /// Instrument identifier (`BTC-PERPETUAL`, `ETH-29SEP23-1500-C`,
    /// …). Routed to Deribit verbatim.
    pub instrument_name: String,
    /// `buy` or `sell`. Decides which upstream endpoint runs.
    pub side: Side,
    /// Order amount. Finite, `> 0`. Contracts for options,
    /// quote-currency for futures / perpetuals (Deribit's own
    /// convention — the adapter does not reinterpret it).
    pub amount: f64,
    /// Order type. Required-field rules:
    /// - `limit` / `stop_limit` / `take_limit` → `price` is required.
    /// - `stop_*` / `take_*` → `trigger_price` and `trigger` required.
    #[serde(rename = "type")]
    pub order_type: PlaceOrderType,
    /// Limit price. Required for limit / stop_limit / take_limit.
    /// Finite, `> 0`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price: Option<f64>,
    /// Time-in-force override. Defaults upstream to `good_til_cancelled`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<PlaceTimeInForce>,
    /// User-defined label echoed back on the resulting order; max 64
    /// chars upstream.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Trigger price. Required for stop / take variants. Finite, `> 0`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_price: Option<f64>,
    /// Trigger reference. Required alongside `trigger_price`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<PlaceTrigger>,
    /// Post-only flag — reject the order if it would cross the book.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post_only: Option<bool>,
    /// `reject_post_only` — reject (vs. amend) when `post_only`
    /// would otherwise be relaxed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reject_post_only: Option<bool>,
    /// Reduce-only — only decrease, never flip, the position.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reduce_only: Option<bool>,
    /// Market-Maker Protection flag (advanced).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mmp: Option<bool>,
    /// Server-side TTL (Unix-ms). After this timestamp the order is
    /// auto-cancelled. Unsigned to match the rest of the adapter's
    /// timestamp inputs (`start_timestamp` / `end_timestamp` in the
    /// Account family).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub valid_until: Option<u64>,
}

fn place_order_tool() -> ToolEntry {
    let schema = schema_for::<PlaceOrderInput>();
    let descriptor = Tool::new(
        "place_order",
        "Place a buy or sell order. This sends a real order to the configured Deribit endpoint.",
        schema,
    );
    let handler: ToolHandlerFn = Arc::new(|ctx, input| Box::pin(handle_place_order(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Trading,
        handler,
    }
}

async fn handle_place_order(ctx: &AdapterContext, input: Value) -> Result<Value, AdapterError> {
    let input: PlaceOrderInput = parse(input)?;
    validate_place_order(&input)?;
    enforce_size_cap(ctx, &input.instrument_name, input.amount, input.price).await?;
    // Closed-set match — adding a future `OrderTransport` variant
    // fails to compile here, forcing reviewers to wire the new
    // path explicitly.
    match ctx.config.order_transport {
        crate::config::OrderTransport::Http => place_order_via_http(ctx, input).await,
        #[cfg(feature = "fix")]
        crate::config::OrderTransport::Fix => place_order_via_fix(ctx, input).await,
        #[cfg(not(feature = "fix"))]
        crate::config::OrderTransport::Fix => Err(AdapterError::not_enabled(
            "place_order",
            "build with --features=fix",
        )),
    }
}

async fn place_order_via_http(
    ctx: &AdapterContext,
    input: PlaceOrderInput,
) -> Result<Value, AdapterError> {
    let (side, request) = build_order_request(input)?;
    let result = match side {
        Side::Buy => ctx.http.buy_order(request).await?,
        Side::Sell => ctx.http.sell_order(request).await?,
    };
    Ok(serde_json::to_value(&result)?)
}

/// Submit `place_order` over the lazy FIX session.
///
/// The upstream `DeribitFixClient::send_order` returns only the
/// FIX `ClOrdID` (string) — the inbound `ExecutionReport (8)`
/// arrives asynchronously and is not surfaced synchronously by
/// `deribit-fix 0.3`. To preserve the MCP wire surface — same
/// `OrderResponse`-shape across both transports — the adapter
/// builds a minimal stub: `{"order": {"order_id": <id>,
/// "instrument_name": <…>, …}, "trades": []}`. The LLM should
/// poll the Account tools for fill information when the trade
/// list matters.
#[cfg(feature = "fix")]
async fn place_order_via_fix(
    ctx: &AdapterContext,
    input: PlaceOrderInput,
) -> Result<Value, AdapterError> {
    let request = build_fix_new_order_request(input)?;
    let fix = ctx.ensure_fix().await?;
    let order_id = {
        let guard = fix.lock().await;
        guard.send_order(request.clone()).await?
    };
    Ok(synthesize_fix_order_response(&order_id, &request))
}

#[cfg(feature = "fix")]
fn build_fix_new_order_request(
    input: PlaceOrderInput,
) -> Result<deribit_fix::model::request::NewOrderRequest, AdapterError> {
    use deribit_fix::model::request::{
        NewOrderRequest, OrderSide as FixSide, OrderType as FixOrderType, TimeInForce as FixTif,
        TriggerType as FixTrigger,
    };

    // `deribit-fix 0.3`'s `NewOrderRequest` does not carry an
    // `mmp` field. Silently dropping the caller flag would make
    // the FIX path quietly diverge from the HTTP path, so refuse
    // up-front with a structured error.
    if input.mmp.is_some() {
        return Err(AdapterError::Validation {
            field: "mmp".to_string(),
            message: "`mmp` is not supported by the FIX transport (deribit-fix 0.3)".to_string(),
        });
    }

    let order_type = match input.order_type {
        PlaceOrderType::Limit => FixOrderType::Limit,
        PlaceOrderType::Market => FixOrderType::Market,
        PlaceOrderType::StopLimit => FixOrderType::StopLimit,
        PlaceOrderType::StopMarket => FixOrderType::StopMarket,
        PlaceOrderType::TakeLimit => FixOrderType::TakeLimit,
        PlaceOrderType::TakeMarket => FixOrderType::TakeMarket,
        PlaceOrderType::MarketLimit => FixOrderType::MarketLimit,
    };
    let side = match input.side {
        Side::Buy => FixSide::Buy,
        Side::Sell => FixSide::Sell,
    };
    let time_in_force = match input.time_in_force {
        Some(PlaceTimeInForce::GoodTilCancelled) | None => FixTif::GoodTilCancelled,
        Some(PlaceTimeInForce::GoodTilDay) => FixTif::GoodTilDay,
        Some(PlaceTimeInForce::FillOrKill) => FixTif::FillOrKill,
        Some(PlaceTimeInForce::ImmediateOrCancel) => FixTif::ImmediateOrCancel,
    };
    let trigger = input.trigger.map(|t| match t {
        PlaceTrigger::IndexPrice => FixTrigger::IndexPrice,
        PlaceTrigger::MarkPrice => FixTrigger::MarkPrice,
        PlaceTrigger::LastPrice => FixTrigger::LastPrice,
    });
    let valid_until = match input.valid_until {
        None => None,
        Some(v) => Some(i64::try_from(v).map_err(|_| AdapterError::Validation {
            field: "valid_until".to_string(),
            message: format!("must fit in i64, got {v}"),
        })?),
    };
    Ok(NewOrderRequest {
        instrument_name: input.instrument_name,
        amount: input.amount,
        order_type,
        side,
        price: input.price,
        time_in_force,
        post_only: input.post_only,
        reduce_only: input.reduce_only,
        label: input.label,
        stop_price: input.trigger_price,
        trigger,
        advanced: None,
        max_show: None,
        reject_post_only: input.reject_post_only,
        valid_until,
        client_order_id: None,
    })
}

#[cfg(feature = "fix")]
fn synthesize_fix_order_response(
    order_id: &str,
    request: &deribit_fix::model::request::NewOrderRequest,
) -> Value {
    use deribit_fix::model::request::OrderSide as FixSide;
    let direction = match request.side {
        FixSide::Buy => "buy",
        FixSide::Sell => "sell",
    };
    serde_json::json!({
        "order": {
            "order_id": order_id,
            "instrument_name": request.instrument_name,
            "amount": request.amount,
            "direction": direction,
            "order_type": request.order_type.as_str(),
            "price": request.price,
            "post_only": request.post_only.unwrap_or(false),
            "reduce_only": request.reduce_only.unwrap_or(false),
            "label": request.label.clone().unwrap_or_default(),
            "order_state": "open",
            "time_in_force": request.time_in_force.as_str(),
            "transport": "fix"
        },
        "trades": []
    })
}

/// Enforce the per-process notional cap configured via
/// `--max-order-usd` / `DERIBIT_MAX_ORDER_USD`.
///
/// Runs after schema validation, before any private
/// order-placement call (`/private/buy` / `/private/sell`). When
/// the cap is unset the function is a no-op. When set, it
/// converts the order size to a USD-equivalent notional and
/// rejects the call with [`AdapterError::SizeCapExceeded`] if the
/// notional is over the cap. May fetch upstream pricing data
/// (`/public/ticker`, `/public/get_index_price`) when the caller
/// did not supply a `price` or the instrument is an option.
///
/// # Notional formula
///
/// Classifies the instrument by its name suffix:
///
/// - **Linear** (`*_USDC*` / `*_USDT*` — settlement in stablecoin):
///   `notional = amount × price`. For market orders without a
///   provided `price`, the upstream `mark_price` from
///   `/public/ticker` is used.
/// - **Option** (final segment is `-C` / `-P` with a numeric
///   strike): `notional = amount × index_price`, where
///   `index_price` is the upstream USD index for the option's
///   underlying (`BTC`, `ETH`, …) via `/public/get_index_price`.
///   This pins the conservative upper bound of underlying USD
///   exposure for `amount` contracts of the option.
/// - **Inverse** (everything else — BTC- / ETH-denominated
///   futures and perpetuals): `amount` is already USD-notional
///   per Deribit's contract-size convention, so the notional is
///   `amount` directly.
///
/// The classification is conservative — when in doubt the inverse
/// branch is taken so the cap doesn't silently let through a
/// larger order.
///
/// # Errors
///
/// Returns [`AdapterError::SizeCapExceeded`] when the computed
/// notional exceeds the cap. May also propagate
/// [`AdapterError::Upstream`] if a price-fetch needed for the
/// notional calculation fails.
pub(crate) async fn enforce_size_cap(
    ctx: &AdapterContext,
    instrument_name: &str,
    amount: f64,
    price: Option<f64>,
) -> Result<(), AdapterError> {
    let Some(cap) = ctx.config.max_order_usd else {
        return Ok(());
    };
    let cap = cap as f64;
    let notional = compute_usd_notional(ctx, instrument_name, amount, price).await?;
    if !notional.is_finite() {
        return Err(AdapterError::Validation {
            field: "amount".to_string(),
            message: "computed notional is not finite".to_string(),
        });
    }
    if notional > cap {
        return Err(AdapterError::SizeCapExceeded {
            requested: notional,
            cap,
        });
    }
    Ok(())
}

/// `true` when the instrument is linear (USDC / USDT settlement).
fn is_linear_instrument(name: &str) -> bool {
    name.contains("_USDC") || name.contains("_USDT")
}

/// `true` when the instrument is an option — last segment is a
/// single `C` or `P` and the segment before it parses as a
/// strike. Matches Deribit's `<BASE>-<EXPIRY>-<STRIKE>-<C|P>`
/// pattern.
fn is_option_instrument(name: &str) -> bool {
    let mut parts = name.rsplit('-');
    let Some(last) = parts.next() else {
        return false;
    };
    if last != "C" && last != "P" {
        return false;
    }
    let Some(strike) = parts.next() else {
        return false;
    };
    strike.parse::<f64>().is_ok()
}

/// Underlying base symbol for an option instrument
/// (`BTC-29SEP24-50000-C` → `Some("BTC")`).
fn option_underlying_base(name: &str) -> Option<&str> {
    name.split('-').next()
}

async fn compute_usd_notional(
    ctx: &AdapterContext,
    instrument_name: &str,
    amount: f64,
    price: Option<f64>,
) -> Result<f64, AdapterError> {
    if is_option_instrument(instrument_name) {
        // Conservative upper bound of underlying USD exposure for
        // `amount` contracts of the option. Each contract is for
        // one unit of the underlying at Deribit, so the underlying
        // notional is `amount × index_price`.
        let base = option_underlying_base(instrument_name).unwrap_or("BTC");
        let index_name = format!("{}_usd", base.to_lowercase());
        let idx = ctx.http.get_index_price(&index_name).await?;
        return Ok(amount * idx.index_price);
    }
    if !is_linear_instrument(instrument_name) {
        // Inverse — amount is USD notional directly.
        return Ok(amount);
    }
    let p = match price {
        Some(p) => p,
        None => {
            let ticker = ctx.http.get_ticker(instrument_name).await?;
            ticker.mark_price
        }
    };
    Ok(amount * p)
}

/// Adapter-side validation ahead of any network call.
///
/// # Errors
///
/// Returns [`AdapterError::Validation`] when:
///
/// - `amount` is non-finite or `<= 0`.
/// - `price` is supplied non-finite or `<= 0`.
/// - `trigger_price` is supplied non-finite or `<= 0`.
/// - The order type requires `price` and it is missing.
/// - The order type requires `trigger_price` / `trigger` and they
///   are missing.
fn validate_place_order(input: &PlaceOrderInput) -> Result<(), AdapterError> {
    if !input.amount.is_finite() || input.amount <= 0.0 {
        return Err(AdapterError::Validation {
            field: "amount".to_string(),
            message: format!("must be finite and > 0, got {}", input.amount),
        });
    }
    if let Some(price) = input.price
        && (!price.is_finite() || price <= 0.0)
    {
        return Err(AdapterError::Validation {
            field: "price".to_string(),
            message: format!("must be finite and > 0, got {price}"),
        });
    }
    if let Some(tp) = input.trigger_price
        && (!tp.is_finite() || tp <= 0.0)
    {
        return Err(AdapterError::Validation {
            field: "trigger_price".to_string(),
            message: format!("must be finite and > 0, got {tp}"),
        });
    }
    let needs_price = matches!(
        input.order_type,
        PlaceOrderType::Limit | PlaceOrderType::StopLimit | PlaceOrderType::TakeLimit
    );
    if needs_price && input.price.is_none() {
        return Err(AdapterError::Validation {
            field: "price".to_string(),
            message: "required for limit / stop_limit / take_limit orders".to_string(),
        });
    }
    let needs_trigger = matches!(
        input.order_type,
        PlaceOrderType::StopLimit
            | PlaceOrderType::StopMarket
            | PlaceOrderType::TakeLimit
            | PlaceOrderType::TakeMarket
    );
    if needs_trigger {
        if input.trigger_price.is_none() {
            return Err(AdapterError::Validation {
                field: "trigger_price".to_string(),
                message: "required for stop / take order types".to_string(),
            });
        }
        if input.trigger.is_none() {
            return Err(AdapterError::Validation {
                field: "trigger".to_string(),
                message: "required for stop / take order types".to_string(),
            });
        }
    }
    Ok(())
}

/// Build the upstream `OrderRequest` plus the side-tag controlling
/// which endpoint to hit. Closed-set matches on `PlaceOrderType` /
/// `PlaceTimeInForce` / `PlaceTrigger` keep the conversion total.
///
/// # Errors
///
/// Returns [`AdapterError::Validation`] if `valid_until` overflows
/// `i64` — practically unreachable for any real Unix-ms timestamp,
/// but the upstream `OrderRequest.valid_until` is signed so the
/// cast is checked here at the boundary instead of silently wrapping.
fn build_order_request(
    input: PlaceOrderInput,
) -> Result<(Side, deribit_http::model::request::OrderRequest), AdapterError> {
    use deribit_http::model::order::OrderType as UpType;
    use deribit_http::model::request::OrderRequest;
    use deribit_http::model::trigger::Trigger as UpTrigger;
    use deribit_http::model::types::TimeInForce as UpTif;

    let order_type = match input.order_type {
        PlaceOrderType::Limit => UpType::Limit,
        PlaceOrderType::Market => UpType::Market,
        PlaceOrderType::StopLimit => UpType::StopLimit,
        PlaceOrderType::StopMarket => UpType::StopMarket,
        PlaceOrderType::TakeLimit => UpType::TakeLimit,
        PlaceOrderType::TakeMarket => UpType::TakeMarket,
        PlaceOrderType::MarketLimit => UpType::MarketLimit,
    };
    let time_in_force = input.time_in_force.map(|t| match t {
        PlaceTimeInForce::GoodTilCancelled => UpTif::GoodTilCancelled,
        PlaceTimeInForce::GoodTilDay => UpTif::GoodTilDay,
        PlaceTimeInForce::FillOrKill => UpTif::FillOrKill,
        PlaceTimeInForce::ImmediateOrCancel => UpTif::ImmediateOrCancel,
    });
    let trigger = input.trigger.map(|t| match t {
        PlaceTrigger::IndexPrice => UpTrigger::IndexPrice,
        PlaceTrigger::MarkPrice => UpTrigger::MarkPrice,
        PlaceTrigger::LastPrice => UpTrigger::LastPrice,
    });
    let valid_until = match input.valid_until {
        None => None,
        Some(v) => Some(i64::try_from(v).map_err(|_| AdapterError::Validation {
            field: "valid_until".to_string(),
            message: format!("must fit in i64, got {v}"),
        })?),
    };
    let req = OrderRequest {
        order_id: None,
        instrument_name: input.instrument_name,
        amount: Some(input.amount),
        contracts: None,
        type_: Some(order_type),
        label: input.label,
        price: input.price,
        time_in_force,
        display_amount: None,
        post_only: input.post_only,
        reject_post_only: input.reject_post_only,
        reduce_only: input.reduce_only,
        trigger_price: input.trigger_price,
        trigger_offset: None,
        trigger,
        advanced: None,
        mmp: input.mmp,
        valid_until,
        linked_order_type: None,
        trigger_fill_condition: None,
        otoco_config: None,
    };
    Ok((input.side, req))
}

// ----- edit_order ---------------------------------------------------

/// `edit_order` input.
///
/// Modifies an existing order identified by `order_id`. All other
/// fields are optional — `None` means "leave the existing value
/// unchanged upstream".
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct EditOrderInput {
    /// Order id returned from `place_order`.
    pub order_id: String,
    /// New amount. Finite, `> 0` if supplied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub amount: Option<f64>,
    /// New limit price. Finite, `> 0` if supplied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price: Option<f64>,
    /// Toggle post-only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post_only: Option<bool>,
    /// `reject_post_only` — reject (vs. amend) when `post_only`
    /// would otherwise be relaxed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reject_post_only: Option<bool>,
    /// Toggle reduce-only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reduce_only: Option<bool>,
    /// Toggle Market-Maker Protection.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mmp: Option<bool>,
    /// Server-side TTL (Unix-ms). `None` keeps the existing value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub valid_until: Option<u64>,
    /// New trigger price for stop / take orders. Finite, `> 0` if
    /// supplied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_price: Option<f64>,
}

fn edit_order_tool() -> ToolEntry {
    let schema = schema_for::<EditOrderInput>();
    let descriptor = Tool::new(
        "edit_order",
        "Modify amount / price / trigger_price / valid_until / flags (post_only, \
         reject_post_only, reduce_only, mmp) of an open order.",
        schema,
    );
    let handler: ToolHandlerFn = Arc::new(|ctx, input| Box::pin(handle_edit_order(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Trading,
        handler,
    }
}

async fn handle_edit_order(ctx: &AdapterContext, input: Value) -> Result<Value, AdapterError> {
    let mut input: EditOrderInput = parse(input)?;
    validate_edit_order(&input)?;
    // Forward the trimmed id — leading / trailing whitespace would
    // surface as an opaque upstream `OrderNotFound`.
    input.order_id = input.order_id.trim().to_string();
    let request = build_edit_request(input)?;
    let result = ctx.http.edit_order(request).await?;
    Ok(serde_json::to_value(&result)?)
}

fn validate_edit_order(input: &EditOrderInput) -> Result<(), AdapterError> {
    if input.order_id.trim().is_empty() {
        return Err(AdapterError::Validation {
            field: "order_id".to_string(),
            message: "must be non-empty".to_string(),
        });
    }
    let any_edit = input.amount.is_some()
        || input.price.is_some()
        || input.post_only.is_some()
        || input.reject_post_only.is_some()
        || input.reduce_only.is_some()
        || input.mmp.is_some()
        || input.valid_until.is_some()
        || input.trigger_price.is_some();
    if !any_edit {
        return Err(AdapterError::Validation {
            field: "arguments".to_string(),
            message: "at least one editable field must be present (amount, price, post_only, \
                      reject_post_only, reduce_only, mmp, valid_until, trigger_price)"
                .to_string(),
        });
    }
    if let Some(amount) = input.amount
        && (!amount.is_finite() || amount <= 0.0)
    {
        return Err(AdapterError::Validation {
            field: "amount".to_string(),
            message: format!("must be finite and > 0, got {amount}"),
        });
    }
    if let Some(price) = input.price
        && (!price.is_finite() || price <= 0.0)
    {
        return Err(AdapterError::Validation {
            field: "price".to_string(),
            message: format!("must be finite and > 0, got {price}"),
        });
    }
    if let Some(tp) = input.trigger_price
        && (!tp.is_finite() || tp <= 0.0)
    {
        return Err(AdapterError::Validation {
            field: "trigger_price".to_string(),
            message: format!("must be finite and > 0, got {tp}"),
        });
    }
    Ok(())
}

fn build_edit_request(
    input: EditOrderInput,
) -> Result<deribit_http::model::request::OrderRequest, AdapterError> {
    use deribit_http::model::request::OrderRequest;

    let valid_until = match input.valid_until {
        None => None,
        Some(v) => Some(i64::try_from(v).map_err(|_| AdapterError::Validation {
            field: "valid_until".to_string(),
            message: format!("must fit in i64, got {v}"),
        })?),
    };
    Ok(OrderRequest {
        order_id: Some(input.order_id),
        // `instrument_name` is unused by the upstream `edit_order`
        // path, but the struct field is non-optional. The empty
        // string round-trips harmlessly because `edit_order` only
        // serialises the fields it needs.
        instrument_name: String::new(),
        amount: input.amount,
        contracts: None,
        type_: None,
        label: None,
        price: input.price,
        time_in_force: None,
        display_amount: None,
        post_only: input.post_only,
        reject_post_only: input.reject_post_only,
        reduce_only: input.reduce_only,
        trigger_price: input.trigger_price,
        trigger_offset: None,
        trigger: None,
        advanced: None,
        mmp: input.mmp,
        valid_until,
        linked_order_type: None,
        trigger_fill_condition: None,
        otoco_config: None,
    })
}

// ----- cancel_order -------------------------------------------------

/// `cancel_order` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct CancelOrderInput {
    /// Order id returned from `place_order`.
    pub order_id: String,
}

fn cancel_order_tool() -> ToolEntry {
    let schema = schema_for::<CancelOrderInput>();
    let descriptor = Tool::new("cancel_order", "Cancel one open order by its id.", schema);
    let handler: ToolHandlerFn = Arc::new(|ctx, input| Box::pin(handle_cancel_order(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Trading,
        handler,
    }
}

async fn handle_cancel_order(ctx: &AdapterContext, input: Value) -> Result<Value, AdapterError> {
    let input: CancelOrderInput = parse(input)?;
    let order_id = input.order_id.trim();
    if order_id.is_empty() {
        return Err(AdapterError::Validation {
            field: "order_id".to_string(),
            message: "must be non-empty".to_string(),
        });
    }
    match ctx.config.order_transport {
        crate::config::OrderTransport::Http => {
            let result = ctx.http.cancel_order(order_id).await?;
            Ok(serde_json::to_value(&result)?)
        }
        #[cfg(feature = "fix")]
        crate::config::OrderTransport::Fix => {
            let fix = ctx.ensure_fix().await?;
            {
                let guard = fix.lock().await;
                guard.cancel_order(order_id.to_string()).await?;
            }
            // FIX `OrderCancelRequest (F)` returns ack via the
            // inbound stream; the upstream wrapper resolves to `()`
            // on success. Synthesize the same shape the HTTP path
            // surfaces (`OrderInfoResponse`-style) so the LLM sees a
            // consistent payload.
            Ok(serde_json::json!({
                "order_id": order_id,
                "order_state": "cancelled",
                "transport": "fix"
            }))
        }
        #[cfg(not(feature = "fix"))]
        crate::config::OrderTransport::Fix => Err(AdapterError::not_enabled(
            "cancel_order",
            "build with --features=fix",
        )),
    }
}

// ----- cancel_all_by_currency ---------------------------------------

/// `cancel_all_by_currency` input.
///
/// Mass-cancels every open order in the given currency.
/// Irreversible — use with care.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct CancelAllByCurrencyInput {
    /// Currency to mass-cancel orders for (`BTC`, `ETH`, `USDC`, …).
    pub currency: String,
}

fn cancel_all_by_currency_tool() -> ToolEntry {
    let schema = schema_for::<CancelAllByCurrencyInput>();
    let descriptor = Tool::new(
        "cancel_all_by_currency",
        "Mass-cancel every open order for a currency. Returns \
         {\"cancelled\": <count>}. Irreversible — use with care.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_cancel_all_by_currency(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Trading,
        handler,
    }
}

async fn handle_cancel_all_by_currency(
    ctx: &AdapterContext,
    input: Value,
) -> Result<Value, AdapterError> {
    let input: CancelAllByCurrencyInput = parse(input)?;
    let currency = input.currency.trim();
    if currency.is_empty() {
        return Err(AdapterError::Validation {
            field: "currency".to_string(),
            message: "must be non-empty".to_string(),
        });
    }
    warn_if_fix_transport(ctx, "cancel_all_by_currency");
    let cancelled = ctx.http.cancel_all_by_currency(currency).await?;
    Ok(serde_json::json!({ "cancelled": cancelled }))
}

// ----- cancel_all_by_instrument -------------------------------------

/// `cancel_all_by_instrument` input.
///
/// Mass-cancels every open order on the given instrument.
/// Irreversible — use with care.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct CancelAllByInstrumentInput {
    /// Instrument identifier (`BTC-PERPETUAL`, …).
    pub instrument_name: String,
}

fn cancel_all_by_instrument_tool() -> ToolEntry {
    let schema = schema_for::<CancelAllByInstrumentInput>();
    let descriptor = Tool::new(
        "cancel_all_by_instrument",
        "Mass-cancel every open order on an instrument. Returns \
         {\"cancelled\": <count>}. Irreversible — use with care.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_cancel_all_by_instrument(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Trading,
        handler,
    }
}

async fn handle_cancel_all_by_instrument(
    ctx: &AdapterContext,
    input: Value,
) -> Result<Value, AdapterError> {
    let input: CancelAllByInstrumentInput = parse(input)?;
    let instrument = input.instrument_name.trim();
    if instrument.is_empty() {
        return Err(AdapterError::Validation {
            field: "instrument_name".to_string(),
            message: "must be non-empty".to_string(),
        });
    }
    warn_if_fix_transport(ctx, "cancel_all_by_instrument");
    let cancelled = ctx.http.cancel_all_by_instrument(instrument).await?;
    Ok(serde_json::json!({ "cancelled": cancelled }))
}

/// `cancel_all_*` always uses HTTP because the upstream
/// `deribit-fix 0.3` does not expose an `OrderMassCancelRequest (q)`
/// helper. Log at WARN when the dispatch deliberately bypasses the
/// configured FIX transport so the operator notices.
fn warn_if_fix_transport(ctx: &AdapterContext, tool: &str) {
    match ctx.config.order_transport {
        crate::config::OrderTransport::Http => {}
        crate::config::OrderTransport::Fix => {
            tracing::warn!(
                tool,
                "`{tool}` always dispatches through HTTP — `deribit-fix 0.3` has \
                 no native mass-cancel helper. The active FIX session is unused \
                 for this call."
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn limit_input() -> PlaceOrderInput {
        PlaceOrderInput {
            instrument_name: "BTC-PERPETUAL".to_string(),
            side: Side::Buy,
            amount: 10.0,
            order_type: PlaceOrderType::Limit,
            price: Some(50_000.0),
            time_in_force: None,
            label: None,
            trigger_price: None,
            trigger: None,
            post_only: None,
            reject_post_only: None,
            reduce_only: None,
            mmp: None,
            valid_until: None,
        }
    }

    #[test]
    fn limit_without_price_rejected() {
        let mut input = limit_input();
        input.price = None;
        let err = validate_place_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "price"));
    }

    #[test]
    fn stop_limit_without_trigger_price_rejected() {
        let mut input = limit_input();
        input.order_type = PlaceOrderType::StopLimit;
        input.trigger = Some(PlaceTrigger::IndexPrice);
        let err = validate_place_order(&input).unwrap_err();
        assert!(
            matches!(err, AdapterError::Validation { ref field, .. } if field == "trigger_price")
        );
    }

    #[test]
    fn stop_limit_without_trigger_rejected() {
        let mut input = limit_input();
        input.order_type = PlaceOrderType::StopLimit;
        input.trigger_price = Some(45_000.0);
        let err = validate_place_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "trigger"));
    }

    #[test]
    fn negative_amount_rejected() {
        let mut input = limit_input();
        input.amount = -1.0;
        let err = validate_place_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "amount"));
    }

    #[test]
    fn nan_amount_rejected() {
        let mut input = limit_input();
        input.amount = f64::NAN;
        let err = validate_place_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "amount"));
    }

    #[test]
    fn nan_price_rejected() {
        let mut input = limit_input();
        input.price = Some(f64::NAN);
        let err = validate_place_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "price"));
    }

    #[test]
    fn market_without_price_accepted() {
        let mut input = limit_input();
        input.order_type = PlaceOrderType::Market;
        input.price = None;
        validate_place_order(&input).unwrap();
    }

    #[test]
    fn full_stop_limit_accepted() {
        let mut input = limit_input();
        input.order_type = PlaceOrderType::StopLimit;
        input.trigger_price = Some(45_000.0);
        input.trigger = Some(PlaceTrigger::MarkPrice);
        validate_place_order(&input).unwrap();
    }

    #[test]
    fn build_request_round_trips_buy_side() {
        let input = limit_input();
        let (side, req) = build_order_request(input).unwrap();
        assert_eq!(side, Side::Buy);
        assert_eq!(req.instrument_name, "BTC-PERPETUAL");
        assert_eq!(req.amount, Some(10.0));
        assert_eq!(req.price, Some(50_000.0));
    }

    #[test]
    fn valid_until_overflow_rejected() {
        let mut input = limit_input();
        input.valid_until = Some(u64::MAX);
        let err = build_order_request(input).unwrap_err();
        assert!(
            matches!(err, AdapterError::Validation { ref field, .. } if field == "valid_until")
        );
    }

    fn edit_input() -> EditOrderInput {
        EditOrderInput {
            order_id: "ORDER-1".to_string(),
            amount: Some(20.0),
            price: Some(51_000.0),
            post_only: None,
            reject_post_only: None,
            reduce_only: None,
            mmp: None,
            valid_until: None,
            trigger_price: None,
        }
    }

    #[test]
    fn edit_empty_order_id_rejected() {
        let mut input = edit_input();
        input.order_id = "  ".to_string();
        let err = validate_edit_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "order_id"));
    }

    #[test]
    fn edit_negative_amount_rejected() {
        let mut input = edit_input();
        input.amount = Some(-1.0);
        let err = validate_edit_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "amount"));
    }

    #[test]
    fn edit_nan_price_rejected() {
        let mut input = edit_input();
        input.price = Some(f64::NAN);
        let err = validate_edit_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "price"));
    }

    #[test]
    fn edit_partial_input_accepted() {
        let mut input = edit_input();
        input.price = None;
        validate_edit_order(&input).unwrap();
        let req = build_edit_request(input).unwrap();
        assert_eq!(req.order_id.as_deref(), Some("ORDER-1"));
        assert_eq!(req.amount, Some(20.0));
        assert_eq!(req.price, None);
    }

    #[test]
    fn linear_instrument_classification() {
        assert!(is_linear_instrument("BTC_USDC-PERPETUAL"));
        assert!(is_linear_instrument("ETH_USDT-29SEP24"));
        assert!(!is_linear_instrument("BTC-PERPETUAL"));
        assert!(!is_linear_instrument("ETH-29SEP24"));
        assert!(!is_linear_instrument("BTC-29SEP24-50000-C"));
    }

    #[test]
    fn option_instrument_classification() {
        assert!(is_option_instrument("BTC-29SEP24-50000-C"));
        assert!(is_option_instrument("ETH-30JUN23-1500-P"));
        assert!(!is_option_instrument("BTC-PERPETUAL"));
        assert!(!is_option_instrument("BTC-29SEP24"));
        // Last segment looks like an option flag but the strike
        // doesn't parse — fall back to non-option.
        assert!(!is_option_instrument("BTC-FOO-BAR-C"));
        assert_eq!(option_underlying_base("BTC-29SEP24-50000-C"), Some("BTC"));
        assert_eq!(option_underlying_base("ETH-30JUN23-1500-P"), Some("ETH"));
    }

    fn ctx_with_cap(cap: Option<u64>) -> AdapterContext {
        use crate::config::{Config, LogFormat, OrderTransport, Transport};
        use std::net::SocketAddr;
        let cfg = Config {
            endpoint: "https://test.deribit.com".to_string(),
            client_id: Some("id".to_string()),
            client_secret: Some("secret".to_string()),
            allow_trading: true,
            max_order_usd: cap,
            transport: Transport::Stdio,
            http_listen: SocketAddr::from(([127, 0, 0, 1], 8723)),
            http_bearer_token: None,
            log_format: LogFormat::Text,
            order_transport: OrderTransport::Http,
        };
        AdapterContext::new(Arc::new(cfg)).expect("ctx")
    }

    #[tokio::test]
    async fn cap_unset_is_noop() {
        let ctx = ctx_with_cap(None);
        enforce_size_cap(&ctx, "BTC-PERPETUAL", 1_000_000.0, Some(50_000.0))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn inverse_notional_uses_amount() {
        // BTC-PERPETUAL inverse: amount IS USD notional. 100k > 10k cap.
        let ctx = ctx_with_cap(Some(10_000));
        let err = enforce_size_cap(&ctx, "BTC-PERPETUAL", 100_000.0, Some(50_000.0))
            .await
            .unwrap_err();
        match err {
            AdapterError::SizeCapExceeded { requested, cap } => {
                assert!((requested - 100_000.0).abs() < 1e-6);
                assert!((cap - 10_000.0).abs() < 1e-6);
            }
            other => panic!("unexpected: {other:?}"),
        }
    }

    #[tokio::test]
    async fn inverse_under_cap_passes() {
        let ctx = ctx_with_cap(Some(10_000));
        // 5_000 USD notional, well under the 10_000 cap.
        enforce_size_cap(&ctx, "BTC-PERPETUAL", 5_000.0, Some(50_000.0))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn linear_notional_uses_price_times_amount() {
        // Linear: notional = amount * price = 0.5 * 100_000 = 50_000 > 10_000.
        let ctx = ctx_with_cap(Some(10_000));
        let err = enforce_size_cap(&ctx, "BTC_USDC-PERPETUAL", 0.5, Some(100_000.0))
            .await
            .unwrap_err();
        assert!(matches!(err, AdapterError::SizeCapExceeded { .. }));
    }

    #[test]
    fn edit_no_fields_rejected() {
        let input = EditOrderInput {
            order_id: "ORDER-1".to_string(),
            amount: None,
            price: None,
            post_only: None,
            reject_post_only: None,
            reduce_only: None,
            mmp: None,
            valid_until: None,
            trigger_price: None,
        };
        let err = validate_edit_order(&input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "arguments"));
    }

    #[test]
    fn edit_valid_until_overflow_rejected() {
        let mut input = edit_input();
        input.valid_until = Some(u64::MAX);
        let err = build_edit_request(input).unwrap_err();
        assert!(
            matches!(err, AdapterError::Validation { ref field, .. } if field == "valid_until")
        );
    }

    #[cfg(feature = "fix")]
    #[test]
    fn build_fix_new_order_request_round_trips_buy_limit() {
        use deribit_fix::model::request::{
            OrderSide as FixSide, OrderType as FixOrderType, TimeInForce as FixTif,
        };
        let input = limit_input();
        let request = build_fix_new_order_request(input).unwrap();
        assert_eq!(request.instrument_name, "BTC-PERPETUAL");
        assert!((request.amount - 10.0).abs() < 1e-9);
        assert!(matches!(request.side, FixSide::Buy));
        assert!(matches!(request.order_type, FixOrderType::Limit));
        assert!(matches!(request.time_in_force, FixTif::GoodTilCancelled));
        assert_eq!(request.price, Some(50_000.0));
        assert_eq!(request.stop_price, None);
        assert!(request.post_only.is_none());
    }

    #[cfg(feature = "fix")]
    #[test]
    fn build_fix_new_order_request_maps_stop_limit_with_trigger() {
        use deribit_fix::model::request::{OrderType as FixOrderType, TriggerType as FixTrigger};
        let mut input = limit_input();
        input.order_type = PlaceOrderType::StopLimit;
        input.trigger_price = Some(45_000.0);
        input.trigger = Some(PlaceTrigger::MarkPrice);
        let request = build_fix_new_order_request(input).unwrap();
        assert!(matches!(request.order_type, FixOrderType::StopLimit));
        assert_eq!(request.stop_price, Some(45_000.0));
        assert!(matches!(request.trigger, Some(FixTrigger::MarkPrice)));
    }

    #[cfg(feature = "fix")]
    #[test]
    fn build_fix_new_order_request_overflow_rejects_valid_until() {
        let mut input = limit_input();
        input.valid_until = Some(u64::MAX);
        let err = build_fix_new_order_request(input).unwrap_err();
        assert!(
            matches!(err, AdapterError::Validation { ref field, .. } if field == "valid_until")
        );
    }

    #[cfg(feature = "fix")]
    #[test]
    fn build_fix_new_order_request_rejects_mmp() {
        let mut input = limit_input();
        input.mmp = Some(true);
        let err = build_fix_new_order_request(input).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { ref field, .. } if field == "mmp"));
    }

    #[cfg(feature = "fix")]
    #[test]
    fn synthesize_fix_order_response_matches_documented_shape() {
        use deribit_fix::model::request::{
            NewOrderRequest, OrderSide as FixSide, OrderType as FixOrderType, TimeInForce as FixTif,
        };
        let request = NewOrderRequest {
            instrument_name: "BTC-PERPETUAL".to_string(),
            amount: 10.0,
            order_type: FixOrderType::Limit,
            side: FixSide::Buy,
            price: Some(50_000.0),
            time_in_force: FixTif::GoodTilCancelled,
            post_only: Some(true),
            reduce_only: None,
            label: Some("test".to_string()),
            stop_price: None,
            trigger: None,
            advanced: None,
            max_show: None,
            reject_post_only: None,
            valid_until: None,
            client_order_id: None,
        };
        let response = synthesize_fix_order_response("ORDER-1", &request);
        assert_eq!(response["order"]["order_id"], "ORDER-1");
        assert_eq!(response["order"]["instrument_name"], "BTC-PERPETUAL");
        assert_eq!(response["order"]["direction"], "buy");
        assert_eq!(response["order"]["order_type"], "limit");
        assert_eq!(response["order"]["price"], 50_000.0);
        assert_eq!(response["order"]["post_only"], true);
        assert_eq!(response["order"]["reduce_only"], false);
        assert_eq!(response["order"]["label"], "test");
        assert_eq!(response["order"]["order_state"], "open");
        assert_eq!(response["order"]["transport"], "fix");
        assert_eq!(response["trades"], serde_json::json!([]));
    }
}