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                    KrakenFuturesHistoryOrderType::Limit
929                    | KrakenFuturesHistoryOrderType::Market
930                    | KrakenFuturesHistoryOrderType::Stop
931                    | KrakenFuturesHistoryOrderType::Liquidation
932                    | KrakenFuturesHistoryOrderType::PartialLiquidation
933                    | KrakenFuturesHistoryOrderType::CoveredLiquidation
934                    | KrakenFuturesHistoryOrderType::Assignment
935                    | KrakenFuturesHistoryOrderType::HedgeAssignment
936                    | KrakenFuturesHistoryOrderType::Unwind
937                    | KrakenFuturesHistoryOrderType::Block
938                    | KrakenFuturesHistoryOrderType::Rfq
939                    | KrakenFuturesHistoryOrderType::Unknown => (TimeInForce::Gtc, false),
940                };
941
942                Some(FuturesOrderEventWrapper {
943                    order: FuturesOrderEvent {
944                        order_id: order.uid,
945                        cli_ord_id: order.client_id.filter(|id| !id.is_empty()),
946                        order_type,
947                        symbol: order.tradeable,
948                        side,
949                        quantity: order.quantity,
950                        filled: order.filled,
951                        limit_price,
952                        stop_price: None,
953                        timestamp,
954                        last_update_timestamp,
955                        reduce_only: order.reduce_only,
956                        time_in_force,
957                        post_only,
958                    },
959                    event_type,
960                    reduced_quantity: None,
961                    event_ms,
962                    state_ms,
963                })
964            })
965            .collect();
966
967        Ok(FuturesOrderEventsResponse {
968            server_time: self.server_time,
969            order_events,
970            continuation_token: self.continuation_token,
971            skipped_rows,
972            oldest_event_ms,
973        })
974    }
975}
976
977// Futures Fills Models
978
979#[derive(Debug, Clone, Serialize, Deserialize)]
980#[serde(rename_all = "camelCase")]
981pub struct FuturesFill {
982    #[serde(rename = "fill_id")]
983    pub fill_id: String,
984    pub symbol: String,
985    pub side: KrakenOrderSide,
986    #[serde(rename = "order_id")]
987    pub order_id: String,
988    pub fill_time: String,
989    #[serde(with = "decimal")]
990    pub size: Decimal,
991    #[serde(with = "decimal")]
992    pub price: Decimal,
993    pub fill_type: KrakenFillType,
994    /// The client order ID under the key the fills API documents.
995    #[serde(rename = "cliOrdId", default)]
996    pub cli_ord_id: Option<String>,
997    /// The client order ID under the snake-case key the WebSocket feeds use, read as well since the
998    /// key the REST response carries is not verified against the live venue.
999    #[serde(rename = "cli_ord_id", default)]
1000    pub cli_ord_id_snake_case: Option<String>,
1001    #[serde(rename = "fee_paid", default, with = "optional_decimal")]
1002    pub fee_paid: Option<Decimal>,
1003    #[serde(rename = "fee_currency", default)]
1004    pub fee_currency: Option<String>,
1005}
1006
1007impl FuturesFill {
1008    /// The client order ID under whichever key the response carries.
1009    #[must_use]
1010    pub fn client_order_id(&self) -> Option<&str> {
1011        self.cli_ord_id
1012            .as_deref()
1013            .or(self.cli_ord_id_snake_case.as_deref())
1014    }
1015}
1016
1017#[derive(Debug, Clone, Serialize, Deserialize)]
1018#[serde(rename_all = "camelCase")]
1019pub struct FuturesFillsResponse {
1020    pub result: KrakenApiResult,
1021    #[serde(default)]
1022    pub server_time: Option<String>,
1023    #[serde(default)]
1024    pub error: Option<String>,
1025    #[serde(default)]
1026    pub fills: Vec<FuturesFill>,
1027}
1028
1029// Futures Positions Models
1030
1031#[derive(Debug, Clone, Serialize, Deserialize)]
1032#[serde(rename_all = "camelCase")]
1033pub struct FuturesPosition {
1034    pub side: KrakenPositionSide,
1035    pub symbol: String,
1036    #[serde(with = "decimal")]
1037    pub price: Decimal,
1038    pub fill_time: String,
1039    #[serde(with = "decimal")]
1040    pub size: Decimal,
1041    #[serde(default, with = "optional_decimal")]
1042    pub unrealized_funding: Option<Decimal>,
1043}
1044
1045#[derive(Debug, Clone, Serialize, Deserialize)]
1046#[serde(rename_all = "camelCase")]
1047pub struct FuturesOpenPositionsResponse {
1048    pub result: KrakenApiResult,
1049    #[serde(default)]
1050    pub server_time: Option<String>,
1051    #[serde(default)]
1052    pub error: Option<String>,
1053    #[serde(default)]
1054    pub open_positions: Vec<FuturesPosition>,
1055}
1056
1057// Futures Order Execution Models
1058
1059#[derive(Debug, Clone, Serialize, Deserialize)]
1060#[serde(rename_all = "camelCase")]
1061pub struct FuturesSendOrderResponse {
1062    pub result: KrakenApiResult,
1063    #[serde(default)]
1064    pub server_time: Option<String>,
1065    #[serde(default)]
1066    pub error: Option<String>,
1067    pub send_status: Option<FuturesSendStatus>,
1068}
1069
1070#[derive(Debug, Clone, Serialize, Deserialize)]
1071#[serde(rename_all = "camelCase")]
1072pub struct FuturesSendStatus {
1073    #[serde(rename = "order_id", default)]
1074    pub order_id: Option<String>,
1075    #[serde(rename = "order_tag", default)]
1076    pub order_tag: Option<String>,
1077    pub status: String,
1078    #[serde(default)]
1079    pub order_events: Option<Vec<FuturesSendOrderEvent>>,
1080    #[serde(rename = "cli_ord_id", default)]
1081    pub cli_ord_id: Option<String>,
1082    #[serde(rename = "receivedTime", default)]
1083    pub received_time: Option<String>,
1084}
1085
1086#[derive(Debug, Clone, Serialize, Deserialize)]
1087#[serde(rename_all = "camelCase")]
1088pub struct FuturesSendOrderEvent {
1089    #[serde(rename = "type")]
1090    pub event_type: KrakenFuturesOrderEventType,
1091    #[serde(default)]
1092    pub order: Option<FuturesOrderEventData>,
1093    #[serde(default)]
1094    pub order_trigger: Option<FuturesOrderTriggerData>,
1095    #[serde(default, with = "optional_decimal")]
1096    pub reduced_quantity: Option<Decimal>,
1097    // Execution event fields
1098    #[serde(rename = "executionId", default)]
1099    pub execution_id: Option<String>,
1100    #[serde(default, with = "optional_decimal")]
1101    pub price: Option<Decimal>,
1102    #[serde(default, with = "optional_decimal")]
1103    pub amount: Option<Decimal>,
1104    #[serde(rename = "orderPriorEdit", default)]
1105    pub order_prior_edit: Option<Box<FuturesOrderEventData>>,
1106    #[serde(rename = "orderPriorExecution", default)]
1107    pub order_prior_execution: Option<Box<FuturesOrderEventData>>,
1108    #[serde(rename = "takerReducedQuantity", default, with = "optional_decimal")]
1109    pub taker_reduced_quantity: Option<Decimal>,
1110    // Reject event fields
1111    #[serde(default)]
1112    pub reason: Option<String>,
1113    #[serde(default)]
1114    pub uid: Option<String>,
1115}
1116
1117#[derive(Debug, Clone, Serialize, Deserialize)]
1118#[serde(rename_all = "camelCase")]
1119pub struct FuturesOrderEventData {
1120    #[serde(rename = "orderId")]
1121    pub order_id: String,
1122    #[serde(rename = "cliOrdId", default)]
1123    pub cli_ord_id: Option<String>,
1124    #[serde(rename = "type")]
1125    pub order_type: KrakenFuturesOrderType,
1126    pub symbol: String,
1127    pub side: KrakenOrderSide,
1128    #[serde(with = "decimal")]
1129    pub quantity: Decimal,
1130    #[serde(with = "decimal")]
1131    pub filled: Decimal,
1132    #[serde(rename = "limitPrice", default, with = "optional_decimal")]
1133    pub limit_price: Option<Decimal>,
1134    #[serde(rename = "stopPrice", default, with = "optional_decimal")]
1135    pub stop_price: Option<Decimal>,
1136    pub timestamp: String,
1137    #[serde(rename = "lastUpdateTimestamp")]
1138    pub last_update_timestamp: String,
1139    #[serde(rename = "reduceOnly", default)]
1140    pub reduce_only: bool,
1141}
1142
1143#[derive(Debug, Clone, Serialize, Deserialize)]
1144#[serde(rename_all = "camelCase")]
1145pub struct FuturesOrderTriggerData {
1146    pub uid: String,
1147    #[serde(rename = "clientId", default)]
1148    pub client_id: Option<String>,
1149    #[serde(rename = "type")]
1150    pub order_type: KrakenFuturesOrderType,
1151    pub symbol: String,
1152    pub side: KrakenOrderSide,
1153    #[serde(with = "decimal")]
1154    pub quantity: Decimal,
1155    #[serde(rename = "limitPrice", default, with = "optional_decimal")]
1156    pub limit_price: Option<Decimal>,
1157    #[serde(rename = "limitPriceOffsetValue", default, with = "optional_decimal")]
1158    pub limit_price_offset_value: Option<Decimal>,
1159    #[serde(rename = "limitPriceOffsetUnit", default)]
1160    pub limit_price_offset_unit: Option<String>,
1161    #[serde(rename = "triggerPrice")]
1162    #[serde(with = "decimal")]
1163    pub trigger_price: Decimal,
1164    #[serde(rename = "triggerSide")]
1165    pub trigger_side: KrakenTriggerSide,
1166    #[serde(rename = "triggerSignal")]
1167    pub trigger_signal: KrakenTriggerSignal,
1168    #[serde(rename = "reduceOnly", default)]
1169    pub reduce_only: bool,
1170    pub timestamp: String,
1171    #[serde(rename = "lastUpdateTimestamp")]
1172    pub last_update_timestamp: String,
1173}
1174
1175#[derive(Debug, Clone, Serialize, Deserialize)]
1176#[serde(rename_all = "camelCase")]
1177pub struct FuturesCancelOrderResponse {
1178    pub result: KrakenApiResult,
1179    #[serde(default)]
1180    pub server_time: Option<String>,
1181    pub cancel_status: FuturesCancelStatus,
1182}
1183
1184#[derive(Debug, Clone, Serialize, Deserialize)]
1185#[serde(rename_all = "camelCase")]
1186pub struct FuturesCancelStatus {
1187    pub status: KrakenSendStatus,
1188    #[serde(rename = "order_id", default)]
1189    pub order_id: Option<String>,
1190    #[serde(rename = "cli_ord_id", default)]
1191    pub cli_ord_id: Option<String>,
1192}
1193
1194#[derive(Debug, Clone, Serialize, Deserialize)]
1195#[serde(rename_all = "camelCase")]
1196pub struct FuturesEditOrderResponse {
1197    pub result: KrakenApiResult,
1198    #[serde(default)]
1199    pub server_time: Option<String>,
1200    #[serde(default)]
1201    pub error: Option<String>,
1202    pub edit_status: Option<FuturesEditStatus>,
1203}
1204
1205#[derive(Debug, Clone, Serialize, Deserialize)]
1206#[serde(rename_all = "camelCase")]
1207pub struct FuturesEditStatus {
1208    pub status: String,
1209    /// The order ID under the key the edit API documents.
1210    #[serde(rename = "orderId", default)]
1211    pub order_id: Option<String>,
1212    /// The order ID under the snake-case key the send response uses, read as well since the key
1213    /// the edit response carries is not verified against the live venue.
1214    #[serde(rename = "order_id", default)]
1215    pub order_id_snake_case: Option<String>,
1216    #[serde(rename = "cli_ord_id", default)]
1217    pub cli_ord_id: Option<String>,
1218}
1219
1220#[derive(Debug, Clone, Serialize, Deserialize)]
1221#[serde(rename_all = "camelCase")]
1222pub struct FuturesBatchOrderResponse {
1223    pub result: KrakenApiResult,
1224    #[serde(default)]
1225    pub server_time: Option<String>,
1226    pub batch_status: Vec<FuturesSendStatus>,
1227}
1228
1229/// Response for batch cancel operations via `/derivatives/api/v3/batchorder`.
1230///
1231/// When sending only cancel operations, the response has a different format
1232/// with individual cancel status items.
1233#[derive(Debug, Clone, Serialize, Deserialize)]
1234#[serde(rename_all = "camelCase")]
1235pub struct FuturesBatchCancelResponse {
1236    pub result: KrakenApiResult,
1237    #[serde(default)]
1238    pub server_time: Option<String>,
1239    #[serde(default)]
1240    pub error: Option<String>,
1241    #[serde(default)]
1242    pub batch_status: Vec<FuturesBatchCancelStatus>,
1243}
1244
1245#[derive(Debug, Clone, Serialize, Deserialize)]
1246#[serde(rename_all = "camelCase")]
1247pub struct FuturesBatchCancelStatus {
1248    #[serde(default)]
1249    pub order_id: Option<String>,
1250    #[serde(default)]
1251    pub cli_ord_id: Option<String>,
1252    #[serde(default)]
1253    pub status: Option<KrakenSendStatus>,
1254    #[serde(default)]
1255    pub cancel_status: Option<FuturesCancelStatus>,
1256}
1257
1258#[derive(Debug, Clone, Serialize, Deserialize)]
1259#[serde(rename_all = "camelCase")]
1260pub struct FuturesCancelAllOrdersResponse {
1261    pub result: KrakenApiResult,
1262    #[serde(default)]
1263    pub server_time: Option<String>,
1264    pub cancel_status: FuturesCancelAllStatus,
1265}
1266
1267#[derive(Debug, Clone, Serialize, Deserialize)]
1268#[serde(rename_all = "camelCase")]
1269pub struct FuturesCancelAllStatus {
1270    pub status: KrakenSendStatus,
1271    #[serde(default)]
1272    pub cancelled_orders: Vec<CancelledOrder>,
1273}
1274
1275#[derive(Debug, Clone, Serialize, Deserialize)]
1276#[serde(rename_all = "camelCase")]
1277pub struct CancelledOrder {
1278    #[serde(rename = "order_id", default)]
1279    pub order_id: Option<String>,
1280    #[serde(default)]
1281    pub cli_ord_id: Option<String>,
1282}
1283
1284// Futures Public Executions Models
1285
1286/// Response from the Kraken Futures public executions endpoint.
1287#[derive(Debug, Clone, Serialize, Deserialize)]
1288#[serde(rename_all = "camelCase")]
1289pub struct FuturesPublicExecutionsResponse {
1290    pub elements: Vec<FuturesPublicExecutionElement>,
1291    #[serde(default)]
1292    pub len: Option<i64>,
1293    #[serde(default)]
1294    pub continuation_token: Option<String>,
1295}
1296
1297/// A single execution element from the public executions response.
1298#[derive(Debug, Clone, Serialize, Deserialize)]
1299pub struct FuturesPublicExecutionElement {
1300    pub uid: String,
1301    pub timestamp: i64,
1302    pub event: FuturesPublicExecutionEvent,
1303}
1304
1305/// The event wrapper containing the execution details.
1306#[derive(Debug, Clone, Serialize, Deserialize)]
1307pub struct FuturesPublicExecutionEvent {
1308    #[serde(rename = "Execution")]
1309    pub execution: FuturesPublicExecutionWrapper,
1310}
1311
1312/// Wrapper containing the actual execution data.
1313#[derive(Debug, Clone, Serialize, Deserialize)]
1314#[serde(rename_all = "camelCase")]
1315pub struct FuturesPublicExecutionWrapper {
1316    pub execution: FuturesPublicExecution,
1317    #[serde(default)]
1318    pub taker_reduced_quantity: Option<String>,
1319}
1320
1321/// The actual execution/trade data.
1322#[derive(Debug, Clone, Serialize, Deserialize)]
1323#[serde(rename_all = "camelCase")]
1324pub struct FuturesPublicExecution {
1325    pub uid: String,
1326    pub maker_order: FuturesPublicOrder,
1327    pub taker_order: FuturesPublicOrder,
1328    pub timestamp: i64,
1329    pub quantity: String,
1330    pub price: String,
1331    #[serde(default)]
1332    pub mark_price: Option<String>,
1333    #[serde(default)]
1334    pub limit_filled: Option<bool>,
1335    #[serde(default)]
1336    pub usd_value: Option<String>,
1337}
1338
1339/// Order information within an execution.
1340#[derive(Debug, Clone, Serialize, Deserialize)]
1341#[serde(rename_all = "camelCase")]
1342pub struct FuturesPublicOrder {
1343    pub uid: String,
1344    pub tradeable: String,
1345    pub direction: String,
1346    pub quantity: String,
1347    pub timestamp: i64,
1348    #[serde(default)]
1349    pub limit_price: Option<String>,
1350    #[serde(default)]
1351    pub order_type: Option<String>,
1352    #[serde(default)]
1353    pub reduce_only: Option<bool>,
1354    #[serde(default)]
1355    pub last_update_timestamp: Option<i64>,
1356}
1357
1358// Futures Accounts Models
1359
1360/// Response from the Kraken Futures accounts endpoint.
1361#[derive(Debug, Clone, Serialize, Deserialize)]
1362#[serde(rename_all = "camelCase")]
1363pub struct FuturesAccountsResponse {
1364    pub result: KrakenApiResult,
1365    #[serde(default)]
1366    pub accounts: AHashMap<String, FuturesAccount>,
1367    #[serde(default)]
1368    pub error: Option<String>,
1369    #[serde(default)]
1370    pub server_time: Option<String>,
1371}
1372
1373/// Kraken Futures account type.
1374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1375#[serde(rename_all = "camelCase")]
1376pub enum KrakenFuturesAccountType {
1377    /// Multi-collateral margin account (flex).
1378    MultiCollateralMarginAccount,
1379    /// Single-collateral margin account.
1380    MarginAccount,
1381    /// Cash account (no margin).
1382    CashAccount,
1383    /// Unknown account type.
1384    #[serde(other)]
1385    Unknown,
1386}
1387
1388/// A Kraken Futures account (margin or multi-collateral).
1389#[derive(Debug, Clone, Serialize, Deserialize)]
1390#[serde(rename_all = "camelCase")]
1391pub struct FuturesAccount {
1392    #[serde(rename = "type")]
1393    pub account_type: KrakenFuturesAccountType,
1394    /// Currency of a single-collateral margin account; its `auxiliary` and `marginRequirements`
1395    /// figures are in this currency. Absent on cash and flex accounts.
1396    #[serde(default)]
1397    pub currency: Option<String>,
1398    /// Balances for margin accounts (symbol -> amount).
1399    #[serde(default, with = "decimal_map")]
1400    pub balances: AHashMap<String, Decimal>,
1401    /// Currencies for flex/multi-collateral accounts.
1402    #[serde(default)]
1403    pub currencies: AHashMap<String, FuturesFlexCurrency>,
1404    /// Auxiliary info for margin accounts.
1405    #[serde(default)]
1406    pub auxiliary: Option<FuturesAuxiliary>,
1407    /// Margin requirements.
1408    #[serde(default)]
1409    pub margin_requirements: Option<FuturesMarginRequirements>,
1410    /// Portfolio value (for flex accounts).
1411    #[serde(default, with = "optional_decimal")]
1412    pub portfolio_value: Option<Decimal>,
1413    /// Available margin (for flex accounts).
1414    #[serde(default, with = "optional_decimal")]
1415    pub available_margin: Option<Decimal>,
1416    /// Initial margin (for flex accounts).
1417    #[serde(default, with = "optional_decimal")]
1418    pub initial_margin: Option<Decimal>,
1419    /// Total maintenance margin held for open positions (for flex accounts, in USD).
1420    #[serde(default, with = "optional_decimal")]
1421    pub maintenance_margin: Option<Decimal>,
1422    /// PnL (for flex accounts).
1423    #[serde(default, with = "optional_decimal")]
1424    pub pnl: Option<Decimal>,
1425}
1426
1427/// Currency info for flex/multi-collateral accounts.
1428#[derive(Debug, Clone, Serialize, Deserialize)]
1429#[serde(rename_all = "camelCase")]
1430pub struct FuturesFlexCurrency {
1431    #[serde(with = "decimal")]
1432    pub quantity: Decimal,
1433    #[serde(default, with = "optional_decimal")]
1434    pub value: Option<Decimal>,
1435    #[serde(default, with = "optional_decimal")]
1436    pub collateral: Option<Decimal>,
1437    #[serde(default, with = "optional_decimal")]
1438    pub available: Option<Decimal>,
1439}
1440
1441/// Auxiliary account info for margin accounts.
1442#[derive(Debug, Clone, Serialize, Deserialize)]
1443#[serde(rename_all = "camelCase")]
1444pub struct FuturesAuxiliary {
1445    #[serde(default, with = "optional_decimal")]
1446    pub usd: Option<Decimal>,
1447    /// Portfolio value.
1448    #[serde(default, with = "optional_decimal")]
1449    pub pv: Option<Decimal>,
1450    /// Profit/loss.
1451    #[serde(default, with = "optional_decimal")]
1452    pub pnl: Option<Decimal>,
1453    /// Available funds.
1454    #[serde(default, with = "optional_decimal")]
1455    pub af: Option<Decimal>,
1456    #[serde(default, with = "optional_decimal")]
1457    pub funding: Option<Decimal>,
1458}
1459
1460/// Margin requirements for an account.
1461#[derive(Debug, Clone, Serialize, Deserialize)]
1462#[serde(rename_all = "camelCase")]
1463pub struct FuturesMarginRequirements {
1464    /// Initial margin.
1465    #[serde(default, with = "optional_decimal")]
1466    pub im: Option<Decimal>,
1467    /// Maintenance margin.
1468    #[serde(default, with = "optional_decimal")]
1469    pub mm: Option<Decimal>,
1470    /// Liquidation threshold.
1471    #[serde(default, with = "optional_decimal")]
1472    pub lt: Option<Decimal>,
1473    /// Termination threshold.
1474    #[serde(default, with = "optional_decimal")]
1475    pub tt: Option<Decimal>,
1476}
1477
1478#[cfg(test)]
1479mod tests {
1480    use rstest::rstest;
1481    use rust_decimal_macros::dec;
1482
1483    use super::*;
1484
1485    fn load_test_data(filename: &str) -> String {
1486        let path = format!("test_data/{filename}");
1487        std::fs::read_to_string(&path)
1488            .unwrap_or_else(|e| panic!("Failed to load test data from {path}: {e}"))
1489    }
1490
1491    #[rstest]
1492    fn test_parse_futures_edit_order_response_reads_the_documented_order_id() {
1493        let data = load_test_data("http_edit_order_futures.json");
1494
1495        let response: FuturesEditOrderResponse = serde_json::from_str(&data).unwrap();
1496
1497        assert_eq!(response.result, KrakenApiResult::Success);
1498        assert_eq!(
1499            response.server_time.as_deref(),
1500            Some("2019-09-05T16:47:47.521Z")
1501        );
1502        let edit_status = response.edit_status.unwrap();
1503        assert_eq!(edit_status.status, "edited");
1504        assert_eq!(
1505            edit_status.order_id.as_deref(),
1506            Some("022774bc-2c4a-4f26-9317-436c8d85746d")
1507        );
1508        assert_eq!(edit_status.order_id_snake_case, None);
1509    }
1510
1511    #[rstest]
1512    fn test_parse_futures_cancel_all_orders_with_no_orders_to_cancel_status() {
1513        // Regression for the venue response shape that broke parsing in production:
1514        // the `cancelStatus.status` field is `noOrdersToCancel` even when one or more
1515        // orders were canceled in the same call. The `cancelledOrders` array carries
1516        // the actual canceled order ids, so the parser must accept this status.
1517        let raw = r#"{
1518            "result": "success",
1519            "cancelStatus": {
1520                "receivedTime": "2026-04-10T13:17:23.291Z",
1521                "cancelOnly": "PF_XBTUSD",
1522                "status": "noOrdersToCancel",
1523                "cancelledOrders": [
1524                    {
1525                        "order_id": "a182b1c0-cd01-4d1c-853b-605e936f412b",
1526                        "cliOrdId": "5f173994-f660-4809-b97a-586221fe5926"
1527                    }
1528                ],
1529                "orderEvents": []
1530            },
1531            "serverTime": "2026-04-10T13:17:23.291Z"
1532        }"#;
1533
1534        let response: FuturesCancelAllOrdersResponse =
1535            serde_json::from_str(raw).expect("Failed to parse cancel-all response");
1536
1537        assert_eq!(response.result, KrakenApiResult::Success);
1538        assert_eq!(
1539            response.cancel_status.status,
1540            KrakenSendStatus::NoOrdersToCancel
1541        );
1542        assert_eq!(response.cancel_status.cancelled_orders.len(), 1);
1543        assert_eq!(
1544            response.cancel_status.cancelled_orders[0]
1545                .order_id
1546                .as_deref(),
1547            Some("a182b1c0-cd01-4d1c-853b-605e936f412b")
1548        );
1549        assert_eq!(
1550            response.cancel_status.cancelled_orders[0]
1551                .cli_ord_id
1552                .as_deref(),
1553            Some("5f173994-f660-4809-b97a-586221fe5926")
1554        );
1555    }
1556
1557    #[rstest]
1558    fn test_parse_futures_open_orders() {
1559        let data = load_test_data("http_futures_open_orders.json");
1560        let response: FuturesOpenOrdersResponse =
1561            serde_json::from_str(&data).expect("Failed to parse futures open orders");
1562
1563        assert_eq!(response.result, KrakenApiResult::Success);
1564        assert_eq!(response.open_orders.len(), 3);
1565
1566        let order = &response.open_orders[0];
1567        assert_eq!(order.order_id, "2ce038ae-c144-4de7-a0f1-82f7f4fca864");
1568        assert_eq!(order.symbol, "PI_ETHUSD");
1569        assert_eq!(order.side, KrakenOrderSide::Buy);
1570        assert_eq!(order.order_type, KrakenFuturesOrderType::Limit);
1571        assert_eq!(order.limit_price, Some(dec!(1200)));
1572        assert_eq!(order.unfilled_size, Some(dec!(100)));
1573        assert_eq!(order.filled_size, dec!(0));
1574
1575        let trigger_order = &response.open_orders[1];
1576        assert_eq!(
1577            trigger_order.order_id,
1578            "c8135f52-2a86-4e26-b629-43cc37da9dbf"
1579        );
1580        assert_eq!(trigger_order.order_type, KrakenFuturesOrderType::TakeProfit);
1581        assert_eq!(trigger_order.symbol, "PI_XBTUSD");
1582        assert_eq!(trigger_order.side, KrakenOrderSide::Buy);
1583        assert_eq!(trigger_order.limit_price, None);
1584        assert_eq!(trigger_order.stop_price, Some(dec!(1880.4)));
1585        assert_eq!(trigger_order.unfilled_size, None);
1586        assert_eq!(trigger_order.received_time, "2023-04-07T15:14:25.995Z");
1587        assert_eq!(trigger_order.status, KrakenFuturesOrderStatus::Untouched);
1588        assert_eq!(trigger_order.filled_size, dec!(0));
1589        assert_eq!(trigger_order.reduce_only, Some(true));
1590        assert_eq!(trigger_order.last_update_time, "2023-04-07T15:14:25.995Z");
1591        assert_eq!(
1592            trigger_order.trigger_signal,
1593            Some(KrakenTriggerSignal::Last)
1594        );
1595        assert_eq!(trigger_order.cli_ord_id, None);
1596    }
1597
1598    #[rstest]
1599    fn test_parse_futures_orders_status() {
1600        let data = load_test_data("http_futures_orders_status.json");
1601        let response: FuturesOrdersStatusResponse =
1602            serde_json::from_str(&data).expect("Failed to parse futures orders status");
1603
1604        assert_eq!(response.result, KrakenApiResult::Success);
1605        assert_eq!(response.orders.len(), 2);
1606
1607        let part_filled = &response.orders[0];
1608        assert_eq!(
1609            part_filled.order.order_id,
1610            "5f6d15a5-8c9e-4b0a-9d3f-5a2b7c8d9e0f"
1611        );
1612        assert_eq!(
1613            part_filled.order.cli_ord_id.as_deref(),
1614            Some("uuid-mp-held-001")
1615        );
1616        assert_eq!(part_filled.order.side, KrakenOrderSide::Buy);
1617        assert_eq!(part_filled.order.quantity, Some(dec!(0.001)));
1618        assert_eq!(part_filled.order.filled, Some(dec!(0.0004)));
1619        assert_eq!(part_filled.order.limit_price, Some(dec!(70000)));
1620        assert!(!part_filled.order.reduce_only);
1621        assert_eq!(
1622            part_filled.status,
1623            KrakenFuturesOrderLifecycleStatus::Cancelled
1624        );
1625        assert_eq!(part_filled.update_reason.as_deref(), Some("PARTIAL_FILL"));
1626
1627        let open = &response.orders[1];
1628        assert_eq!(open.order.quantity, Some(dec!(0.0002)));
1629        assert_eq!(open.order.filled, Some(dec!(0)));
1630        assert!(open.order.reduce_only);
1631        assert_eq!(open.status, KrakenFuturesOrderLifecycleStatus::EnteredBook);
1632        assert_eq!(open.update_reason, None);
1633    }
1634
1635    #[rstest]
1636    fn test_parse_futures_instruments_maker_protection() {
1637        let data = load_test_data("http_futures_instruments_maker_protection.json");
1638        let response: FuturesInstrumentsResponse =
1639            serde_json::from_str(&data).expect("Failed to parse futures instruments");
1640
1641        assert_eq!(response.result, KrakenApiResult::Success);
1642        assert_eq!(response.instruments.len(), 2);
1643
1644        let protected = &response.instruments[0];
1645        assert_eq!(protected.symbol, "PF_ATOMUSD");
1646        assert_eq!(protected.maker_protection_millis, Some(20));
1647
1648        // The venue omits makerProtectionMillis entirely on unprotected
1649        // markets; absent must decode the same as no protection configured.
1650        let unprotected = &response.instruments[1];
1651        assert_eq!(unprotected.symbol, "PF_ETHUSD");
1652        assert_eq!(unprotected.maker_protection_millis, None);
1653    }
1654
1655    /// The open-orders and fills APIs document the client order ID as `cliOrdId`. The snake-case
1656    /// key is read as well, and a body carrying both reads the documented one rather than failing.
1657    #[rstest]
1658    #[case::documented_key(r#","cliOrdId":"doc-1""#, Some("doc-1"))]
1659    #[case::snake_case_key(r#","cli_ord_id":"snake-1""#, Some("snake-1"))]
1660    #[case::both_keys(r#","cliOrdId":"doc-1","cli_ord_id":"snake-1""#, Some("doc-1"))]
1661    #[case::neither_key("", None)]
1662    fn test_futures_open_order_and_fill_read_either_client_order_id_key(
1663        #[case] keys: &str,
1664        #[case] expected: Option<&str>,
1665    ) {
1666        let order: FuturesOpenOrder = serde_json::from_str(&format!(
1667            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}}}"#
1668        ))
1669        .unwrap();
1670        let fill: FuturesFill = serde_json::from_str(&format!(
1671            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}}}"#
1672        ))
1673        .unwrap();
1674
1675        assert_eq!(order.client_order_id(), expected);
1676        assert_eq!(fill.client_order_id(), expected);
1677    }
1678
1679    #[rstest]
1680    fn test_parse_futures_fills() {
1681        let data = load_test_data("http_futures_fills.json");
1682        let response: FuturesFillsResponse =
1683            serde_json::from_str(&data).expect("Failed to parse futures fills");
1684
1685        assert_eq!(response.result, KrakenApiResult::Success);
1686        assert_eq!(response.fills.len(), 3);
1687
1688        let fill = &response.fills[0];
1689        assert_eq!(fill.fill_id, "cad76f07-814e-4dc6-8478-7867407b6bff");
1690        assert_eq!(fill.symbol, "PI_XBTUSD");
1691        assert_eq!(fill.side, KrakenOrderSide::Buy);
1692        assert_eq!(fill.size, dec!(5000));
1693        assert_eq!(fill.price, dec!(27937.5));
1694        assert_eq!(fill.fill_type, KrakenFillType::Maker);
1695        assert_eq!(fill.fee_currency, Some("BTC".to_string()));
1696        assert_eq!(response.fills[1].fill_type, KrakenFillType::Taker);
1697        assert_eq!(response.fills[2].fill_type, KrakenFillType::Assignee);
1698    }
1699
1700    #[rstest]
1701    fn test_parse_futures_open_positions() {
1702        let data = load_test_data("http_futures_open_positions.json");
1703        let response: FuturesOpenPositionsResponse =
1704            serde_json::from_str(&data).expect("Failed to parse futures open positions");
1705
1706        assert_eq!(response.result, KrakenApiResult::Success);
1707        assert_eq!(response.open_positions.len(), 2);
1708
1709        let position = &response.open_positions[0];
1710        assert_eq!(position.side, KrakenPositionSide::Short);
1711        assert_eq!(position.symbol, "PI_XBTUSD");
1712        assert_eq!(position.size, dec!(8000));
1713        assert!(position.unrealized_funding.is_some());
1714    }
1715
1716    #[rstest]
1717    fn test_parse_futures_orderbook() {
1718        let data = load_test_data("http_futures_orderbook.json");
1719        let response: FuturesOrderBookResponse =
1720            serde_json::from_str(&data).expect("Failed to parse futures orderbook");
1721
1722        assert_eq!(response.result, KrakenApiResult::Success);
1723        assert_eq!(response.order_book.bids.len(), 3);
1724        assert_eq!(response.order_book.asks.len(), 3);
1725
1726        let best_bid = &response.order_book.bids[0];
1727        assert_eq!(best_bid.price, dec!(105900));
1728        assert_eq!(best_bid.qty, dec!(0.5));
1729
1730        let best_ask = &response.order_book.asks[0];
1731        assert_eq!(best_ask.price, dec!(105950));
1732        assert_eq!(best_ask.qty, dec!(0.3));
1733    }
1734
1735    #[rstest]
1736    fn test_parse_futures_historical_funding_rates() {
1737        let data = load_test_data("http_futures_historical_funding_rates.json");
1738        let response: FuturesHistoricalFundingRatesResponse =
1739            serde_json::from_str(&data).expect("Failed to parse historical funding rates");
1740
1741        assert_eq!(response.result, KrakenApiResult::Success);
1742        assert_eq!(response.rates.len(), 3);
1743
1744        let rate = &response.rates[0];
1745        assert_eq!(rate.timestamp, "2025-07-11T08:00:00.000Z");
1746        assert_eq!(rate.relative_funding_rate, dec!(0.0001));
1747        assert_eq!(rate.funding_rate, dec!(0.00005));
1748
1749        let negative_rate = &response.rates[1];
1750        assert_eq!(negative_rate.relative_funding_rate, dec!(-0.00005));
1751    }
1752
1753    #[rstest]
1754    fn test_parse_futures_orderbook_preserves_decimal_precision() {
1755        let data = load_test_data("http_futures_orderbook_precision.json");
1756        let level: FuturesOrderBookLevel = serde_json::from_str(&data).unwrap();
1757
1758        assert_eq!(level.price, dec!(0.1234567890123456789012345678));
1759        assert_eq!(level.qty, dec!(123456789.123456789));
1760    }
1761
1762    fn order_history_events(fixture: &str) -> FuturesOrderEventsResponse {
1763        let data = load_test_data(fixture);
1764        order_history_events_from(&data)
1765    }
1766
1767    fn order_history_events_from(data: &str) -> FuturesOrderEventsResponse {
1768        let response: FuturesOrderHistoryResponse =
1769            serde_json::from_str(data).expect("Failed to parse futures order history");
1770        response
1771            .into_order_events()
1772            .expect("the page carries elements")
1773    }
1774
1775    fn placed_element(order: &str) -> String {
1776        format!(
1777            r#"{{"elements":[{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderPlaced":{{"order":{order}}}}}}}]}}"#
1778        )
1779    }
1780
1781    /// Each documented event kind maps onto the event type the readers switch on.
1782    #[rstest]
1783    fn test_parse_futures_order_events_uses_enum_event_type() {
1784        let response = order_history_events("http_futures_order_events.json");
1785
1786        assert_eq!(response.order_events.len(), 3);
1787        assert_eq!(
1788            response.order_events[0].event_type,
1789            KrakenFuturesOrderEventType::Place
1790        );
1791        assert_eq!(
1792            response.order_events[1].event_type,
1793            KrakenFuturesOrderEventType::Edit
1794        );
1795        assert_eq!(
1796            response.order_events[2].event_type,
1797            KrakenFuturesOrderEventType::Cancel
1798        );
1799        assert_eq!(response.continuation_token.as_deref(), Some("simb178"));
1800    }
1801
1802    /// An update carries the order after the edit.
1803    #[rstest]
1804    fn test_parse_futures_order_events_update_uses_the_new_order() {
1805        let response = order_history_events("http_futures_order_events.json");
1806        let updated = &response.order_events[1].order;
1807
1808        assert_eq!(updated.filled, dec!(10000));
1809        assert_eq!(updated.order_type, KrakenFuturesOrderType::Market);
1810        assert_eq!(updated.limit_price, None, "a zero limit price is no price");
1811        assert_eq!(updated.cli_ord_id, None, "an empty client id is no id");
1812    }
1813
1814    /// The contract name is kept as the venue spells it, and the millisecond timestamps are
1815    /// formatted for the readers, which parse RFC 3339.
1816    #[rstest]
1817    fn test_parse_futures_order_events_keeps_the_tradeable_and_formats_timestamps() {
1818        let response = order_history_events("http_futures_order_events.json");
1819        let canceled = &response.order_events[2].order;
1820
1821        assert_eq!(canceled.symbol, "pi_xbtusd");
1822        assert_eq!(canceled.timestamp, "2023-04-07T13:00:00.000Z");
1823        assert_eq!(canceled.last_update_timestamp, "2023-04-07T16:00:00.000Z");
1824        assert!(canceled.reduce_only);
1825        assert_eq!(canceled.limit_price, Some(dec!(26000.0)));
1826        assert_eq!(
1827            canceled.stop_price, None,
1828            "the history schema has no trigger price"
1829        );
1830    }
1831
1832    /// A stop row carries no trigger price, which the engine needs to materialize a stop order,
1833    /// so it is reported as the limit or market order it executes as once triggered.
1834    #[rstest]
1835    #[case::with_limit("26000.0", KrakenFuturesOrderType::Limit, Some(dec!(26000.0)))]
1836    #[case::without_limit("0", KrakenFuturesOrderType::Market, None)]
1837    fn test_parse_futures_order_events_reports_a_stop_as_its_triggered_order(
1838        #[case] limit_price: &str,
1839        #[case] expected_type: KrakenFuturesOrderType,
1840        #[case] expected_price: Option<Decimal>,
1841    ) {
1842        let data = placed_element(&format!(
1843            r#"{{"uid":"o1","tradeable":"PI_XBTUSD","direction":"Sell","quantity":"2000","filled":"0","limitPrice":"{limit_price}","orderType":"Stop","clientId":"","reduceOnly":true,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}"#
1844        ));
1845        let response = order_history_events_from(&data);
1846        let order = &response.order_events[0].order;
1847
1848        assert_eq!(order.order_type, expected_type);
1849        assert_eq!(order.limit_price, expected_price);
1850        assert_eq!(order.stop_price, None);
1851    }
1852
1853    /// A market order's placeholder price, empty or zero, is no price; a limit order keeps its
1854    /// price even at zero, since futures instruments allow non-positive prices.
1855    #[rstest]
1856    #[case::market_empty("Market", "", None)]
1857    #[case::market_zero("Market", "0", None)]
1858    #[case::limit_zero("Limit", "0", Some(dec!(0)))]
1859    fn test_parse_futures_order_events_reads_the_limit_price_by_order_kind(
1860        #[case] order_type: &str,
1861        #[case] limit_price: &str,
1862        #[case] expected: Option<Decimal>,
1863    ) {
1864        let data = placed_element(&format!(
1865            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}}"#
1866        ));
1867        let response = order_history_events_from(&data);
1868
1869        assert_eq!(response.order_events[0].order.limit_price, expected);
1870    }
1871
1872    /// A rejected order reports as rejected.
1873    #[rstest]
1874    fn test_parse_futures_order_events_maps_a_rejection() {
1875        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"}}}]}"#;
1876        let response = order_history_events_from(data);
1877
1878        assert_eq!(
1879            response.order_events[0].event_type,
1880            KrakenFuturesOrderEventType::Reject
1881        );
1882    }
1883
1884    /// An order whose type the venue reports as `Unknown` establishes no order type, so its row
1885    /// is skipped and counted, while the sibling rows of the page are kept with their fields
1886    /// intact. A not-found event carries no state and is skipped without counting; an
1887    /// undocumented kind may carry state and counts.
1888    #[rstest]
1889    fn test_parse_futures_order_events_skips_an_unknown_order_type_and_keeps_siblings() {
1890        let response = order_history_events("http_futures_order_events_unknown.json");
1891
1892        assert_eq!(response.order_events.len(), 1);
1893        let sibling = &response.order_events[0];
1894        assert_eq!(sibling.event_type, KrakenFuturesOrderEventType::Edit);
1895        assert_eq!(sibling.reduced_quantity, None);
1896        assert_eq!(sibling.order.order_id, "abc");
1897        assert_eq!(sibling.order.cli_ord_id, None);
1898        assert_eq!(sibling.order.order_type, KrakenFuturesOrderType::Limit);
1899        assert_eq!(sibling.order.symbol, "PF_XBTUSD");
1900        assert_eq!(sibling.order.side, KrakenOrderSide::Buy);
1901        assert_eq!(sibling.order.quantity, dec!(1.0));
1902        assert_eq!(sibling.order.filled, dec!(0.5));
1903        assert_eq!(sibling.order.limit_price, Some(dec!(70000.0)));
1904        assert_eq!(sibling.order.stop_price, None);
1905        assert_eq!(sibling.order.timestamp, "2026-05-18T00:00:00.000Z");
1906        assert_eq!(
1907            sibling.order.last_update_timestamp,
1908            "2026-05-18T00:00:01.000Z"
1909        );
1910        assert!(!sibling.order.reduce_only);
1911        assert_eq!(
1912            response.server_time.as_deref(),
1913            Some("2026-05-18T00:00:03.000Z")
1914        );
1915        assert_eq!(response.continuation_token, None);
1916        assert_eq!(
1917            response.skipped_rows.len(),
1918            2,
1919            "the Unknown type and the undocumented kind count; the not-found event does not"
1920        );
1921    }
1922
1923    /// A page reaches back to its oldest event whatever the projection keeps, so the oldest time
1924    /// counts a not-found or undocumented element as well as a kept one.
1925    #[rstest]
1926    #[case::not_found(r#"{"OrderNotFound":{"orderId":"gone"}}"#)]
1927    #[case::undocumented(r#"{"OrderSomethingNew":{"order":{"uid":"x"}}}"#)]
1928    fn test_parse_futures_order_events_oldest_time_counts_every_element(#[case] oldest: &str) {
1929        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"}}"#;
1930        let data = format!(
1931            r#"{{"elements":[{{"uid":"e2","timestamp":1680876931000,"event":{kept}}},{{"uid":"e1","timestamp":1680876930000,"event":{oldest}}}]}}"#
1932        );
1933
1934        let response = order_history_events_from(&data);
1935
1936        assert_eq!(response.order_events.len(), 1);
1937        assert_eq!(response.oldest_event_ms, Some(1_680_876_930_000));
1938    }
1939
1940    /// A row skipped for a timestamp before the epoch names the order it carries, so a lookup
1941    /// cannot rule that order out.
1942    #[rstest]
1943    fn test_parse_futures_order_events_names_the_order_of_a_pre_epoch_row() {
1944        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"}}}]}"#;
1945
1946        let response = order_history_events_from(data);
1947
1948        assert!(response.order_events.is_empty());
1949        assert_eq!(
1950            response.skipped_rows,
1951            vec![SkippedHistoryRow {
1952                order_id: Some("o-pre".to_string()),
1953                tradeable: Some("PF_XBTUSD".to_string()),
1954                event_ms: 1_680_876_930_250,
1955                undocumented: false,
1956            }]
1957        );
1958    }
1959
1960    /// A page reaches back to its oldest event whatever the projection keeps, so a skipped row
1961    /// counts toward the oldest time. A skipped row names its order when it carries one, and an
1962    /// undocumented kind is marked, since its shape is only a guess.
1963    #[rstest]
1964    fn test_parse_futures_order_events_reports_what_the_page_covers() {
1965        let response = order_history_events("http_futures_order_events_unknown.json");
1966
1967        assert_eq!(
1968            response.oldest_event_ms,
1969            Some(1_779_062_400_000),
1970            "the oldest element is the skipped Unknown-type row"
1971        );
1972        let rows: Vec<_> = response
1973            .skipped_rows
1974            .iter()
1975            .map(|row| (row.order_id.as_deref(), row.undocumented))
1976            .collect();
1977        assert_eq!(rows, vec![(Some("abc"), false), (Some("abc"), true)]);
1978    }
1979
1980    /// `Unknown` is how the venue reports a source type it could not decode, so neither it nor a
1981    /// missing type establishes what the order is: the row is skipped with its price rather than
1982    /// reported as a market order, the sibling row is kept, and the row is listed as skipped.
1983    #[rstest]
1984    #[case::missing_type("")]
1985    #[case::undocumented_type(r#""orderType":"SomethingNew","#)]
1986    fn test_parse_futures_order_events_skips_an_unmappable_order_type(#[case] order_type: &str) {
1987        let data = format!(
1988            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}}}}}}}}]}}"#
1989        );
1990        let response = order_history_events_from(&data);
1991
1992        assert_eq!(response.order_events.len(), 1);
1993        let sibling = &response.order_events[0];
1994        assert_eq!(sibling.event_type, KrakenFuturesOrderEventType::Place);
1995        assert_eq!(sibling.order.order_id, "o2");
1996        assert_eq!(sibling.order.cli_ord_id.as_deref(), Some("cl-2"));
1997        assert_eq!(sibling.order.order_type, KrakenFuturesOrderType::Limit);
1998        assert_eq!(sibling.order.symbol, "PF_XBTUSD");
1999        assert_eq!(sibling.order.side, KrakenOrderSide::Buy);
2000        assert_eq!(sibling.order.quantity, dec!(2));
2001        assert_eq!(sibling.order.filled, dec!(0.5));
2002        assert_eq!(sibling.order.limit_price, Some(dec!(69500.5)));
2003        assert_eq!(sibling.order.stop_price, None);
2004        assert_eq!(sibling.order.timestamp, "2023-04-07T14:20:45.500Z");
2005        assert_eq!(
2006            sibling.order.last_update_timestamp,
2007            "2023-04-07T14:20:45.500Z"
2008        );
2009        assert!(!sibling.order.reduce_only);
2010        assert_eq!(
2011            response.skipped_rows.len(),
2012            1,
2013            "the row is listed as skipped"
2014        );
2015    }
2016
2017    /// A timestamp before the epoch cannot be reported, so the row is skipped rather than dated
2018    /// at the epoch.
2019    #[rstest]
2020    fn test_parse_futures_order_events_skips_a_negative_timestamp() {
2021        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}}}}]}"#;
2022        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2023        let response = response.into_order_events().unwrap();
2024
2025        assert!(response.order_events.is_empty());
2026        assert_eq!(
2027            response.skipped_rows.len(),
2028            1,
2029            "the row is listed as skipped"
2030        );
2031    }
2032
2033    /// The kind is found wherever it sits among the event's keys.
2034    #[rstest]
2035    fn test_parse_futures_order_events_finds_the_kind_after_other_keys() {
2036        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}}}}]}"#;
2037        let response = order_history_events_from(data);
2038
2039        assert_eq!(
2040            response.order_events[0].event_type,
2041            KrakenFuturesOrderEventType::Cancel
2042        );
2043    }
2044
2045    /// A report is dated at the event when that is later than the order's own update stamp, as
2046    /// for a refused edit.
2047    #[rstest]
2048    fn test_parse_futures_order_events_dates_a_report_at_the_event() {
2049        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}}}}]}"#;
2050        let response = order_history_events_from(data);
2051
2052        assert_eq!(
2053            response.order_events[0].order.last_update_timestamp,
2054            "2023-04-07T14:20:45.500Z"
2055        );
2056    }
2057
2058    /// An empty event object is an undocumented kind, not a failed page.
2059    #[rstest]
2060    fn test_parse_futures_order_events_tolerates_an_empty_event() {
2061        let data = r#"{"elements":[{"uid":"e1","timestamp":1,"event":{}}]}"#;
2062        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2063
2064        assert!(matches!(
2065            response.elements.as_deref(),
2066            Some([FuturesOrderHistoryElement { event: FuturesOrderHistoryEvent::Unknown { kind, .. }, .. }]) if kind.is_empty()
2067        ));
2068    }
2069
2070    /// A documented kind whose payload does not decode is a skipped row naming what can be read of
2071    /// it, each field from the first documented position holding a usable value, and the page's
2072    /// other rows are kept.
2073    #[rstest]
2074    #[case::bad_quantity(
2075        r#"{"OrderCancelled":{"order":{"uid":"o-bad","tradeable":"PF_XBTUSD","quantity":"oops"}}}"#,
2076        Some("o-bad"),
2077        Some("PF_XBTUSD")
2078    )]
2079    #[case::number_out_of_range(
2080        r#"{"OrderCancelled":{"order":{"uid":"o-bad","tradeable":"PF_XBTUSD","quantity":1e999}}}"#,
2081        Some("o-bad"),
2082        Some("PF_XBTUSD")
2083    )]
2084    #[case::missing_uid(
2085        r#"{"OrderCancelled":{"order":{"tradeable":"PF_XBTUSD"}}}"#,
2086        None,
2087        Some("PF_XBTUSD")
2088    )]
2089    #[case::mistyped_uid(
2090        r#"{"OrderCancelled":{"order":{"uid":5,"tradeable":"PF_XBTUSD"}}}"#,
2091        None,
2092        Some("PF_XBTUSD")
2093    )]
2094    #[case::invalid_uid(
2095        r#"{"OrderCancelled":{"order":{"uid":"","tradeable":"PF_XBTUSD"}}}"#,
2096        None,
2097        Some("PF_XBTUSD")
2098    )]
2099    #[case::missing_tradeable(
2100        r#"{"OrderCancelled":{"order":{"uid":"o-bad"}}}"#,
2101        Some("o-bad"),
2102        None
2103    )]
2104    #[case::payload_not_an_object(r#"{"OrderCancelled":"gone"}"#, None, None)]
2105    #[case::no_order_position(r#"{"OrderCancelled":{}}"#, None, None)]
2106    #[case::mistyped_not_found(r#"{"OrderNotFound":{"orderId":5}}"#, None, None)]
2107    #[case::update_read_from_the_old_order(
2108        r#"{"OrderUpdated":{"newOrder":{"uid":"","tradeable":""},"oldOrder":{"uid":"o-bad","tradeable":"PF_XBTUSD"}}}"#,
2109        Some("o-bad"),
2110        Some("PF_XBTUSD")
2111    )]
2112    #[case::refused_edit_read_from_the_attempted_order(
2113        r#"{"OrderEditRejected":{"oldOrder":{"uid":7},"attemptedOrder":{"uid":"o-bad","tradeable":"PF_XBTUSD"}}}"#,
2114        Some("o-bad"),
2115        Some("PF_XBTUSD")
2116    )]
2117    fn test_parse_futures_order_events_skips_an_unreadable_row_and_keeps_siblings(
2118        #[case] unreadable: &str,
2119        #[case] expected_order: Option<&str>,
2120        #[case] expected_contract: Option<&str>,
2121    ) {
2122        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}}}"#;
2123        let data = format!(
2124            r#"{{"elements":[{{"uid":"e2","timestamp":1680876931000,"event":{unreadable}}},{{"uid":"e1","timestamp":1680876930000,"event":{sibling}}}]}}"#
2125        );
2126
2127        let response = order_history_events_from(&data);
2128
2129        assert_eq!(response.order_events.len(), 1);
2130        assert_eq!(response.order_events[0].order.order_id, "o-sibling");
2131        assert_eq!(
2132            response.skipped_rows,
2133            vec![SkippedHistoryRow {
2134                order_id: expected_order.map(str::to_string),
2135                tradeable: expected_contract.map(str::to_string),
2136                event_ms: 1_680_876_931_000,
2137                undocumented: false,
2138            }]
2139        );
2140    }
2141
2142    /// A row whose order ID cannot be an ID does not decode, so it names no order unless another
2143    /// documented position of the row does.
2144    #[rstest]
2145    #[case::empty_on_a_limit_row("", "Limit")]
2146    #[case::empty_on_an_unknown_type("", "Unknown")]
2147    #[case::whitespace(" ", "Limit")]
2148    #[case::non_ascii("\u{e9}", "Limit")]
2149    fn test_parse_futures_order_events_reads_an_invalid_order_id_as_naming_no_order(
2150        #[case] uid: &str,
2151        #[case] order_type: &str,
2152    ) {
2153        let data = format!(
2154            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}}}}}}}}]}}"#
2155        );
2156
2157        let response = order_history_events_from(&data);
2158
2159        assert!(response.order_events.is_empty());
2160        assert_eq!(
2161            response.skipped_rows,
2162            vec![SkippedHistoryRow {
2163                order_id: None,
2164                tradeable: Some("PF_XBTUSD".to_string()),
2165                event_ms: 1_680_876_930_250,
2166                undocumented: false,
2167            }]
2168        );
2169    }
2170
2171    /// An update's invalid new order leaves its old order to name the row, whatever else decodes.
2172    #[rstest]
2173    fn test_parse_futures_order_events_reads_an_update_from_its_old_order_past_an_invalid_id() {
2174        let order = |uid: &str| {
2175            format!(
2176                r#"{{"uid":"{uid}","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}"#
2177            )
2178        };
2179        let data = format!(
2180            r#"{{"elements":[{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderUpdated":{{"oldOrder":{},"newOrder":{}}}}}}}]}}"#,
2181            order("o-old"),
2182            order(""),
2183        );
2184
2185        let response = order_history_events_from(&data);
2186
2187        assert_eq!(
2188            response.skipped_rows,
2189            vec![SkippedHistoryRow {
2190                order_id: Some("o-old".to_string()),
2191                tradeable: Some("PF_XBTUSD".to_string()),
2192                event_ms: 1_680_876_930_250,
2193                undocumented: false,
2194            }]
2195        );
2196    }
2197
2198    /// A row keeps the first documented kind it names, so a malformed later key does not cost it.
2199    #[rstest]
2200    fn test_parse_futures_order_events_keeps_the_first_documented_kind() {
2201        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"}}]}"#;
2202
2203        let response = order_history_events_from(data);
2204
2205        assert!(response.skipped_rows.is_empty());
2206        assert_eq!(
2207            response.order_events[0].event_type,
2208            KrakenFuturesOrderEventType::Place
2209        );
2210    }
2211
2212    /// A row's envelope is the page's structure, which the documentation requires of every
2213    /// element, so an element without one fails the read rather than reading as a skipped row.
2214    #[rstest]
2215    #[case::not_an_object("1")]
2216    #[case::no_event(r#"{"uid":"e1","timestamp":1}"#)]
2217    #[case::event_not_an_object(r#"{"uid":"e1","timestamp":1,"event":"OrderPlaced"}"#)]
2218    #[case::no_uid(r#"{"timestamp":1,"event":{}}"#)]
2219    #[case::no_timestamp(r#"{"uid":"e1","event":{}}"#)]
2220    #[case::mistyped_timestamp(r#"{"uid":"e1","timestamp":"now","event":{}}"#)]
2221    fn test_parse_futures_order_events_fail_on_an_invalid_element(#[case] element: &str) {
2222        let data = format!(r#"{{"elements":[{element}]}}"#);
2223
2224        assert!(serde_json::from_str::<FuturesOrderHistoryResponse>(&data).is_err());
2225    }
2226
2227    /// A numeric quantity keeps all its digits through the row's raw JSON text.
2228    #[rstest]
2229    fn test_parse_futures_order_events_keeps_a_numeric_quantity_exact() {
2230        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}}}}]}"#;
2231
2232        let response = order_history_events_from(data);
2233
2234        assert_eq!(
2235            response.order_events[0].order.quantity,
2236            rust_decimal_macros::dec!(1.2345678901234567891)
2237        );
2238    }
2239
2240    /// The order type is the only place the history states a time in force or post-only.
2241    #[rstest]
2242    #[case::limit("Limit", TimeInForce::Gtc, false)]
2243    #[case::ioc("IoC", TimeInForce::Ioc, false)]
2244    #[case::hedge_ioc("HedgeImmediateOrCancel", TimeInForce::Ioc, false)]
2245    #[case::fill_or_kill("FillOrKill", TimeInForce::Fok, false)]
2246    #[case::post("Post", TimeInForce::Gtc, true)]
2247    #[case::market("Market", TimeInForce::Gtc, false)]
2248    #[case::stop("Stop", TimeInForce::Gtc, false)]
2249    fn test_parse_futures_order_events_read_the_time_in_force_from_the_type(
2250        #[case] order_type: &str,
2251        #[case] expected_time_in_force: TimeInForce,
2252        #[case] expected_post_only: bool,
2253    ) {
2254        let data = format!(
2255            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}}}}}}}}]}}"#
2256        );
2257
2258        let response = order_history_events_from(&data);
2259
2260        let event = &response.order_events[0].order;
2261        assert_eq!(event.time_in_force, expected_time_in_force);
2262        assert_eq!(event.post_only, expected_post_only);
2263    }
2264
2265    /// An order whose direction the venue could not decode has no side to report, so it is skipped.
2266    #[rstest]
2267    fn test_parse_futures_order_events_skips_an_unknown_direction() {
2268        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":""}}}]}"#;
2269        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2270        let response = response.into_order_events().unwrap();
2271
2272        assert!(response.order_events.is_empty());
2273        assert_eq!(
2274            response.skipped_rows.len(),
2275            1,
2276            "the row is listed as skipped"
2277        );
2278    }
2279
2280    /// A venue error reported with a success status fails the read with the venue's reason, not
2281    /// as an empty page.
2282    #[rstest]
2283    fn test_parse_futures_order_events_fails_on_a_venue_error_body() {
2284        let data = r#"{"result":"error","error":"apiLimitExceeded"}"#;
2285        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2286
2287        let error = response
2288            .into_order_events()
2289            .expect_err("a venue error must fail the read");
2290
2291        assert!(
2292            matches!(&error, KrakenHttpError::ApiError(reasons) if reasons == &["apiLimitExceeded"]),
2293            "unexpected error: {error}"
2294        );
2295    }
2296
2297    /// A body without an `elements` array is not an order history page.
2298    #[rstest]
2299    fn test_parse_futures_order_events_requires_elements() {
2300        let data = r#"{"serverTime":"2023-04-07T16:30:45.678Z"}"#;
2301        let response: FuturesOrderHistoryResponse = serde_json::from_str(data).unwrap();
2302
2303        assert!(matches!(
2304            response.into_order_events(),
2305            Err(KrakenHttpError::ParseError(_))
2306        ));
2307    }
2308
2309    #[rstest]
2310    fn test_parse_futures_order_trigger_data_tolerates_unknown_enum_values() {
2311        // Trigger payload uses non-optional enums, so an `"unknown"` on
2312        // triggerSide / triggerSignal must not fail the sendStatus batch.
2313        let data = load_test_data("http_send_order_futures_unknown_trigger.json");
2314        let response: FuturesSendOrderResponse =
2315            serde_json::from_str(&data).expect("Failed to parse send-order response with unknown");
2316
2317        let send_status = response.send_status.expect("sendStatus missing");
2318        let order_events = send_status.order_events.expect("orderEvents missing");
2319        let trigger = order_events[0]
2320            .order_trigger
2321            .as_ref()
2322            .expect("orderTrigger missing");
2323
2324        assert_eq!(trigger.order_type, KrakenFuturesOrderType::Unknown);
2325        assert_eq!(trigger.trigger_side, KrakenTriggerSide::Unknown);
2326        assert_eq!(trigger.trigger_signal, KrakenTriggerSignal::Unknown);
2327    }
2328
2329    #[rstest]
2330    fn test_parse_futures_send_order_execution_event_uses_enum_event_type() {
2331        let data = r#"
2332        {
2333          "result": "success",
2334          "sendStatus": {
2335            "status": "placed",
2336            "orderEvents": [
2337              {
2338                "type": "EXECUTION",
2339                "executionId": "c8a35168-8d52-4609-944f-3f32bb0d5c77",
2340                "price": 35000.5,
2341                "amount": 1.25,
2342                "orderPriorExecution": {
2343                  "orderId": "c8a35168-8d52-4609-944f-3f32bb0d5c77",
2344                  "cliOrdId": "test-order-001",
2345                  "type": "lmt",
2346                  "symbol": "PI_XBTUSD",
2347                  "side": "buy",
2348                  "quantity": 2.0,
2349                  "filled": 0.0,
2350                  "limitPrice": 35000.5,
2351                  "timestamp": "2024-01-15T10:30:45.123Z",
2352                  "lastUpdateTimestamp": "2024-01-15T10:30:45.123Z",
2353                  "reduceOnly": false
2354                }
2355              }
2356            ]
2357          }
2358        }
2359        "#;
2360        let response: FuturesSendOrderResponse =
2361            serde_json::from_str(data).expect("Failed to parse futures send order response");
2362
2363        let send_status = response.send_status.expect("sendStatus missing");
2364        let order_events = send_status.order_events.expect("orderEvents missing");
2365
2366        assert_eq!(order_events.len(), 1);
2367        assert_eq!(
2368            order_events[0].event_type,
2369            KrakenFuturesOrderEventType::Execution
2370        );
2371    }
2372}