Skip to main content

nautilus_kraken/http/futures/
models.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Data models for Kraken Futures HTTP API responses.
17
18use ahash::AHashMap;
19use nautilus_core::{UnixNanos, datetime::unix_nanos_to_iso8601_millis};
20use nautilus_model::{enums::TimeInForce, identifiers::VenueOrderId};
21use rust_decimal::Decimal;
22use serde::{Deserialize, Serialize, de::DeserializeOwned};
23use serde_json::value::RawValue;
24
25use crate::{
26    common::{
27        enums::{
28            KrakenApiResult, KrakenFillType, KrakenFuturesHistoryDirection,
29            KrakenFuturesHistoryOrderType, KrakenFuturesOrderEventType,
30            KrakenFuturesOrderLifecycleStatus, KrakenFuturesOrderStatus, KrakenFuturesOrderType,
31            KrakenInstrumentType, KrakenOrderSide, KrakenPositionSide, KrakenSendStatus,
32            KrakenTriggerSide, KrakenTriggerSignal,
33        },
34        serialization::{
35            decimal, decimal_map, deserialize_decimal_pair, optional_decimal,
36            optional_decimal_or_empty,
37        },
38    },
39    http::error::KrakenHttpError,
40};
41
42// Futures Instruments Models
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct FuturesMarginLevel {
47    /// Number of contracts (for inverse futures) or notional units (for flexible futures).
48    /// The field name varies: `contracts` for inverse, `numNonContractUnits` for flexible.
49    #[serde(alias = "numNonContractUnits", default, with = "decimal")]
50    pub contracts: Decimal,
51    #[serde(with = "decimal")]
52    pub initial_margin: Decimal,
53    #[serde(with = "decimal")]
54    pub maintenance_margin: Decimal,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct FuturesInstrument {
60    pub symbol: String,
61    #[serde(rename = "type")]
62    pub instrument_type: KrakenInstrumentType,
63    /// Only present for inverse futures, not for flexible futures.
64    #[serde(default)]
65    pub underlying: Option<String>,
66    #[serde(with = "decimal")]
67    pub tick_size: Decimal,
68    #[serde(with = "decimal")]
69    pub contract_size: Decimal,
70    pub tradeable: bool,
71    #[serde(default, with = "optional_decimal")]
72    pub impact_mid_size: Option<Decimal>,
73    #[serde(default, with = "optional_decimal")]
74    pub max_position_size: Option<Decimal>,
75    pub opening_date: String,
76    pub margin_levels: Vec<FuturesMarginLevel>,
77    #[serde(default)]
78    pub funding_rate_coefficient: Option<i32>,
79    #[serde(default, with = "optional_decimal")]
80    pub max_relative_funding_rate: Option<Decimal>,
81    #[serde(default)]
82    pub isin: Option<String>,
83    pub contract_value_trade_precision: i32,
84    pub post_only: bool,
85    /// Maker Protection hold window in milliseconds for this market.
86    ///
87    /// Only present when the venue has Maker Protection configured for the
88    /// market; absent means no hold (treat the same as zero).
89    #[serde(default)]
90    pub maker_protection_millis: Option<i64>,
91    #[serde(default)]
92    pub fee_schedule_uid: Option<String>,
93    pub mtf: bool,
94    pub base: String,
95    pub quote: String,
96    pub pair: String,
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct FuturesInstrumentsResponse {
101    pub result: KrakenApiResult,
102    pub instruments: Vec<FuturesInstrument>,
103}
104
105// Futures Ticker Models
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108#[serde(rename_all = "camelCase")]
109pub struct FuturesTicker {
110    pub symbol: String,
111    #[serde(default, with = "optional_decimal")]
112    pub last: Option<Decimal>,
113    #[serde(default)]
114    pub last_time: Option<String>,
115    pub tag: String,
116    pub pair: String,
117    #[serde(default, with = "optional_decimal")]
118    pub mark_price: Option<Decimal>,
119    #[serde(default, with = "optional_decimal")]
120    pub bid: Option<Decimal>,
121    #[serde(default, with = "optional_decimal")]
122    pub bid_size: Option<Decimal>,
123    #[serde(default, with = "optional_decimal")]
124    pub ask: Option<Decimal>,
125    #[serde(default, with = "optional_decimal")]
126    pub ask_size: Option<Decimal>,
127    #[serde(rename = "vol24h", default, with = "optional_decimal")]
128    pub vol_24h: Option<Decimal>,
129    #[serde(default, with = "optional_decimal")]
130    pub volume_quote: Option<Decimal>,
131    #[serde(default, with = "optional_decimal")]
132    pub open_interest: Option<Decimal>,
133    #[serde(rename = "open24h", default, with = "optional_decimal")]
134    pub open_24h: Option<Decimal>,
135    #[serde(rename = "high24h", default, with = "optional_decimal")]
136    pub high_24h: Option<Decimal>,
137    #[serde(rename = "low24h", default, with = "optional_decimal")]
138    pub low_24h: Option<Decimal>,
139    #[serde(default, with = "optional_decimal")]
140    pub last_size: Option<Decimal>,
141    #[serde(default, with = "optional_decimal")]
142    pub funding_rate: Option<Decimal>,
143    #[serde(default, with = "optional_decimal")]
144    pub funding_rate_prediction: Option<Decimal>,
145    #[serde(default)]
146    pub suspended: bool,
147    #[serde(default, with = "optional_decimal")]
148    pub index_price: Option<Decimal>,
149    #[serde(default)]
150    pub post_only: bool,
151    #[serde(rename = "change24h", default, with = "optional_decimal")]
152    pub change_24h: Option<Decimal>,
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize)]
156#[serde(rename_all = "camelCase")]
157pub struct FuturesTickersResponse {
158    pub result: KrakenApiResult,
159    #[serde(default)]
160    pub server_time: Option<String>,
161    pub tickers: Vec<FuturesTicker>,
162}
163
164// Futures Order Book Models
165
166/// A `[price, qty]` pair from the Kraken Futures orderbook endpoint.
167#[derive(Debug, Clone, Serialize)]
168pub struct FuturesOrderBookLevel {
169    #[serde(serialize_with = "decimal::serialize")]
170    pub price: Decimal,
171    #[serde(serialize_with = "decimal::serialize")]
172    pub qty: Decimal,
173}
174
175impl<'de> serde::Deserialize<'de> for FuturesOrderBookLevel {
176    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
177    where
178        D: serde::Deserializer<'de>,
179    {
180        let arr = deserialize_decimal_pair(deserializer)?;
181        Ok(Self {
182            price: arr.0,
183            qty: arr.1,
184        })
185    }
186}
187
188#[derive(Debug, Clone, Serialize, Deserialize)]
189#[serde(rename_all = "camelCase")]
190pub struct FuturesOrderBookData {
191    pub bids: Vec<FuturesOrderBookLevel>,
192    pub asks: Vec<FuturesOrderBookLevel>,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize)]
196#[serde(rename_all = "camelCase")]
197pub struct FuturesOrderBookResponse {
198    pub result: KrakenApiResult,
199    pub order_book: FuturesOrderBookData,
200    #[serde(default)]
201    pub server_time: Option<String>,
202}
203
204// Futures Historical Funding Rates Models
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
207#[serde(rename_all = "camelCase")]
208pub struct FuturesHistoricalFundingRate {
209    pub timestamp: String,
210    #[serde(with = "decimal")]
211    pub relative_funding_rate: Decimal,
212    #[serde(with = "decimal")]
213    pub funding_rate: Decimal,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
217#[serde(rename_all = "camelCase")]
218pub struct FuturesHistoricalFundingRatesResponse {
219    pub result: KrakenApiResult,
220    pub rates: Vec<FuturesHistoricalFundingRate>,
221}
222
223// Futures OHLC (Candles) Models
224
225#[derive(Debug, Clone, Serialize, Deserialize)]
226pub struct FuturesCandle {
227    pub time: i64,
228    pub open: String,
229    pub high: String,
230    pub low: String,
231    pub close: String,
232    pub volume: String,
233}
234
235#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct FuturesCandlesResponse {
237    pub candles: Vec<FuturesCandle>,
238}
239
240// Futures Open Orders Models
241
242#[derive(Debug, Clone, Serialize, Deserialize)]
243#[serde(rename_all = "camelCase")]
244pub struct FuturesOpenOrder {
245    #[serde(rename = "order_id")]
246    pub order_id: String,
247    pub symbol: String,
248    pub side: KrakenOrderSide,
249    pub order_type: KrakenFuturesOrderType,
250    #[serde(default, with = "optional_decimal")]
251    pub limit_price: Option<Decimal>,
252    #[serde(default, with = "optional_decimal")]
253    pub stop_price: Option<Decimal>,
254    #[serde(default, with = "optional_decimal")]
255    pub unfilled_size: Option<Decimal>,
256    pub received_time: String,
257    pub status: KrakenFuturesOrderStatus,
258    #[serde(with = "decimal")]
259    pub filled_size: Decimal,
260    #[serde(default)]
261    pub reduce_only: Option<bool>,
262    pub last_update_time: String,
263    #[serde(default)]
264    pub trigger_signal: Option<KrakenTriggerSignal>,
265    /// The client order ID under the key the open-orders API documents.
266    #[serde(rename = "cliOrdId", default)]
267    pub cli_ord_id: Option<String>,
268    /// The client order ID under the snake-case key the WebSocket feeds use, read as well since the
269    /// key the REST response carries is not verified against the live venue.
270    #[serde(rename = "cli_ord_id", default)]
271    pub cli_ord_id_snake_case: Option<String>,
272}
273
274impl FuturesOpenOrder {
275    /// The client order ID under whichever key the response carries.
276    #[must_use]
277    pub fn client_order_id(&self) -> Option<&str> {
278        self.cli_ord_id
279            .as_deref()
280            .or(self.cli_ord_id_snake_case.as_deref())
281    }
282}
283
284#[derive(Debug, Clone, Serialize, Deserialize)]
285#[serde(rename_all = "camelCase")]
286pub struct FuturesOpenOrdersResponse {
287    pub result: KrakenApiResult,
288    #[serde(default)]
289    pub server_time: Option<String>,
290    #[serde(default)]
291    pub error: Option<String>,
292    #[serde(default)]
293    pub open_orders: Vec<FuturesOpenOrder>,
294}
295
296// Futures Orders Status Models (/orders/status)
297
298/// Order body returned by the `/orders/status` endpoint.
299#[derive(Debug, Clone, Serialize, Deserialize)]
300#[serde(rename_all = "camelCase")]
301pub struct FuturesCachedOrder {
302    pub order_id: String,
303    #[serde(default)]
304    pub cli_ord_id: Option<String>,
305    pub symbol: String,
306    pub side: KrakenOrderSide,
307    #[serde(default, with = "optional_decimal")]
308    pub quantity: Option<Decimal>,
309    #[serde(default, with = "optional_decimal")]
310    pub filled: Option<Decimal>,
311    #[serde(default, with = "optional_decimal")]
312    pub limit_price: Option<Decimal>,
313    #[serde(default)]
314    pub reduce_only: bool,
315    pub timestamp: String,
316    pub last_update_timestamp: String,
317}
318
319/// A single order status entry returned by the `/orders/status` endpoint.
320#[derive(Debug, Clone, Serialize, Deserialize)]
321#[serde(rename_all = "camelCase")]
322pub struct FuturesOrderStatusDetails {
323    pub order: FuturesCachedOrder,
324    pub status: KrakenFuturesOrderLifecycleStatus,
325    #[serde(default)]
326    pub update_reason: Option<String>,
327    #[serde(default)]
328    pub error: Option<String>,
329}
330
331/// Response from the Kraken Futures `/orders/status` endpoint, which reports
332/// orders open or with a fill/cancel event in the last 5 seconds.
333#[derive(Debug, Clone, Serialize, Deserialize)]
334#[serde(rename_all = "camelCase")]
335pub struct FuturesOrdersStatusResponse {
336    pub result: KrakenApiResult,
337    #[serde(default)]
338    pub server_time: Option<String>,
339    #[serde(default)]
340    pub error: Option<String>,
341    #[serde(default)]
342    pub orders: Vec<FuturesOrderStatusDetails>,
343}
344
345// Futures Order Events Models
346
347/// Wrapper for an order event containing the order data and event type.
348#[derive(Debug, Clone, Serialize, Deserialize)]
349#[serde(rename_all = "camelCase")]
350pub struct FuturesOrderEventWrapper {
351    pub order: FuturesOrderEvent,
352    #[serde(rename = "type")]
353    pub event_type: KrakenFuturesOrderEventType,
354    #[serde(default, with = "optional_decimal")]
355    pub reduced_quantity: Option<Decimal>,
356    /// When the event happened, in milliseconds; see [`SkippedHistoryRow::event_ms`].
357    #[serde(skip)]
358    pub event_ms: i64,
359    /// How far the state this row describes is known to reach, in milliseconds, which an unread
360    /// row of the order must be older than for the state to stand. A cancel or reject closes the
361    /// order at its event. Any other row can describe the order as it stood before the event, as a
362    /// refused edit does, so it counts from the earlier of the event and the order's own stamp.
363    #[serde(skip)]
364    pub state_ms: i64,
365}
366
367/// The actual order data within an order event.
368#[derive(Debug, Clone, Serialize, Deserialize)]
369#[serde(rename_all = "camelCase")]
370pub struct FuturesOrderEvent {
371    pub order_id: String,
372    #[serde(default)]
373    pub cli_ord_id: Option<String>,
374    #[serde(rename = "type")]
375    pub order_type: KrakenFuturesOrderType,
376    pub symbol: String,
377    pub side: KrakenOrderSide,
378    #[serde(with = "decimal")]
379    pub quantity: Decimal,
380    #[serde(with = "decimal")]
381    pub filled: Decimal,
382    #[serde(default, with = "optional_decimal")]
383    pub limit_price: Option<Decimal>,
384    #[serde(default, with = "optional_decimal")]
385    pub stop_price: Option<Decimal>,
386    pub timestamp: String,
387    pub last_update_timestamp: String,
388    #[serde(default)]
389    pub reduce_only: bool,
390    pub time_in_force: TimeInForce,
391    pub post_only: bool,
392}
393
394/// Order events in the shape the readers consume, built from [`FuturesOrderHistoryResponse`].
395///
396/// This is a projection, not a wire type: a page is decoded as [`FuturesOrderHistoryResponse`]
397/// and converted, so a body of another shape cannot read as an empty page.
398#[derive(Debug, Clone)]
399pub struct FuturesOrderEventsResponse {
400    pub server_time: Option<String>,
401    pub order_events: Vec<FuturesOrderEventWrapper>,
402    pub continuation_token: Option<String>,
403    /// Rows the projection could not represent. Each reader decides what a row means for it.
404    pub skipped_rows: Vec<SkippedHistoryRow>,
405    /// The earliest event time on the page in milliseconds, over every element including the
406    /// skipped ones. The venue returns history newest first, so with a continuation token this is
407    /// how far back the page reaches.
408    pub oldest_event_ms: Option<i64>,
409}
410
411/// An order history row the projection could not represent, with what could be read of it.
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub struct SkippedHistoryRow {
414    pub order_id: Option<String>,
415    pub tradeable: Option<String>,
416    /// When the event happened, in milliseconds. A stamp before the epoch places the row nowhere,
417    /// so it reads as newer than any state.
418    pub event_ms: i64,
419    /// The row is of a kind the documentation does not list, so the order and contract read from
420    /// it are a guess at its shape: they can withhold an order but rule nothing out.
421    pub undocumented: bool,
422}
423
424impl SkippedHistoryRow {
425    fn new(identity: HistoryRowIdentity, event_ms: i64, undocumented: bool) -> Self {
426        Self {
427            order_id: identity.order_id,
428            tradeable: identity.tradeable,
429            event_ms,
430            undocumented,
431        }
432    }
433
434    fn of_order(order: FuturesOrderHistoryOrder, event_ms: i64) -> Self {
435        Self {
436            order_id: Some(order.uid),
437            tradeable: Some(order.tradeable),
438            event_ms,
439            undocumented: false,
440        }
441    }
442
443    /// Whether this row may be a state of `order_id` that the state at `state_ms` does not
444    /// supersede. A row that names no order may be any order's, as may an undocumented kind.
445    #[must_use]
446    pub fn may_supersede(&self, order_id: &str, state_ms: i64) -> bool {
447        (self.undocumented || self.order_id.as_deref().is_none_or(|id| id == order_id))
448            && self.event_ms >= state_ms
449    }
450}
451
452// Futures Order History Models
453
454/// Response from the Kraken Futures order history endpoint, `/api/history/v3/orders`.
455///
456/// Each element carries one lifecycle event keyed by its kind, and the order inside it names the
457/// contract as `tradeable` and the side as `direction`, with millisecond timestamps. The venue
458/// can answer with a success status and an error body, so `result` and `error` are read before
459/// the shape is checked; see [`Self::into_order_events`].
460#[derive(Debug, Clone, Deserialize)]
461#[serde(rename_all = "camelCase")]
462pub struct FuturesOrderHistoryResponse {
463    #[serde(default)]
464    pub result: Option<KrakenApiResult>,
465    #[serde(default)]
466    pub error: Option<String>,
467    #[serde(default)]
468    pub server_time: Option<String>,
469    #[serde(default)]
470    pub elements: Option<Vec<FuturesOrderHistoryElement>>,
471    #[serde(default)]
472    pub continuation_token: Option<String>,
473}
474
475/// One order history element: the event and when it happened.
476#[derive(Debug, Clone, Deserialize)]
477#[serde(rename_all = "camelCase")]
478pub struct FuturesOrderHistoryElement {
479    pub uid: String,
480    pub timestamp: i64,
481    pub event: FuturesOrderHistoryEvent,
482}
483
484/// An order history event, externally tagged by its kind.
485///
486/// The documented kinds are modeled; one the documentation does not list is kept by name, and one
487/// whose payload does not decode is kept with the reason, so the surrounding page still decodes.
488#[derive(Debug, Clone)]
489pub enum FuturesOrderHistoryEvent {
490    OrderPlaced(FuturesOrderHistoryOrderEvent),
491    OrderUpdated(FuturesOrderHistoryOrderUpdate),
492    OrderCancelled(FuturesOrderHistoryOrderEvent),
493    OrderRejected(FuturesOrderHistoryOrderEvent),
494    /// An edit the venue refused; the order stands as `old_order`.
495    OrderEditRejected(FuturesOrderHistoryEditRejected),
496    /// A request naming an order the venue does not hold; it carries no order state.
497    OrderNotFound(FuturesOrderHistoryOrderNotFound),
498    Unreadable {
499        kind: String,
500        reason: String,
501        identity: HistoryRowIdentity,
502    },
503    Unknown {
504        kind: String,
505        identity: HistoryRowIdentity,
506    },
507}
508
509/// The order and contract a row names, read leniently from a payload that does not decode.
510#[derive(Debug, Clone, Default)]
511pub struct HistoryRowIdentity {
512    pub order_id: Option<String>,
513    pub tradeable: Option<String>,
514}
515
516impl HistoryRowIdentity {
517    /// Reads each field from the first of `positions` holding a usable value. Every other value
518    /// stays raw, so one that `serde_json::Value` could not hold, such as `1e999`, cannot cost the
519    /// row its identity.
520    fn read(payload: &RawValue, positions: &[&str]) -> Self {
521        type RawFields = AHashMap<String, Box<RawValue>>;
522
523        let payload: RawFields = serde_json::from_str(payload.get()).unwrap_or_default();
524        let orders: Vec<RawFields> = positions
525            .iter()
526            .filter_map(|position| payload.get(*position))
527            .filter_map(|order| serde_json::from_str(order.get()).ok())
528            .collect();
529        let field = |name: &str, usable: fn(&str) -> bool| {
530            orders.iter().find_map(|order| {
531                order
532                    .get(name)
533                    .and_then(|value| serde_json::from_str::<String>(value.get()).ok())
534                    .filter(|value| usable(value))
535            })
536        };
537
538        Self {
539            order_id: field("uid", |uid| VenueOrderId::new_checked(uid).is_ok()),
540            tradeable: field("tradeable", |tradeable| !tradeable.is_empty()),
541        }
542    }
543}
544
545/// Decodes a documented kind's payload from its raw JSON text, which keeps a numeric quantity's
546/// digits. A payload that does not decode is an unreadable row rather than a failed page.
547fn read_documented_event<'de, A, T>(
548    map: &mut A,
549    kind: &str,
550    positions: &[&str],
551    wrap: fn(T) -> FuturesOrderHistoryEvent,
552) -> Result<FuturesOrderHistoryEvent, A::Error>
553where
554    A: serde::de::MapAccess<'de>,
555    T: DeserializeOwned,
556{
557    let payload: Box<RawValue> = map.next_value()?;
558
559    Ok(match serde_json::from_str(payload.get()) {
560        Ok(event) => wrap(event),
561        Err(e) => FuturesOrderHistoryEvent::Unreadable {
562            kind: kind.to_string(),
563            reason: e.to_string(),
564            identity: HistoryRowIdentity::read(&payload, positions),
565        },
566    })
567}
568
569impl<'de> Deserialize<'de> for FuturesOrderHistoryEvent {
570    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
571    where
572        D: serde::Deserializer<'de>,
573    {
574        struct EventVisitor;
575
576        impl<'de> serde::de::Visitor<'de> for EventVisitor {
577            type Value = FuturesOrderHistoryEvent;
578
579            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
580                formatter.write_str("an order history event keyed by its kind")
581            }
582
583            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
584            where
585                A: serde::de::MapAccess<'de>,
586            {
587                // The kind is the first key naming a documented event, wherever it sits among any
588                // other keys; the first key is reported when no key does.
589                let mut event = None;
590                let mut undocumented: Option<(String, Box<RawValue>)> = None;
591
592                while let Some(key) = map.next_key::<String>()? {
593                    if event.is_some() {
594                        map.next_value::<serde::de::IgnoredAny>()?;
595                        continue;
596                    }
597
598                    event = Some(match key.as_str() {
599                        "OrderPlaced" => read_documented_event(
600                            &mut map,
601                            &key,
602                            &["order"],
603                            FuturesOrderHistoryEvent::OrderPlaced,
604                        )?,
605                        "OrderUpdated" => read_documented_event(
606                            &mut map,
607                            &key,
608                            &["newOrder", "oldOrder"],
609                            FuturesOrderHistoryEvent::OrderUpdated,
610                        )?,
611                        "OrderCancelled" => read_documented_event(
612                            &mut map,
613                            &key,
614                            &["order"],
615                            FuturesOrderHistoryEvent::OrderCancelled,
616                        )?,
617                        "OrderRejected" => read_documented_event(
618                            &mut map,
619                            &key,
620                            &["order"],
621                            FuturesOrderHistoryEvent::OrderRejected,
622                        )?,
623                        "OrderEditRejected" => read_documented_event(
624                            &mut map,
625                            &key,
626                            &["oldOrder", "attemptedOrder"],
627                            FuturesOrderHistoryEvent::OrderEditRejected,
628                        )?,
629                        "OrderNotFound" => read_documented_event(
630                            &mut map,
631                            &key,
632                            &[],
633                            FuturesOrderHistoryEvent::OrderNotFound,
634                        )?,
635                        _ => {
636                            let payload = map.next_value()?;
637
638                            if undocumented.is_none() {
639                                undocumented = Some((key, payload));
640                            }
641                            continue;
642                        }
643                    });
644                }
645
646                Ok(event.unwrap_or_else(|| {
647                    let (kind, identity) = undocumented.map_or_else(
648                        || (String::new(), HistoryRowIdentity::default()),
649                        |(kind, payload)| {
650                            let identity = HistoryRowIdentity::read(
651                                &payload,
652                                &["order", "newOrder", "oldOrder"],
653                            );
654                            (kind, identity)
655                        },
656                    );
657                    FuturesOrderHistoryEvent::Unknown { kind, identity }
658                }))
659            }
660        }
661
662        deserializer.deserialize_map(EventVisitor)
663    }
664}
665
666/// An event that carries one order: placed, canceled or rejected.
667#[derive(Debug, Clone, Deserialize)]
668#[serde(rename_all = "camelCase")]
669pub struct FuturesOrderHistoryOrderEvent {
670    pub order: FuturesOrderHistoryOrder,
671}
672
673/// An update event, carrying the order before and after the edit.
674#[derive(Debug, Clone, Deserialize)]
675#[serde(rename_all = "camelCase")]
676pub struct FuturesOrderHistoryOrderUpdate {
677    pub new_order: FuturesOrderHistoryOrder,
678}
679
680/// A refused edit, carrying the order as it stands.
681#[derive(Debug, Clone, Deserialize)]
682#[serde(rename_all = "camelCase")]
683pub struct FuturesOrderHistoryEditRejected {
684    pub old_order: FuturesOrderHistoryOrder,
685}
686
687/// A request for an order the venue does not hold.
688#[derive(Debug, Clone, Deserialize)]
689#[serde(rename_all = "camelCase")]
690pub struct FuturesOrderHistoryOrderNotFound {
691    #[serde(default)]
692    pub order_id: Option<String>,
693}
694
695fn deserialize_order_uid<'de, D>(deserializer: D) -> Result<String, D::Error>
696where
697    D: serde::Deserializer<'de>,
698{
699    let uid = String::deserialize(deserializer)?;
700    VenueOrderId::new_checked(&uid).map_err(serde::de::Error::custom)?;
701    Ok(uid)
702}
703
704/// An order as the history endpoint reports it.
705#[derive(Debug, Clone, Deserialize)]
706#[serde(rename_all = "camelCase")]
707pub struct FuturesOrderHistoryOrder {
708    /// An ID that cannot be a venue order ID does not decode, so its row is skipped.
709    #[serde(deserialize_with = "deserialize_order_uid")]
710    pub uid: String,
711    pub tradeable: String,
712    pub direction: KrakenFuturesHistoryDirection,
713    #[serde(with = "decimal")]
714    pub quantity: Decimal,
715    #[serde(with = "decimal")]
716    pub filled: Decimal,
717    /// Absent for a market order, which the venue reports as zero or as an empty string.
718    #[serde(default, deserialize_with = "optional_decimal_or_empty::deserialize")]
719    pub limit_price: Option<Decimal>,
720    #[serde(default)]
721    pub order_type: Option<KrakenFuturesHistoryOrderType>,
722    #[serde(default)]
723    pub client_id: Option<String>,
724    #[serde(default)]
725    pub reduce_only: bool,
726    pub timestamp: i64,
727    pub last_update_timestamp: i64,
728}
729
730fn millis_to_rfc3339(millis: i64) -> Option<String> {
731    let nanos = u64::try_from(millis).ok()?.checked_mul(1_000_000)?;
732    Some(unix_nanos_to_iso8601_millis(UnixNanos::from(nanos)))
733}
734
735impl FuturesOrderHistoryResponse {
736    /// Projects each element onto the event wrapper the readers consume.
737    ///
738    /// A venue error reported with a success status fails the read with the venue's reason, and a
739    /// body without an `elements` array fails it as a parse error, so neither reads as an empty
740    /// page. An update, and a refused edit, are represented by the order as it stands afterwards.
741    /// A not-found event carries no order state and is skipped. A kind the documentation does not
742    /// list, a documented kind whose payload does not decode, an order whose direction the venue
743    /// could not decode, an order whose type is missing or reported as `Unknown`, and an order
744    /// with a timestamp before the epoch may carry order state the projection cannot read, so each
745    /// is skipped with a warning and listed in `skipped_rows`. `Unknown` is how the venue reports a
746    /// source type it could not decode, so it establishes no order type, and in particular not a
747    /// market order. The venue fills the required `limitPrice` of a market order with a zero or
748    /// an empty string and a missing client id with an empty string, so a market-like order (a
749    /// market order or a venue-initiated kind) carries no price and an empty client id is
750    /// `None`; a limit order keeps its price even at zero, since futures instruments allow
751    /// non-positive prices. The contract name is kept as the venue spells it;
752    /// the readers resolve it case-insensitively. The history order carries no trigger price, and
753    /// the engine cannot materialize a stop order without one, so a stop row is reported as the
754    /// limit or market order it executes as once triggered. The order type is the only place the
755    /// history states a time in force or post-only, so it sets both.
756    ///
757    /// # Errors
758    ///
759    /// Returns an error if the body carries a venue error or has no `elements` array.
760    pub fn into_order_events(self) -> Result<FuturesOrderEventsResponse, KrakenHttpError> {
761        if let Some(error) = self.error {
762            return Err(KrakenHttpError::ApiError(vec![error]));
763        }
764
765        if self.result == Some(KrakenApiResult::Error) {
766            return Err(KrakenHttpError::ApiError(vec![
767                "order history request failed without a reason".to_string(),
768            ]));
769        }
770
771        let Some(elements) = self.elements else {
772            return Err(KrakenHttpError::ParseError(
773                "order history page has no `elements` array".to_string(),
774            ));
775        };
776
777        let mut skipped_rows = Vec::new();
778        let oldest_event_ms = elements.iter().map(|element| element.timestamp).min();
779        let order_events = elements
780            .into_iter()
781            .filter_map(|element| {
782                let event_ms = if element.timestamp < 0 {
783                    i64::MAX
784                } else {
785                    element.timestamp
786                };
787                let (order, event_type) = match element.event {
788                    FuturesOrderHistoryEvent::OrderPlaced(event) => {
789                        (event.order, KrakenFuturesOrderEventType::Place)
790                    }
791                    FuturesOrderHistoryEvent::OrderUpdated(event) => {
792                        (event.new_order, KrakenFuturesOrderEventType::Edit)
793                    }
794                    FuturesOrderHistoryEvent::OrderCancelled(event) => {
795                        (event.order, KrakenFuturesOrderEventType::Cancel)
796                    }
797                    FuturesOrderHistoryEvent::OrderRejected(event) => {
798                        (event.order, KrakenFuturesOrderEventType::Reject)
799                    }
800                    FuturesOrderHistoryEvent::OrderEditRejected(event) => {
801                        (event.old_order, KrakenFuturesOrderEventType::Edit)
802                    }
803                    FuturesOrderHistoryEvent::OrderNotFound(event) => {
804                        log::warn!(
805                            "Skipping order history event {} (order not found {:?}): no order state",
806                            element.uid,
807                            event.order_id
808                        );
809                        return None;
810                    }
811                    FuturesOrderHistoryEvent::Unreadable {
812                        kind,
813                        reason,
814                        identity,
815                    } => {
816                        log::warn!(
817                            "Skipping order history event {} of kind {kind} for order {:?} on {:?}: payload does not decode: {reason}",
818                            element.uid,
819                            identity.order_id,
820                            identity.tradeable,
821                        );
822                        skipped_rows.push(SkippedHistoryRow::new(identity, event_ms, false));
823                        return None;
824                    }
825                    FuturesOrderHistoryEvent::Unknown { kind, identity } => {
826                        log::warn!(
827                            "Skipping order history event {} of undocumented kind {kind:?} for order {:?}",
828                            element.uid,
829                            identity.order_id,
830                        );
831                        skipped_rows.push(SkippedHistoryRow::new(identity, event_ms, true));
832                        return None;
833                    }
834                };
835
836                let state_ms = match event_type {
837                    KrakenFuturesOrderEventType::Cancel | KrakenFuturesOrderEventType::Reject => {
838                        element.timestamp
839                    }
840                    _ => order.last_update_timestamp.min(element.timestamp),
841                };
842
843                // The event time is when this state became known; a refused edit, for one,
844                // leaves the order's own stamp at its last change.
845                let (Some(timestamp), Some(last_update_timestamp)) = (
846                    millis_to_rfc3339(order.timestamp),
847                    millis_to_rfc3339(order.last_update_timestamp.max(element.timestamp)),
848                ) else {
849                    log::warn!(
850                        "Skipping order history event {} for order {} on {}: timestamp before the epoch",
851                        element.uid,
852                        order.uid,
853                        order.tradeable
854                    );
855                    skipped_rows.push(SkippedHistoryRow::of_order(order, event_ms));
856                    return None;
857                };
858
859                let side = match order.direction {
860                    KrakenFuturesHistoryDirection::Buy => KrakenOrderSide::Buy,
861                    KrakenFuturesHistoryDirection::Sell => KrakenOrderSide::Sell,
862                    KrakenFuturesHistoryDirection::Unknown => {
863                        log::warn!(
864                            "Skipping order history event {} for order {} on {}: direction unknown",
865                            element.uid,
866                            order.uid,
867                            order.tradeable
868                        );
869                        skipped_rows.push(SkippedHistoryRow::of_order(order, event_ms));
870                        return None;
871                    }
872                };
873
874                // `Unknown` is how the venue reports a source type it could not decode, so
875                // neither it nor a missing type establishes what the order is.
876                let kind = match order.order_type {
877                    Some(KrakenFuturesHistoryOrderType::Unknown) | None => {
878                        let situation = if order.order_type.is_none() {
879                            "order type missing"
880                        } else {
881                            "order type reported as Unknown"
882                        };
883                        log::warn!(
884                            "Skipping order history event {} for order {} (client id {:?}) on {}: {situation}",
885                            element.uid,
886                            order.uid,
887                            order.client_id.as_deref().filter(|id| !id.is_empty()),
888                            order.tradeable
889                        );
890                        skipped_rows.push(SkippedHistoryRow::of_order(order, event_ms));
891                        return None;
892                    }
893                    Some(kind) => kind,
894                };
895
896                let market_like = matches!(
897                    kind,
898                    KrakenFuturesHistoryOrderType::Market
899                        | KrakenFuturesHistoryOrderType::Liquidation
900                        | KrakenFuturesHistoryOrderType::PartialLiquidation
901                        | KrakenFuturesHistoryOrderType::CoveredLiquidation
902                        | KrakenFuturesHistoryOrderType::Assignment
903                        | KrakenFuturesHistoryOrderType::HedgeAssignment
904                        | KrakenFuturesHistoryOrderType::Unwind
905                        | KrakenFuturesHistoryOrderType::Block
906                        | KrakenFuturesHistoryOrderType::Rfq
907                );
908                let limit_price = match kind {
909                    _ if market_like => None,
910                    // A stop with the placeholder price has no limit leg.
911                    KrakenFuturesHistoryOrderType::Stop => {
912                        order.limit_price.filter(|price| !price.is_zero())
913                    }
914                    _ => order.limit_price,
915                };
916                let order_type = match (kind, limit_price) {
917                    (KrakenFuturesHistoryOrderType::Stop, Some(_)) => KrakenFuturesOrderType::Limit,
918                    (KrakenFuturesHistoryOrderType::Stop, None) => KrakenFuturesOrderType::Market,
919                    (kind, _) => kind.into(),
920                };
921                let (time_in_force, post_only) = match kind {
922                    KrakenFuturesHistoryOrderType::Ioc
923                    | KrakenFuturesHistoryOrderType::HedgeImmediateOrCancel => {
924                        (TimeInForce::Ioc, false)
925                    }
926                    KrakenFuturesHistoryOrderType::FillOrKill => (TimeInForce::Fok, false),
927                    KrakenFuturesHistoryOrderType::Post => (TimeInForce::Gtc, true),
928                    _ => (TimeInForce::Gtc, false),
929                };
930
931                Some(FuturesOrderEventWrapper {
932                    order: FuturesOrderEvent {
933                        order_id: order.uid,
934                        cli_ord_id: order.client_id.filter(|id| !id.is_empty()),
935                        order_type,
936                        symbol: order.tradeable,
937                        side,
938                        quantity: order.quantity,
939                        filled: order.filled,
940                        limit_price,
941                        stop_price: None,
942                        timestamp,
943                        last_update_timestamp,
944                        reduce_only: order.reduce_only,
945                        time_in_force,
946                        post_only,
947                    },
948                    event_type,
949                    reduced_quantity: None,
950                    event_ms,
951                    state_ms,
952                })
953            })
954            .collect();
955
956        Ok(FuturesOrderEventsResponse {
957            server_time: self.server_time,
958            order_events,
959            continuation_token: self.continuation_token,
960            skipped_rows,
961            oldest_event_ms,
962        })
963    }
964}
965
966// Futures Fills Models
967
968#[derive(Debug, Clone, Serialize, Deserialize)]
969#[serde(rename_all = "camelCase")]
970pub struct FuturesFill {
971    #[serde(rename = "fill_id")]
972    pub fill_id: String,
973    pub symbol: String,
974    pub side: KrakenOrderSide,
975    #[serde(rename = "order_id")]
976    pub order_id: String,
977    pub fill_time: String,
978    #[serde(with = "decimal")]
979    pub size: Decimal,
980    #[serde(with = "decimal")]
981    pub price: Decimal,
982    pub fill_type: KrakenFillType,
983    /// The client order ID under the key the fills API documents.
984    #[serde(rename = "cliOrdId", default)]
985    pub cli_ord_id: Option<String>,
986    /// The client order ID under the snake-case key the WebSocket feeds use, read as well since the
987    /// key the REST response carries is not verified against the live venue.
988    #[serde(rename = "cli_ord_id", default)]
989    pub cli_ord_id_snake_case: Option<String>,
990    #[serde(rename = "fee_paid", default, with = "optional_decimal")]
991    pub fee_paid: Option<Decimal>,
992    #[serde(rename = "fee_currency", default)]
993    pub fee_currency: Option<String>,
994}
995
996impl FuturesFill {
997    /// The client order ID under whichever key the response carries.
998    #[must_use]
999    pub fn client_order_id(&self) -> Option<&str> {
1000        self.cli_ord_id
1001            .as_deref()
1002            .or(self.cli_ord_id_snake_case.as_deref())
1003    }
1004}
1005
1006#[derive(Debug, Clone, Serialize, Deserialize)]
1007#[serde(rename_all = "camelCase")]
1008pub struct FuturesFillsResponse {
1009    pub result: KrakenApiResult,
1010    #[serde(default)]
1011    pub server_time: Option<String>,
1012    #[serde(default)]
1013    pub error: Option<String>,
1014    #[serde(default)]
1015    pub fills: Vec<FuturesFill>,
1016}
1017
1018// Futures Positions Models
1019
1020#[derive(Debug, Clone, Serialize, Deserialize)]
1021#[serde(rename_all = "camelCase")]
1022pub struct FuturesPosition {
1023    pub side: KrakenPositionSide,
1024    pub symbol: String,
1025    #[serde(with = "decimal")]
1026    pub price: Decimal,
1027    pub fill_time: String,
1028    #[serde(with = "decimal")]
1029    pub size: Decimal,
1030    #[serde(default, with = "optional_decimal")]
1031    pub unrealized_funding: Option<Decimal>,
1032}
1033
1034#[derive(Debug, Clone, Serialize, Deserialize)]
1035#[serde(rename_all = "camelCase")]
1036pub struct FuturesOpenPositionsResponse {
1037    pub result: KrakenApiResult,
1038    #[serde(default)]
1039    pub server_time: Option<String>,
1040    #[serde(default)]
1041    pub error: Option<String>,
1042    #[serde(default)]
1043    pub open_positions: Vec<FuturesPosition>,
1044}
1045
1046// Futures Order Execution Models
1047
1048#[derive(Debug, Clone, Serialize, Deserialize)]
1049#[serde(rename_all = "camelCase")]
1050pub struct FuturesSendOrderResponse {
1051    pub result: KrakenApiResult,
1052    #[serde(default)]
1053    pub server_time: Option<String>,
1054    #[serde(default)]
1055    pub error: Option<String>,
1056    pub send_status: Option<FuturesSendStatus>,
1057}
1058
1059#[derive(Debug, Clone, Serialize, Deserialize)]
1060#[serde(rename_all = "camelCase")]
1061pub struct FuturesSendStatus {
1062    #[serde(rename = "order_id", default)]
1063    pub order_id: Option<String>,
1064    #[serde(rename = "order_tag", default)]
1065    pub order_tag: Option<String>,
1066    pub status: String,
1067    #[serde(default)]
1068    pub order_events: Option<Vec<FuturesSendOrderEvent>>,
1069    #[serde(rename = "cli_ord_id", default)]
1070    pub cli_ord_id: Option<String>,
1071    #[serde(rename = "receivedTime", default)]
1072    pub received_time: Option<String>,
1073}
1074
1075#[derive(Debug, Clone, Serialize, Deserialize)]
1076#[serde(rename_all = "camelCase")]
1077pub struct FuturesSendOrderEvent {
1078    #[serde(rename = "type")]
1079    pub event_type: KrakenFuturesOrderEventType,
1080    #[serde(default)]
1081    pub order: Option<FuturesOrderEventData>,
1082    #[serde(default)]
1083    pub order_trigger: Option<FuturesOrderTriggerData>,
1084    #[serde(default, with = "optional_decimal")]
1085    pub reduced_quantity: Option<Decimal>,
1086    // Execution event fields
1087    #[serde(rename = "executionId", default)]
1088    pub execution_id: Option<String>,
1089    #[serde(default, with = "optional_decimal")]
1090    pub price: Option<Decimal>,
1091    #[serde(default, with = "optional_decimal")]
1092    pub amount: Option<Decimal>,
1093    #[serde(rename = "orderPriorEdit", default)]
1094    pub order_prior_edit: Option<Box<FuturesOrderEventData>>,
1095    #[serde(rename = "orderPriorExecution", default)]
1096    pub order_prior_execution: Option<Box<FuturesOrderEventData>>,
1097    #[serde(rename = "takerReducedQuantity", default, with = "optional_decimal")]
1098    pub taker_reduced_quantity: Option<Decimal>,
1099    // Reject event fields
1100    #[serde(default)]
1101    pub reason: Option<String>,
1102    #[serde(default)]
1103    pub uid: Option<String>,
1104}
1105
1106#[derive(Debug, Clone, Serialize, Deserialize)]
1107#[serde(rename_all = "camelCase")]
1108pub struct FuturesOrderEventData {
1109    #[serde(rename = "orderId")]
1110    pub order_id: String,
1111    #[serde(rename = "cliOrdId", default)]
1112    pub cli_ord_id: Option<String>,
1113    #[serde(rename = "type")]
1114    pub order_type: KrakenFuturesOrderType,
1115    pub symbol: String,
1116    pub side: KrakenOrderSide,
1117    #[serde(with = "decimal")]
1118    pub quantity: Decimal,
1119    #[serde(with = "decimal")]
1120    pub filled: Decimal,
1121    #[serde(rename = "limitPrice", default, with = "optional_decimal")]
1122    pub limit_price: Option<Decimal>,
1123    #[serde(rename = "stopPrice", default, with = "optional_decimal")]
1124    pub stop_price: Option<Decimal>,
1125    pub timestamp: String,
1126    #[serde(rename = "lastUpdateTimestamp")]
1127    pub last_update_timestamp: String,
1128    #[serde(rename = "reduceOnly", default)]
1129    pub reduce_only: bool,
1130}
1131
1132#[derive(Debug, Clone, Serialize, Deserialize)]
1133#[serde(rename_all = "camelCase")]
1134pub struct FuturesOrderTriggerData {
1135    pub uid: String,
1136    #[serde(rename = "clientId", default)]
1137    pub client_id: Option<String>,
1138    #[serde(rename = "type")]
1139    pub order_type: KrakenFuturesOrderType,
1140    pub symbol: String,
1141    pub side: KrakenOrderSide,
1142    #[serde(with = "decimal")]
1143    pub quantity: Decimal,
1144    #[serde(rename = "limitPrice", default, with = "optional_decimal")]
1145    pub limit_price: Option<Decimal>,
1146    #[serde(rename = "limitPriceOffsetValue", default, with = "optional_decimal")]
1147    pub limit_price_offset_value: Option<Decimal>,
1148    #[serde(rename = "limitPriceOffsetUnit", default)]
1149    pub limit_price_offset_unit: Option<String>,
1150    #[serde(rename = "triggerPrice")]
1151    #[serde(with = "decimal")]
1152    pub trigger_price: Decimal,
1153    #[serde(rename = "triggerSide")]
1154    pub trigger_side: KrakenTriggerSide,
1155    #[serde(rename = "triggerSignal")]
1156    pub trigger_signal: KrakenTriggerSignal,
1157    #[serde(rename = "reduceOnly", default)]
1158    pub reduce_only: bool,
1159    pub timestamp: String,
1160    #[serde(rename = "lastUpdateTimestamp")]
1161    pub last_update_timestamp: String,
1162}
1163
1164#[derive(Debug, Clone, Serialize, Deserialize)]
1165#[serde(rename_all = "camelCase")]
1166pub struct FuturesCancelOrderResponse {
1167    pub result: KrakenApiResult,
1168    #[serde(default)]
1169    pub server_time: Option<String>,
1170    pub cancel_status: FuturesCancelStatus,
1171}
1172
1173#[derive(Debug, Clone, Serialize, Deserialize)]
1174#[serde(rename_all = "camelCase")]
1175pub struct FuturesCancelStatus {
1176    pub status: KrakenSendStatus,
1177    #[serde(rename = "order_id", default)]
1178    pub order_id: Option<String>,
1179    #[serde(rename = "cli_ord_id", default)]
1180    pub cli_ord_id: Option<String>,
1181}
1182
1183#[derive(Debug, Clone, Serialize, Deserialize)]
1184#[serde(rename_all = "camelCase")]
1185pub struct FuturesEditOrderResponse {
1186    pub result: KrakenApiResult,
1187    #[serde(default)]
1188    pub server_time: Option<String>,
1189    pub edit_status: FuturesEditStatus,
1190}
1191
1192#[derive(Debug, Clone, Serialize, Deserialize)]
1193#[serde(rename_all = "camelCase")]
1194pub struct FuturesEditStatus {
1195    pub status: String,
1196    /// The order ID under the key the edit API documents.
1197    #[serde(rename = "orderId", default)]
1198    pub order_id: Option<String>,
1199    /// The order ID under the snake-case key the send response uses, read as well since the key
1200    /// the edit response carries is not verified against the live venue.
1201    #[serde(rename = "order_id", default)]
1202    pub order_id_snake_case: Option<String>,
1203    #[serde(rename = "cli_ord_id", default)]
1204    pub cli_ord_id: Option<String>,
1205}
1206
1207#[derive(Debug, Clone, Serialize, Deserialize)]
1208#[serde(rename_all = "camelCase")]
1209pub struct FuturesBatchOrderResponse {
1210    pub result: KrakenApiResult,
1211    #[serde(default)]
1212    pub server_time: Option<String>,
1213    pub batch_status: Vec<FuturesSendStatus>,
1214}
1215
1216/// Response for batch cancel operations via `/derivatives/api/v3/batchorder`.
1217///
1218/// When sending only cancel operations, the response has a different format
1219/// with individual cancel status items.
1220#[derive(Debug, Clone, Serialize, Deserialize)]
1221#[serde(rename_all = "camelCase")]
1222pub struct FuturesBatchCancelResponse {
1223    pub result: KrakenApiResult,
1224    #[serde(default)]
1225    pub server_time: Option<String>,
1226    #[serde(default)]
1227    pub error: Option<String>,
1228    #[serde(default)]
1229    pub batch_status: Vec<FuturesBatchCancelStatus>,
1230}
1231
1232#[derive(Debug, Clone, Serialize, Deserialize)]
1233#[serde(rename_all = "camelCase")]
1234pub struct FuturesBatchCancelStatus {
1235    #[serde(default)]
1236    pub order_id: Option<String>,
1237    #[serde(default)]
1238    pub cli_ord_id: Option<String>,
1239    #[serde(default)]
1240    pub status: Option<KrakenSendStatus>,
1241    #[serde(default)]
1242    pub cancel_status: Option<FuturesCancelStatus>,
1243}
1244
1245#[derive(Debug, Clone, Serialize, Deserialize)]
1246#[serde(rename_all = "camelCase")]
1247pub struct FuturesCancelAllOrdersResponse {
1248    pub result: KrakenApiResult,
1249    #[serde(default)]
1250    pub server_time: Option<String>,
1251    pub cancel_status: FuturesCancelAllStatus,
1252}
1253
1254#[derive(Debug, Clone, Serialize, Deserialize)]
1255#[serde(rename_all = "camelCase")]
1256pub struct FuturesCancelAllStatus {
1257    pub status: KrakenSendStatus,
1258    #[serde(default)]
1259    pub cancelled_orders: Vec<CancelledOrder>,
1260}
1261
1262#[derive(Debug, Clone, Serialize, Deserialize)]
1263#[serde(rename_all = "camelCase")]
1264pub struct CancelledOrder {
1265    #[serde(rename = "order_id", default)]
1266    pub order_id: Option<String>,
1267    #[serde(default)]
1268    pub cli_ord_id: Option<String>,
1269}
1270
1271// Futures Public Executions Models
1272
1273/// Response from the Kraken Futures public executions endpoint.
1274#[derive(Debug, Clone, Serialize, Deserialize)]
1275#[serde(rename_all = "camelCase")]
1276pub struct FuturesPublicExecutionsResponse {
1277    pub elements: Vec<FuturesPublicExecutionElement>,
1278    #[serde(default)]
1279    pub len: Option<i64>,
1280    #[serde(default)]
1281    pub continuation_token: Option<String>,
1282}
1283
1284/// A single execution element from the public executions response.
1285#[derive(Debug, Clone, Serialize, Deserialize)]
1286pub struct FuturesPublicExecutionElement {
1287    pub uid: String,
1288    pub timestamp: i64,
1289    pub event: FuturesPublicExecutionEvent,
1290}
1291
1292/// The event wrapper containing the execution details.
1293#[derive(Debug, Clone, Serialize, Deserialize)]
1294pub struct FuturesPublicExecutionEvent {
1295    #[serde(rename = "Execution")]
1296    pub execution: FuturesPublicExecutionWrapper,
1297}
1298
1299/// Wrapper containing the actual execution data.
1300#[derive(Debug, Clone, Serialize, Deserialize)]
1301#[serde(rename_all = "camelCase")]
1302pub struct FuturesPublicExecutionWrapper {
1303    pub execution: FuturesPublicExecution,
1304    #[serde(default)]
1305    pub taker_reduced_quantity: Option<String>,
1306}
1307
1308/// The actual execution/trade data.
1309#[derive(Debug, Clone, Serialize, Deserialize)]
1310#[serde(rename_all = "camelCase")]
1311pub struct FuturesPublicExecution {
1312    pub uid: String,
1313    pub maker_order: FuturesPublicOrder,
1314    pub taker_order: FuturesPublicOrder,
1315    pub timestamp: i64,
1316    pub quantity: String,
1317    pub price: String,
1318    #[serde(default)]
1319    pub mark_price: Option<String>,
1320    #[serde(default)]
1321    pub limit_filled: Option<bool>,
1322    #[serde(default)]
1323    pub usd_value: Option<String>,
1324}
1325
1326/// Order information within an execution.
1327#[derive(Debug, Clone, Serialize, Deserialize)]
1328#[serde(rename_all = "camelCase")]
1329pub struct FuturesPublicOrder {
1330    pub uid: String,
1331    pub tradeable: String,
1332    pub direction: String,
1333    pub quantity: String,
1334    pub timestamp: i64,
1335    #[serde(default)]
1336    pub limit_price: Option<String>,
1337    #[serde(default)]
1338    pub order_type: Option<String>,
1339    #[serde(default)]
1340    pub reduce_only: Option<bool>,
1341    #[serde(default)]
1342    pub last_update_timestamp: Option<i64>,
1343}
1344
1345// Futures Accounts Models
1346
1347/// Response from the Kraken Futures accounts endpoint.
1348#[derive(Debug, Clone, Serialize, Deserialize)]
1349#[serde(rename_all = "camelCase")]
1350pub struct FuturesAccountsResponse {
1351    pub result: KrakenApiResult,
1352    #[serde(default)]
1353    pub accounts: AHashMap<String, FuturesAccount>,
1354    #[serde(default)]
1355    pub error: Option<String>,
1356    #[serde(default)]
1357    pub server_time: Option<String>,
1358}
1359
1360/// Kraken Futures account type.
1361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1362#[serde(rename_all = "camelCase")]
1363pub enum KrakenFuturesAccountType {
1364    /// Multi-collateral margin account (flex).
1365    MultiCollateralMarginAccount,
1366    /// Single-collateral margin account.
1367    MarginAccount,
1368    /// Cash account (no margin).
1369    CashAccount,
1370    /// Unknown account type.
1371    #[serde(other)]
1372    Unknown,
1373}
1374
1375/// A Kraken Futures account (margin or multi-collateral).
1376#[derive(Debug, Clone, Serialize, Deserialize)]
1377#[serde(rename_all = "camelCase")]
1378pub struct FuturesAccount {
1379    #[serde(rename = "type")]
1380    pub account_type: KrakenFuturesAccountType,
1381    /// Currency of a single-collateral margin account; its `auxiliary` and `marginRequirements`
1382    /// figures are in this currency. Absent on cash and flex accounts.
1383    #[serde(default)]
1384    pub currency: Option<String>,
1385    /// Balances for margin accounts (symbol -> amount).
1386    #[serde(default, with = "decimal_map")]
1387    pub balances: AHashMap<String, Decimal>,
1388    /// Currencies for flex/multi-collateral accounts.
1389    #[serde(default)]
1390    pub currencies: AHashMap<String, FuturesFlexCurrency>,
1391    /// Auxiliary info for margin accounts.
1392    #[serde(default)]
1393    pub auxiliary: Option<FuturesAuxiliary>,
1394    /// Margin requirements.
1395    #[serde(default)]
1396    pub margin_requirements: Option<FuturesMarginRequirements>,
1397    /// Portfolio value (for flex accounts).
1398    #[serde(default, with = "optional_decimal")]
1399    pub portfolio_value: Option<Decimal>,
1400    /// Available margin (for flex accounts).
1401    #[serde(default, with = "optional_decimal")]
1402    pub available_margin: Option<Decimal>,
1403    /// Initial margin (for flex accounts).
1404    #[serde(default, with = "optional_decimal")]
1405    pub initial_margin: Option<Decimal>,
1406    /// Total maintenance margin held for open positions (for flex accounts, in USD).
1407    #[serde(default, with = "optional_decimal")]
1408    pub maintenance_margin: Option<Decimal>,
1409    /// PnL (for flex accounts).
1410    #[serde(default, with = "optional_decimal")]
1411    pub pnl: Option<Decimal>,
1412}
1413
1414/// Currency info for flex/multi-collateral accounts.
1415#[derive(Debug, Clone, Serialize, Deserialize)]
1416#[serde(rename_all = "camelCase")]
1417pub struct FuturesFlexCurrency {
1418    #[serde(with = "decimal")]
1419    pub quantity: Decimal,
1420    #[serde(default, with = "optional_decimal")]
1421    pub value: Option<Decimal>,
1422    #[serde(default, with = "optional_decimal")]
1423    pub collateral: Option<Decimal>,
1424    #[serde(default, with = "optional_decimal")]
1425    pub available: Option<Decimal>,
1426}
1427
1428/// Auxiliary account info for margin accounts.
1429#[derive(Debug, Clone, Serialize, Deserialize)]
1430#[serde(rename_all = "camelCase")]
1431pub struct FuturesAuxiliary {
1432    #[serde(default, with = "optional_decimal")]
1433    pub usd: Option<Decimal>,
1434    /// Portfolio value.
1435    #[serde(default, with = "optional_decimal")]
1436    pub pv: Option<Decimal>,
1437    /// Profit/loss.
1438    #[serde(default, with = "optional_decimal")]
1439    pub pnl: Option<Decimal>,
1440    /// Available funds.
1441    #[serde(default, with = "optional_decimal")]
1442    pub af: Option<Decimal>,
1443    #[serde(default, with = "optional_decimal")]
1444    pub funding: Option<Decimal>,
1445}
1446
1447/// Margin requirements for an account.
1448#[derive(Debug, Clone, Serialize, Deserialize)]
1449#[serde(rename_all = "camelCase")]
1450pub struct FuturesMarginRequirements {
1451    /// Initial margin.
1452    #[serde(default, with = "optional_decimal")]
1453    pub im: Option<Decimal>,
1454    /// Maintenance margin.
1455    #[serde(default, with = "optional_decimal")]
1456    pub mm: Option<Decimal>,
1457    /// Liquidation threshold.
1458    #[serde(default, with = "optional_decimal")]
1459    pub lt: Option<Decimal>,
1460    /// Termination threshold.
1461    #[serde(default, with = "optional_decimal")]
1462    pub tt: Option<Decimal>,
1463}
1464
1465#[cfg(test)]
1466mod tests {
1467    use rstest::rstest;
1468    use rust_decimal_macros::dec;
1469
1470    use super::*;
1471
1472    fn load_test_data(filename: &str) -> String {
1473        let path = format!("test_data/{filename}");
1474        std::fs::read_to_string(&path)
1475            .unwrap_or_else(|e| panic!("Failed to load test data from {path}: {e}"))
1476    }
1477
1478    #[rstest]
1479    fn test_parse_futures_edit_order_response_reads_the_documented_order_id() {
1480        let data = load_test_data("http_edit_order_futures.json");
1481
1482        let response: FuturesEditOrderResponse = serde_json::from_str(&data).unwrap();
1483
1484        assert_eq!(response.result, KrakenApiResult::Success);
1485        assert_eq!(
1486            response.server_time.as_deref(),
1487            Some("2019-09-05T16:47:47.521Z")
1488        );
1489        assert_eq!(response.edit_status.status, "edited");
1490        assert_eq!(
1491            response.edit_status.order_id.as_deref(),
1492            Some("022774bc-2c4a-4f26-9317-436c8d85746d")
1493        );
1494        assert_eq!(response.edit_status.order_id_snake_case, None);
1495    }
1496
1497    #[rstest]
1498    fn test_parse_futures_cancel_all_orders_with_no_orders_to_cancel_status() {
1499        // Regression for the venue response shape that broke parsing in production:
1500        // the `cancelStatus.status` field is `noOrdersToCancel` even when one or more
1501        // orders were canceled in the same call. The `cancelledOrders` array carries
1502        // the actual canceled order ids, so the parser must accept this status.
1503        let raw = r#"{
1504            "result": "success",
1505            "cancelStatus": {
1506                "receivedTime": "2026-04-10T13:17:23.291Z",
1507                "cancelOnly": "PF_XBTUSD",
1508                "status": "noOrdersToCancel",
1509                "cancelledOrders": [
1510                    {
1511                        "order_id": "a182b1c0-cd01-4d1c-853b-605e936f412b",
1512                        "cliOrdId": "5f173994-f660-4809-b97a-586221fe5926"
1513                    }
1514                ],
1515                "orderEvents": []
1516            },
1517            "serverTime": "2026-04-10T13:17:23.291Z"
1518        }"#;
1519
1520        let response: FuturesCancelAllOrdersResponse =
1521            serde_json::from_str(raw).expect("Failed to parse cancel-all response");
1522
1523        assert_eq!(response.result, KrakenApiResult::Success);
1524        assert_eq!(
1525            response.cancel_status.status,
1526            KrakenSendStatus::NoOrdersToCancel
1527        );
1528        assert_eq!(response.cancel_status.cancelled_orders.len(), 1);
1529        assert_eq!(
1530            response.cancel_status.cancelled_orders[0]
1531                .order_id
1532                .as_deref(),
1533            Some("a182b1c0-cd01-4d1c-853b-605e936f412b")
1534        );
1535        assert_eq!(
1536            response.cancel_status.cancelled_orders[0]
1537                .cli_ord_id
1538                .as_deref(),
1539            Some("5f173994-f660-4809-b97a-586221fe5926")
1540        );
1541    }
1542
1543    #[rstest]
1544    fn test_parse_futures_open_orders() {
1545        let data = load_test_data("http_futures_open_orders.json");
1546        let response: FuturesOpenOrdersResponse =
1547            serde_json::from_str(&data).expect("Failed to parse futures open orders");
1548
1549        assert_eq!(response.result, KrakenApiResult::Success);
1550        assert_eq!(response.open_orders.len(), 3);
1551
1552        let order = &response.open_orders[0];
1553        assert_eq!(order.order_id, "2ce038ae-c144-4de7-a0f1-82f7f4fca864");
1554        assert_eq!(order.symbol, "PI_ETHUSD");
1555        assert_eq!(order.side, KrakenOrderSide::Buy);
1556        assert_eq!(order.order_type, KrakenFuturesOrderType::Limit);
1557        assert_eq!(order.limit_price, Some(dec!(1200)));
1558        assert_eq!(order.unfilled_size, Some(dec!(100)));
1559        assert_eq!(order.filled_size, dec!(0));
1560
1561        let trigger_order = &response.open_orders[1];
1562        assert_eq!(
1563            trigger_order.order_id,
1564            "c8135f52-2a86-4e26-b629-43cc37da9dbf"
1565        );
1566        assert_eq!(trigger_order.order_type, KrakenFuturesOrderType::TakeProfit);
1567        assert_eq!(trigger_order.symbol, "PI_XBTUSD");
1568        assert_eq!(trigger_order.side, KrakenOrderSide::Buy);
1569        assert_eq!(trigger_order.limit_price, None);
1570        assert_eq!(trigger_order.stop_price, Some(dec!(1880.4)));
1571        assert_eq!(trigger_order.unfilled_size, None);
1572        assert_eq!(trigger_order.received_time, "2023-04-07T15:14:25.995Z");
1573        assert_eq!(trigger_order.status, KrakenFuturesOrderStatus::Untouched);
1574        assert_eq!(trigger_order.filled_size, dec!(0));
1575        assert_eq!(trigger_order.reduce_only, Some(true));
1576        assert_eq!(trigger_order.last_update_time, "2023-04-07T15:14:25.995Z");
1577        assert_eq!(
1578            trigger_order.trigger_signal,
1579            Some(KrakenTriggerSignal::Last)
1580        );
1581        assert_eq!(trigger_order.cli_ord_id, None);
1582    }
1583
1584    #[rstest]
1585    fn test_parse_futures_orders_status() {
1586        let data = load_test_data("http_futures_orders_status.json");
1587        let response: FuturesOrdersStatusResponse =
1588            serde_json::from_str(&data).expect("Failed to parse futures orders status");
1589
1590        assert_eq!(response.result, KrakenApiResult::Success);
1591        assert_eq!(response.orders.len(), 2);
1592
1593        let part_filled = &response.orders[0];
1594        assert_eq!(
1595            part_filled.order.order_id,
1596            "5f6d15a5-8c9e-4b0a-9d3f-5a2b7c8d9e0f"
1597        );
1598        assert_eq!(
1599            part_filled.order.cli_ord_id.as_deref(),
1600            Some("uuid-mp-held-001")
1601        );
1602        assert_eq!(part_filled.order.side, KrakenOrderSide::Buy);
1603        assert_eq!(part_filled.order.quantity, Some(dec!(0.001)));
1604        assert_eq!(part_filled.order.filled, Some(dec!(0.0004)));
1605        assert_eq!(part_filled.order.limit_price, Some(dec!(70000)));
1606        assert!(!part_filled.order.reduce_only);
1607        assert_eq!(
1608            part_filled.status,
1609            KrakenFuturesOrderLifecycleStatus::Cancelled
1610        );
1611        assert_eq!(part_filled.update_reason.as_deref(), Some("PARTIAL_FILL"));
1612
1613        let open = &response.orders[1];
1614        assert_eq!(open.order.quantity, Some(dec!(0.0002)));
1615        assert_eq!(open.order.filled, Some(dec!(0)));
1616        assert!(open.order.reduce_only);
1617        assert_eq!(open.status, KrakenFuturesOrderLifecycleStatus::EnteredBook);
1618        assert_eq!(open.update_reason, None);
1619    }
1620
1621    #[rstest]
1622    fn test_parse_futures_instruments_maker_protection() {
1623        let data = load_test_data("http_futures_instruments_maker_protection.json");
1624        let response: FuturesInstrumentsResponse =
1625            serde_json::from_str(&data).expect("Failed to parse futures instruments");
1626
1627        assert_eq!(response.result, KrakenApiResult::Success);
1628        assert_eq!(response.instruments.len(), 2);
1629
1630        let protected = &response.instruments[0];
1631        assert_eq!(protected.symbol, "PF_ATOMUSD");
1632        assert_eq!(protected.maker_protection_millis, Some(20));
1633
1634        // The venue omits makerProtectionMillis entirely on unprotected
1635        // markets; absent must decode the same as no protection configured.
1636        let unprotected = &response.instruments[1];
1637        assert_eq!(unprotected.symbol, "PF_ETHUSD");
1638        assert_eq!(unprotected.maker_protection_millis, None);
1639    }
1640
1641    /// The open-orders and fills APIs document the client order ID as `cliOrdId`. The snake-case
1642    /// key is read as well, and a body carrying both reads the documented one rather than failing.
1643    #[rstest]
1644    #[case::documented_key(r#","cliOrdId":"doc-1""#, Some("doc-1"))]
1645    #[case::snake_case_key(r#","cli_ord_id":"snake-1""#, Some("snake-1"))]
1646    #[case::both_keys(r#","cliOrdId":"doc-1","cli_ord_id":"snake-1""#, Some("doc-1"))]
1647    #[case::neither_key("", None)]
1648    fn test_futures_open_order_and_fill_read_either_client_order_id_key(
1649        #[case] keys: &str,
1650        #[case] expected: Option<&str>,
1651    ) {
1652        let order: FuturesOpenOrder = serde_json::from_str(&format!(
1653            r#"{{"order_id":"o1","symbol":"PI_XBTUSD","side":"buy","orderType":"lmt","limitPrice":1.0,"unfilledSize":1.0,"receivedTime":"2023-04-07T14:15:30.250Z","status":"untouched","filledSize":0.0,"reduceOnly":false,"lastUpdateTime":"2023-04-07T14:15:30.250Z"{keys}}}"#
1654        ))
1655        .unwrap();
1656        let fill: FuturesFill = serde_json::from_str(&format!(
1657            r#"{{"fill_id":"f1","symbol":"PI_XBTUSD","side":"buy","order_id":"o1","fillTime":"2023-04-07T15:20:45.500Z","size":1,"price":1.0,"fillType":"taker"{keys}}}"#
1658        ))
1659        .unwrap();
1660
1661        assert_eq!(order.client_order_id(), expected);
1662        assert_eq!(fill.client_order_id(), expected);
1663    }
1664
1665    #[rstest]
1666    fn test_parse_futures_fills() {
1667        let data = load_test_data("http_futures_fills.json");
1668        let response: FuturesFillsResponse =
1669            serde_json::from_str(&data).expect("Failed to parse futures fills");
1670
1671        assert_eq!(response.result, KrakenApiResult::Success);
1672        assert_eq!(response.fills.len(), 3);
1673
1674        let fill = &response.fills[0];
1675        assert_eq!(fill.fill_id, "cad76f07-814e-4dc6-8478-7867407b6bff");
1676        assert_eq!(fill.symbol, "PI_XBTUSD");
1677        assert_eq!(fill.side, KrakenOrderSide::Buy);
1678        assert_eq!(fill.size, dec!(5000));
1679        assert_eq!(fill.price, dec!(27937.5));
1680        assert_eq!(fill.fill_type, KrakenFillType::Maker);
1681        assert_eq!(fill.fee_currency, Some("BTC".to_string()));
1682        assert_eq!(response.fills[1].fill_type, KrakenFillType::Taker);
1683        assert_eq!(response.fills[2].fill_type, KrakenFillType::Assignee);
1684    }
1685
1686    #[rstest]
1687    fn test_parse_futures_open_positions() {
1688        let data = load_test_data("http_futures_open_positions.json");
1689        let response: FuturesOpenPositionsResponse =
1690            serde_json::from_str(&data).expect("Failed to parse futures open positions");
1691
1692        assert_eq!(response.result, KrakenApiResult::Success);
1693        assert_eq!(response.open_positions.len(), 2);
1694
1695        let position = &response.open_positions[0];
1696        assert_eq!(position.side, KrakenPositionSide::Short);
1697        assert_eq!(position.symbol, "PI_XBTUSD");
1698        assert_eq!(position.size, dec!(8000));
1699        assert!(position.unrealized_funding.is_some());
1700    }
1701
1702    #[rstest]
1703    fn test_parse_futures_orderbook() {
1704        let data = load_test_data("http_futures_orderbook.json");
1705        let response: FuturesOrderBookResponse =
1706            serde_json::from_str(&data).expect("Failed to parse futures orderbook");
1707
1708        assert_eq!(response.result, KrakenApiResult::Success);
1709        assert_eq!(response.order_book.bids.len(), 3);
1710        assert_eq!(response.order_book.asks.len(), 3);
1711
1712        let best_bid = &response.order_book.bids[0];
1713        assert_eq!(best_bid.price, dec!(105900));
1714        assert_eq!(best_bid.qty, dec!(0.5));
1715
1716        let best_ask = &response.order_book.asks[0];
1717        assert_eq!(best_ask.price, dec!(105950));
1718        assert_eq!(best_ask.qty, dec!(0.3));
1719    }
1720
1721    #[rstest]
1722    fn test_parse_futures_historical_funding_rates() {
1723        let data = load_test_data("http_futures_historical_funding_rates.json");
1724        let response: FuturesHistoricalFundingRatesResponse =
1725            serde_json::from_str(&data).expect("Failed to parse historical funding rates");
1726
1727        assert_eq!(response.result, KrakenApiResult::Success);
1728        assert_eq!(response.rates.len(), 3);
1729
1730        let rate = &response.rates[0];
1731        assert_eq!(rate.timestamp, "2025-07-11T08:00:00.000Z");
1732        assert_eq!(rate.relative_funding_rate, dec!(0.0001));
1733        assert_eq!(rate.funding_rate, dec!(0.00005));
1734
1735        let negative_rate = &response.rates[1];
1736        assert_eq!(negative_rate.relative_funding_rate, dec!(-0.00005));
1737    }
1738
1739    #[rstest]
1740    fn test_parse_futures_orderbook_preserves_decimal_precision() {
1741        let data = load_test_data("http_futures_orderbook_precision.json");
1742        let level: FuturesOrderBookLevel = serde_json::from_str(&data).unwrap();
1743
1744        assert_eq!(level.price, dec!(0.1234567890123456789012345678));
1745        assert_eq!(level.qty, dec!(123456789.123456789));
1746    }
1747
1748    fn order_history_events(fixture: &str) -> FuturesOrderEventsResponse {
1749        let data = load_test_data(fixture);
1750        order_history_events_from(&data)
1751    }
1752
1753    fn order_history_events_from(data: &str) -> FuturesOrderEventsResponse {
1754        let response: FuturesOrderHistoryResponse =
1755            serde_json::from_str(data).expect("Failed to parse futures order history");
1756        response
1757            .into_order_events()
1758            .expect("the page carries elements")
1759    }
1760
1761    fn placed_element(order: &str) -> String {
1762        format!(
1763            r#"{{"elements":[{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderPlaced":{{"order":{order}}}}}}}]}}"#
1764        )
1765    }
1766
1767    /// Each documented event kind maps onto the event type the readers switch on.
1768    #[rstest]
1769    fn test_parse_futures_order_events_uses_enum_event_type() {
1770        let response = order_history_events("http_futures_order_events.json");
1771
1772        assert_eq!(response.order_events.len(), 3);
1773        assert_eq!(
1774            response.order_events[0].event_type,
1775            KrakenFuturesOrderEventType::Place
1776        );
1777        assert_eq!(
1778            response.order_events[1].event_type,
1779            KrakenFuturesOrderEventType::Edit
1780        );
1781        assert_eq!(
1782            response.order_events[2].event_type,
1783            KrakenFuturesOrderEventType::Cancel
1784        );
1785        assert_eq!(response.continuation_token.as_deref(), Some("simb178"));
1786    }
1787
1788    /// An update carries the order after the edit.
1789    #[rstest]
1790    fn test_parse_futures_order_events_update_uses_the_new_order() {
1791        let response = order_history_events("http_futures_order_events.json");
1792        let updated = &response.order_events[1].order;
1793
1794        assert_eq!(updated.filled, dec!(10000));
1795        assert_eq!(updated.order_type, KrakenFuturesOrderType::Market);
1796        assert_eq!(updated.limit_price, None, "a zero limit price is no price");
1797        assert_eq!(updated.cli_ord_id, None, "an empty client id is no id");
1798    }
1799
1800    /// The contract name is kept as the venue spells it, and the millisecond timestamps are
1801    /// formatted for the readers, which parse RFC 3339.
1802    #[rstest]
1803    fn test_parse_futures_order_events_keeps_the_tradeable_and_formats_timestamps() {
1804        let response = order_history_events("http_futures_order_events.json");
1805        let canceled = &response.order_events[2].order;
1806
1807        assert_eq!(canceled.symbol, "pi_xbtusd");
1808        assert_eq!(canceled.timestamp, "2023-04-07T13:00:00.000Z");
1809        assert_eq!(canceled.last_update_timestamp, "2023-04-07T16:00:00.000Z");
1810        assert!(canceled.reduce_only);
1811        assert_eq!(canceled.limit_price, Some(dec!(26000.0)));
1812        assert_eq!(
1813            canceled.stop_price, None,
1814            "the history schema has no trigger price"
1815        );
1816    }
1817
1818    /// A stop row carries no trigger price, which the engine needs to materialize a stop order,
1819    /// so it is reported as the limit or market order it executes as once triggered.
1820    #[rstest]
1821    #[case::with_limit("26000.0", KrakenFuturesOrderType::Limit, Some(dec!(26000.0)))]
1822    #[case::without_limit("0", KrakenFuturesOrderType::Market, None)]
1823    fn test_parse_futures_order_events_reports_a_stop_as_its_triggered_order(
1824        #[case] limit_price: &str,
1825        #[case] expected_type: KrakenFuturesOrderType,
1826        #[case] expected_price: Option<Decimal>,
1827    ) {
1828        let data = placed_element(&format!(
1829            r#"{{"uid":"o1","tradeable":"PI_XBTUSD","direction":"Sell","quantity":"2000","filled":"0","limitPrice":"{limit_price}","orderType":"Stop","clientId":"","reduceOnly":true,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}"#
1830        ));
1831        let response = order_history_events_from(&data);
1832        let order = &response.order_events[0].order;
1833
1834        assert_eq!(order.order_type, expected_type);
1835        assert_eq!(order.limit_price, expected_price);
1836        assert_eq!(order.stop_price, None);
1837    }
1838
1839    /// A market order's placeholder price, empty or zero, is no price; a limit order keeps its
1840    /// price even at zero, since futures instruments allow non-positive prices.
1841    #[rstest]
1842    #[case::market_empty("Market", "", None)]
1843    #[case::market_zero("Market", "0", None)]
1844    #[case::limit_zero("Limit", "0", Some(dec!(0)))]
1845    fn test_parse_futures_order_events_reads_the_limit_price_by_order_kind(
1846        #[case] order_type: &str,
1847        #[case] limit_price: &str,
1848        #[case] expected: Option<Decimal>,
1849    ) {
1850        let data = placed_element(&format!(
1851            r#"{{"uid":"o1","tradeable":"PI_XBTUSD","direction":"Buy","quantity":"1","filled":"1","limitPrice":"{limit_price}","orderType":"{order_type}","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}"#
1852        ));
1853        let response = order_history_events_from(&data);
1854
1855        assert_eq!(response.order_events[0].order.limit_price, expected);
1856    }
1857
1858    /// A rejected order reports as rejected.
1859    #[rstest]
1860    fn test_parse_futures_order_events_maps_a_rejection() {
1861        let data = r#"{"elements":[{"uid":"e1","timestamp":1680876930250,"event":{"OrderRejected":{"order":{"uid":"o1","tradeable":"PI_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250},"reason":"insufficient_margin"}}}]}"#;
1862        let response = order_history_events_from(data);
1863
1864        assert_eq!(
1865            response.order_events[0].event_type,
1866            KrakenFuturesOrderEventType::Reject
1867        );
1868    }
1869
1870    /// An order whose type the venue reports as `Unknown` establishes no order type, so its row
1871    /// is skipped and counted, while the sibling rows of the page are kept with their fields
1872    /// intact. A not-found event carries no state and is skipped without counting; an
1873    /// undocumented kind may carry state and counts.
1874    #[rstest]
1875    fn test_parse_futures_order_events_skips_an_unknown_order_type_and_keeps_siblings() {
1876        let response = order_history_events("http_futures_order_events_unknown.json");
1877
1878        assert_eq!(response.order_events.len(), 1);
1879        let sibling = &response.order_events[0];
1880        assert_eq!(sibling.event_type, KrakenFuturesOrderEventType::Edit);
1881        assert_eq!(sibling.reduced_quantity, None);
1882        assert_eq!(sibling.order.order_id, "abc");
1883        assert_eq!(sibling.order.cli_ord_id, None);
1884        assert_eq!(sibling.order.order_type, KrakenFuturesOrderType::Limit);
1885        assert_eq!(sibling.order.symbol, "PF_XBTUSD");
1886        assert_eq!(sibling.order.side, KrakenOrderSide::Buy);
1887        assert_eq!(sibling.order.quantity, dec!(1.0));
1888        assert_eq!(sibling.order.filled, dec!(0.5));
1889        assert_eq!(sibling.order.limit_price, Some(dec!(70000.0)));
1890        assert_eq!(sibling.order.stop_price, None);
1891        assert_eq!(sibling.order.timestamp, "2026-05-18T00:00:00.000Z");
1892        assert_eq!(
1893            sibling.order.last_update_timestamp,
1894            "2026-05-18T00:00:01.000Z"
1895        );
1896        assert!(!sibling.order.reduce_only);
1897        assert_eq!(
1898            response.server_time.as_deref(),
1899            Some("2026-05-18T00:00:03.000Z")
1900        );
1901        assert_eq!(response.continuation_token, None);
1902        assert_eq!(
1903            response.skipped_rows.len(),
1904            2,
1905            "the Unknown type and the undocumented kind count; the not-found event does not"
1906        );
1907    }
1908
1909    /// A page reaches back to its oldest event whatever the projection keeps, so the oldest time
1910    /// counts a not-found or undocumented element as well as a kept one.
1911    #[rstest]
1912    #[case::not_found(r#"{"OrderNotFound":{"orderId":"gone"}}"#)]
1913    #[case::undocumented(r#"{"OrderSomethingNew":{"order":{"uid":"x"}}}"#)]
1914    fn test_parse_futures_order_events_oldest_time_counts_every_element(#[case] oldest: &str) {
1915        let kept = r#"{"OrderPlaced":{"order":{"uid":"o1","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250},"reason":"new_user_order"}}"#;
1916        let data = format!(
1917            r#"{{"elements":[{{"uid":"e2","timestamp":1680876931000,"event":{kept}}},{{"uid":"e1","timestamp":1680876930000,"event":{oldest}}}]}}"#
1918        );
1919
1920        let response = order_history_events_from(&data);
1921
1922        assert_eq!(response.order_events.len(), 1);
1923        assert_eq!(response.oldest_event_ms, Some(1_680_876_930_000));
1924    }
1925
1926    /// A row skipped for a timestamp before the epoch names the order it carries, so a lookup
1927    /// cannot rule that order out.
1928    #[rstest]
1929    fn test_parse_futures_order_events_names_the_order_of_a_pre_epoch_row() {
1930        let data = r#"{"elements":[{"uid":"e1","timestamp":1680876930250,"event":{"OrderPlaced":{"order":{"uid":"o-pre","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":-1,"lastUpdateTimestamp":-1},"reason":"new_user_order"}}}]}"#;
1931
1932        let response = order_history_events_from(data);
1933
1934        assert!(response.order_events.is_empty());
1935        assert_eq!(
1936            response.skipped_rows,
1937            vec![SkippedHistoryRow {
1938                order_id: Some("o-pre".to_string()),
1939                tradeable: Some("PF_XBTUSD".to_string()),
1940                event_ms: 1_680_876_930_250,
1941                undocumented: false,
1942            }]
1943        );
1944    }
1945
1946    /// A page reaches back to its oldest event whatever the projection keeps, so a skipped row
1947    /// counts toward the oldest time. A skipped row names its order when it carries one, and an
1948    /// undocumented kind is marked, since its shape is only a guess.
1949    #[rstest]
1950    fn test_parse_futures_order_events_reports_what_the_page_covers() {
1951        let response = order_history_events("http_futures_order_events_unknown.json");
1952
1953        assert_eq!(
1954            response.oldest_event_ms,
1955            Some(1_779_062_400_000),
1956            "the oldest element is the skipped Unknown-type row"
1957        );
1958        let rows: Vec<_> = response
1959            .skipped_rows
1960            .iter()
1961            .map(|row| (row.order_id.as_deref(), row.undocumented))
1962            .collect();
1963        assert_eq!(rows, vec![(Some("abc"), false), (Some("abc"), true)]);
1964    }
1965
1966    /// `Unknown` is how the venue reports a source type it could not decode, so neither it nor a
1967    /// missing type establishes what the order is: the row is skipped with its price rather than
1968    /// reported as a market order, the sibling row is kept, and the row is listed as skipped.
1969    #[rstest]
1970    #[case::missing_type("")]
1971    #[case::undocumented_type(r#""orderType":"SomethingNew","#)]
1972    fn test_parse_futures_order_events_skips_an_unmappable_order_type(#[case] order_type: &str) {
1973        let data = format!(
1974            r#"{{"elements":[{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderPlaced":{{"order":{{"uid":"o1","tradeable":"PF_XBTUSD","direction":"Sell","quantity":"3","filled":"1",{order_type}"limitPrice":"70000","clientId":"cl-1","reduceOnly":true,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}}}}}}},{{"uid":"e2","timestamp":1680877245500,"event":{{"OrderPlaced":{{"order":{{"uid":"o2","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"2","filled":"0.5","limitPrice":"69500.5","orderType":"Limit","clientId":"cl-2","reduceOnly":false,"timestamp":1680877245500,"lastUpdateTimestamp":1680877245500}}}}}}}}]}}"#
1975        );
1976        let response = order_history_events_from(&data);
1977
1978        assert_eq!(response.order_events.len(), 1);
1979        let sibling = &response.order_events[0];
1980        assert_eq!(sibling.event_type, KrakenFuturesOrderEventType::Place);
1981        assert_eq!(sibling.order.order_id, "o2");
1982        assert_eq!(sibling.order.cli_ord_id.as_deref(), Some("cl-2"));
1983        assert_eq!(sibling.order.order_type, KrakenFuturesOrderType::Limit);
1984        assert_eq!(sibling.order.symbol, "PF_XBTUSD");
1985        assert_eq!(sibling.order.side, KrakenOrderSide::Buy);
1986        assert_eq!(sibling.order.quantity, dec!(2));
1987        assert_eq!(sibling.order.filled, dec!(0.5));
1988        assert_eq!(sibling.order.limit_price, Some(dec!(69500.5)));
1989        assert_eq!(sibling.order.stop_price, None);
1990        assert_eq!(sibling.order.timestamp, "2023-04-07T14:20:45.500Z");
1991        assert_eq!(
1992            sibling.order.last_update_timestamp,
1993            "2023-04-07T14:20:45.500Z"
1994        );
1995        assert!(!sibling.order.reduce_only);
1996        assert_eq!(
1997            response.skipped_rows.len(),
1998            1,
1999            "the row is listed as skipped"
2000        );
2001    }
2002
2003    /// A timestamp before the epoch cannot be reported, so the row is skipped rather than dated
2004    /// at the epoch.
2005    #[rstest]
2006    fn test_parse_futures_order_events_skips_a_negative_timestamp() {
2007        let data = r#"{"elements":[{"uid":"e1","timestamp":-1,"event":{"OrderPlaced":{"order":{"uid":"o1","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":-1,"lastUpdateTimestamp":-1}}}}]}"#;
2008        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2009        let response = response.into_order_events().unwrap();
2010
2011        assert!(response.order_events.is_empty());
2012        assert_eq!(
2013            response.skipped_rows.len(),
2014            1,
2015            "the row is listed as skipped"
2016        );
2017    }
2018
2019    /// The kind is found wherever it sits among the event's keys.
2020    #[rstest]
2021    fn test_parse_futures_order_events_finds_the_kind_after_other_keys() {
2022        let data = r#"{"elements":[{"uid":"e1","timestamp":1680877245500,"event":{"version":1,"OrderCancelled":{"order":{"uid":"o1","tradeable":"PI_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}}}]}"#;
2023        let response = order_history_events_from(data);
2024
2025        assert_eq!(
2026            response.order_events[0].event_type,
2027            KrakenFuturesOrderEventType::Cancel
2028        );
2029    }
2030
2031    /// A report is dated at the event when that is later than the order's own update stamp, as
2032    /// for a refused edit.
2033    #[rstest]
2034    fn test_parse_futures_order_events_dates_a_report_at_the_event() {
2035        let data = r#"{"elements":[{"uid":"e1","timestamp":1680877245500,"event":{"OrderEditRejected":{"oldOrder":{"uid":"o1","tradeable":"PI_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}}}]}"#;
2036        let response = order_history_events_from(data);
2037
2038        assert_eq!(
2039            response.order_events[0].order.last_update_timestamp,
2040            "2023-04-07T14:20:45.500Z"
2041        );
2042    }
2043
2044    /// An empty event object is an undocumented kind, not a failed page.
2045    #[rstest]
2046    fn test_parse_futures_order_events_tolerates_an_empty_event() {
2047        let data = r#"{"elements":[{"uid":"e1","timestamp":1,"event":{}}]}"#;
2048        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2049
2050        assert!(matches!(
2051            response.elements.as_deref(),
2052            Some([FuturesOrderHistoryElement { event: FuturesOrderHistoryEvent::Unknown { kind, .. }, .. }]) if kind.is_empty()
2053        ));
2054    }
2055
2056    /// A documented kind whose payload does not decode is a skipped row naming what can be read of
2057    /// it, each field from the first documented position holding a usable value, and the page's
2058    /// other rows are kept.
2059    #[rstest]
2060    #[case::bad_quantity(
2061        r#"{"OrderCancelled":{"order":{"uid":"o-bad","tradeable":"PF_XBTUSD","quantity":"oops"}}}"#,
2062        Some("o-bad"),
2063        Some("PF_XBTUSD")
2064    )]
2065    #[case::number_out_of_range(
2066        r#"{"OrderCancelled":{"order":{"uid":"o-bad","tradeable":"PF_XBTUSD","quantity":1e999}}}"#,
2067        Some("o-bad"),
2068        Some("PF_XBTUSD")
2069    )]
2070    #[case::missing_uid(
2071        r#"{"OrderCancelled":{"order":{"tradeable":"PF_XBTUSD"}}}"#,
2072        None,
2073        Some("PF_XBTUSD")
2074    )]
2075    #[case::mistyped_uid(
2076        r#"{"OrderCancelled":{"order":{"uid":5,"tradeable":"PF_XBTUSD"}}}"#,
2077        None,
2078        Some("PF_XBTUSD")
2079    )]
2080    #[case::invalid_uid(
2081        r#"{"OrderCancelled":{"order":{"uid":"","tradeable":"PF_XBTUSD"}}}"#,
2082        None,
2083        Some("PF_XBTUSD")
2084    )]
2085    #[case::missing_tradeable(
2086        r#"{"OrderCancelled":{"order":{"uid":"o-bad"}}}"#,
2087        Some("o-bad"),
2088        None
2089    )]
2090    #[case::payload_not_an_object(r#"{"OrderCancelled":"gone"}"#, None, None)]
2091    #[case::no_order_position(r#"{"OrderCancelled":{}}"#, None, None)]
2092    #[case::mistyped_not_found(r#"{"OrderNotFound":{"orderId":5}}"#, None, None)]
2093    #[case::update_read_from_the_old_order(
2094        r#"{"OrderUpdated":{"newOrder":{"uid":"","tradeable":""},"oldOrder":{"uid":"o-bad","tradeable":"PF_XBTUSD"}}}"#,
2095        Some("o-bad"),
2096        Some("PF_XBTUSD")
2097    )]
2098    #[case::refused_edit_read_from_the_attempted_order(
2099        r#"{"OrderEditRejected":{"oldOrder":{"uid":7},"attemptedOrder":{"uid":"o-bad","tradeable":"PF_XBTUSD"}}}"#,
2100        Some("o-bad"),
2101        Some("PF_XBTUSD")
2102    )]
2103    fn test_parse_futures_order_events_skips_an_unreadable_row_and_keeps_siblings(
2104        #[case] unreadable: &str,
2105        #[case] expected_order: Option<&str>,
2106        #[case] expected_contract: Option<&str>,
2107    ) {
2108        let sibling = r#"{"OrderPlaced":{"order":{"uid":"o-sibling","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}}"#;
2109        let data = format!(
2110            r#"{{"elements":[{{"uid":"e2","timestamp":1680876931000,"event":{unreadable}}},{{"uid":"e1","timestamp":1680876930000,"event":{sibling}}}]}}"#
2111        );
2112
2113        let response = order_history_events_from(&data);
2114
2115        assert_eq!(response.order_events.len(), 1);
2116        assert_eq!(response.order_events[0].order.order_id, "o-sibling");
2117        assert_eq!(
2118            response.skipped_rows,
2119            vec![SkippedHistoryRow {
2120                order_id: expected_order.map(str::to_string),
2121                tradeable: expected_contract.map(str::to_string),
2122                event_ms: 1_680_876_931_000,
2123                undocumented: false,
2124            }]
2125        );
2126    }
2127
2128    /// A row whose order ID cannot be an ID does not decode, so it names no order unless another
2129    /// documented position of the row does.
2130    #[rstest]
2131    #[case::empty_on_a_limit_row("", "Limit")]
2132    #[case::empty_on_an_unknown_type("", "Unknown")]
2133    #[case::whitespace(" ", "Limit")]
2134    #[case::non_ascii("\u{e9}", "Limit")]
2135    fn test_parse_futures_order_events_reads_an_invalid_order_id_as_naming_no_order(
2136        #[case] uid: &str,
2137        #[case] order_type: &str,
2138    ) {
2139        let data = format!(
2140            r#"{{"elements":[{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderPlaced":{{"order":{{"uid":"{uid}","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"{order_type}","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}}}}}}}]}}"#
2141        );
2142
2143        let response = order_history_events_from(&data);
2144
2145        assert!(response.order_events.is_empty());
2146        assert_eq!(
2147            response.skipped_rows,
2148            vec![SkippedHistoryRow {
2149                order_id: None,
2150                tradeable: Some("PF_XBTUSD".to_string()),
2151                event_ms: 1_680_876_930_250,
2152                undocumented: false,
2153            }]
2154        );
2155    }
2156
2157    /// An update's invalid new order leaves its old order to name the row, whatever else decodes.
2158    #[rstest]
2159    fn test_parse_futures_order_events_reads_an_update_from_its_old_order_past_an_invalid_id() {
2160        let order = |uid: &str| {
2161            format!(
2162                r#"{{"uid":"{uid}","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}"#
2163            )
2164        };
2165        let data = format!(
2166            r#"{{"elements":[{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderUpdated":{{"oldOrder":{},"newOrder":{}}}}}}}]}}"#,
2167            order("o-old"),
2168            order(""),
2169        );
2170
2171        let response = order_history_events_from(&data);
2172
2173        assert_eq!(
2174            response.skipped_rows,
2175            vec![SkippedHistoryRow {
2176                order_id: Some("o-old".to_string()),
2177                tradeable: Some("PF_XBTUSD".to_string()),
2178                event_ms: 1_680_876_930_250,
2179                undocumented: false,
2180            }]
2181        );
2182    }
2183
2184    /// A row keeps the first documented kind it names, so a malformed later key does not cost it.
2185    #[rstest]
2186    fn test_parse_futures_order_events_keeps_the_first_documented_kind() {
2187        let data = r#"{"elements":[{"uid":"e1","timestamp":1680876930250,"event":{"OrderPlaced":{"order":{"uid":"o1","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}},"OrderCancelled":"not an event"}}]}"#;
2188
2189        let response = order_history_events_from(data);
2190
2191        assert!(response.skipped_rows.is_empty());
2192        assert_eq!(
2193            response.order_events[0].event_type,
2194            KrakenFuturesOrderEventType::Place
2195        );
2196    }
2197
2198    /// A row's envelope is the page's structure, which the documentation requires of every
2199    /// element, so an element without one fails the read rather than reading as a skipped row.
2200    #[rstest]
2201    #[case::not_an_object("1")]
2202    #[case::no_event(r#"{"uid":"e1","timestamp":1}"#)]
2203    #[case::event_not_an_object(r#"{"uid":"e1","timestamp":1,"event":"OrderPlaced"}"#)]
2204    #[case::no_uid(r#"{"timestamp":1,"event":{}}"#)]
2205    #[case::no_timestamp(r#"{"uid":"e1","event":{}}"#)]
2206    #[case::mistyped_timestamp(r#"{"uid":"e1","timestamp":"now","event":{}}"#)]
2207    fn test_parse_futures_order_events_fail_on_an_invalid_element(#[case] element: &str) {
2208        let data = format!(r#"{{"elements":[{element}]}}"#);
2209
2210        assert!(serde_json::from_str::<FuturesOrderHistoryResponse>(&data).is_err());
2211    }
2212
2213    /// A numeric quantity keeps all its digits through the row's raw JSON text.
2214    #[rstest]
2215    fn test_parse_futures_order_events_keeps_a_numeric_quantity_exact() {
2216        let data = r#"{"elements":[{"uid":"e1","timestamp":1680876930250,"event":{"OrderPlaced":{"order":{"uid":"o1","tradeable":"PF_XBTUSD","direction":"Buy","quantity":1.2345678901234567891,"filled":0,"limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}}}]}"#;
2217
2218        let response = order_history_events_from(data);
2219
2220        assert_eq!(
2221            response.order_events[0].order.quantity,
2222            rust_decimal_macros::dec!(1.2345678901234567891)
2223        );
2224    }
2225
2226    /// The order type is the only place the history states a time in force or post-only.
2227    #[rstest]
2228    #[case::limit("Limit", TimeInForce::Gtc, false)]
2229    #[case::ioc("IoC", TimeInForce::Ioc, false)]
2230    #[case::hedge_ioc("HedgeImmediateOrCancel", TimeInForce::Ioc, false)]
2231    #[case::fill_or_kill("FillOrKill", TimeInForce::Fok, false)]
2232    #[case::post("Post", TimeInForce::Gtc, true)]
2233    #[case::market("Market", TimeInForce::Gtc, false)]
2234    #[case::stop("Stop", TimeInForce::Gtc, false)]
2235    fn test_parse_futures_order_events_read_the_time_in_force_from_the_type(
2236        #[case] order_type: &str,
2237        #[case] expected_time_in_force: TimeInForce,
2238        #[case] expected_post_only: bool,
2239    ) {
2240        let data = format!(
2241            r#"{{"elements":[{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderPlaced":{{"order":{{"uid":"o1","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"{order_type}","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}}}}}}}]}}"#
2242        );
2243
2244        let response = order_history_events_from(&data);
2245
2246        let event = &response.order_events[0].order;
2247        assert_eq!(event.time_in_force, expected_time_in_force);
2248        assert_eq!(event.post_only, expected_post_only);
2249    }
2250
2251    /// An order whose direction the venue could not decode has no side to report, so it is skipped.
2252    #[rstest]
2253    fn test_parse_futures_order_events_skips_an_unknown_direction() {
2254        let data = r#"{"elements":[{"uid":"e1","timestamp":1680876930250,"event":{"OrderPlaced":{"order":{"uid":"o1","tradeable":"PF_XBTUSD","direction":"Unknown","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250},"reason":"","reducedQuantity":""}}}]}"#;
2255        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2256        let response = response.into_order_events().unwrap();
2257
2258        assert!(response.order_events.is_empty());
2259        assert_eq!(
2260            response.skipped_rows.len(),
2261            1,
2262            "the row is listed as skipped"
2263        );
2264    }
2265
2266    /// A venue error reported with a success status fails the read with the venue's reason, not
2267    /// as an empty page.
2268    #[rstest]
2269    fn test_parse_futures_order_events_fails_on_a_venue_error_body() {
2270        let data = r#"{"result":"error","error":"apiLimitExceeded"}"#;
2271        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2272
2273        let error = response
2274            .into_order_events()
2275            .expect_err("a venue error must fail the read");
2276
2277        assert!(
2278            matches!(&error, KrakenHttpError::ApiError(reasons) if reasons == &["apiLimitExceeded"]),
2279            "unexpected error: {error}"
2280        );
2281    }
2282
2283    /// A body without an `elements` array is not an order history page.
2284    #[rstest]
2285    fn test_parse_futures_order_events_requires_elements() {
2286        let data = r#"{"serverTime":"2023-04-07T16:30:45.678Z"}"#;
2287        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2288
2289        assert!(matches!(
2290            response.into_order_events(),
2291            Err(KrakenHttpError::ParseError(_))
2292        ));
2293    }
2294
2295    #[rstest]
2296    fn test_parse_futures_order_trigger_data_tolerates_unknown_enum_values() {
2297        // Trigger payload uses non-optional enums, so an `"unknown"` on
2298        // triggerSide / triggerSignal must not fail the sendStatus batch.
2299        let data = load_test_data("http_send_order_futures_unknown_trigger.json");
2300        let response: FuturesSendOrderResponse =
2301            serde_json::from_str(&data).expect("Failed to parse send-order response with unknown");
2302
2303        let send_status = response.send_status.expect("sendStatus missing");
2304        let order_events = send_status.order_events.expect("orderEvents missing");
2305        let trigger = order_events[0]
2306            .order_trigger
2307            .as_ref()
2308            .expect("orderTrigger missing");
2309
2310        assert_eq!(trigger.order_type, KrakenFuturesOrderType::Unknown);
2311        assert_eq!(trigger.trigger_side, KrakenTriggerSide::Unknown);
2312        assert_eq!(trigger.trigger_signal, KrakenTriggerSignal::Unknown);
2313    }
2314
2315    #[rstest]
2316    fn test_parse_futures_send_order_execution_event_uses_enum_event_type() {
2317        let data = r#"
2318        {
2319          "result": "success",
2320          "sendStatus": {
2321            "status": "placed",
2322            "orderEvents": [
2323              {
2324                "type": "EXECUTION",
2325                "executionId": "c8a35168-8d52-4609-944f-3f32bb0d5c77",
2326                "price": 35000.5,
2327                "amount": 1.25,
2328                "orderPriorExecution": {
2329                  "orderId": "c8a35168-8d52-4609-944f-3f32bb0d5c77",
2330                  "cliOrdId": "test-order-001",
2331                  "type": "lmt",
2332                  "symbol": "PI_XBTUSD",
2333                  "side": "buy",
2334                  "quantity": 2.0,
2335                  "filled": 0.0,
2336                  "limitPrice": 35000.5,
2337                  "timestamp": "2024-01-15T10:30:45.123Z",
2338                  "lastUpdateTimestamp": "2024-01-15T10:30:45.123Z",
2339                  "reduceOnly": false
2340                }
2341              }
2342            ]
2343          }
2344        }
2345        "#;
2346        let response: FuturesSendOrderResponse =
2347            serde_json::from_str(data).expect("Failed to parse futures send order response");
2348
2349        let send_status = response.send_status.expect("sendStatus missing");
2350        let order_events = send_status.order_events.expect("orderEvents missing");
2351
2352        assert_eq!(order_events.len(), 1);
2353        assert_eq!(
2354            order_events[0].event_type,
2355            KrakenFuturesOrderEventType::Execution
2356        );
2357    }
2358}