Skip to main content

nautilus_kraken/websocket/futures/
parse.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//! WebSocket message parsers for converting Kraken Futures streaming data to Nautilus domain models.
17
18use anyhow::Context;
19use nautilus_core::{UUID4, datetime::NANOSECONDS_IN_MILLISECOND, nanos::UnixNanos};
20use nautilus_model::{
21    data::{
22        BookOrder, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate, OrderBookDelta, QuoteTick,
23        TradeTick,
24    },
25    enums::{AggressorSide, BookAction, OrderSide, OrderStatus, OrderType, TriggerType},
26    identifiers::{AccountId, ClientOrderId, TradeId},
27    instruments::{Instrument, any::InstrumentAny},
28    reports::{FillReport, OrderStatusReport},
29    types::{Money, Price, Quantity},
30};
31use rust_decimal::Decimal;
32
33use super::messages::{
34    KrakenFuturesBookDelta, KrakenFuturesBookSnapshot, KrakenFuturesFill, KrakenFuturesOpenOrder,
35    KrakenFuturesTickerData, KrakenFuturesTradeData,
36};
37use crate::common::{
38    enums::KrakenOrderSide,
39    parse::{fee_currency, parse_futures_order_type_time_in_force, parse_venue_order_id},
40};
41
42fn millis_to_nanos(millis: i64) -> UnixNanos {
43    UnixNanos::from((millis as u64) * NANOSECONDS_IN_MILLISECOND)
44}
45
46pub fn parse_futures_ws_quote_tick(
47    ticker: &KrakenFuturesTickerData,
48    instrument: &InstrumentAny,
49    ts_init: UnixNanos,
50) -> anyhow::Result<QuoteTick> {
51    let price_precision = instrument.price_precision();
52    let size_precision = instrument.size_precision();
53
54    let bid = ticker.bid.context("Ticker missing bid")?;
55    let ask = ticker.ask.context("Ticker missing ask")?;
56    let bid_size = ticker.bid_size.unwrap_or(Decimal::ZERO);
57    let ask_size = ticker.ask_size.unwrap_or(Decimal::ZERO);
58
59    let bid_price =
60        Price::from_decimal_dp(bid, price_precision).context("Failed to construct bid Price")?;
61    let ask_price =
62        Price::from_decimal_dp(ask, price_precision).context("Failed to construct ask Price")?;
63    let bid_qty = Quantity::from_decimal_dp(bid_size, size_precision)
64        .context("Failed to construct bid Quantity")?;
65    let ask_qty = Quantity::from_decimal_dp(ask_size, size_precision)
66        .context("Failed to construct ask Quantity")?;
67
68    let ts_event = ticker.time.map_or(ts_init, millis_to_nanos);
69
70    Ok(QuoteTick::new(
71        instrument.id(),
72        bid_price,
73        ask_price,
74        bid_qty,
75        ask_qty,
76        ts_event,
77        ts_init,
78    ))
79}
80
81pub fn parse_futures_ws_trade_tick(
82    trade: &KrakenFuturesTradeData,
83    instrument: &InstrumentAny,
84    ts_init: UnixNanos,
85) -> anyhow::Result<TradeTick> {
86    let price_precision = instrument.price_precision();
87    let size_precision = instrument.size_precision();
88
89    let price = Price::from_decimal_dp(trade.price, price_precision)
90        .context("Failed to construct trade Price")?;
91    let size = Quantity::from_decimal_dp(trade.qty, size_precision)
92        .context("Failed to construct trade Quantity")?;
93
94    let aggressor = match trade.side {
95        KrakenOrderSide::Buy => AggressorSide::Buy,
96        KrakenOrderSide::Sell => AggressorSide::Sell,
97    };
98
99    let trade_id = trade
100        .uid
101        .as_deref()
102        .map_or_else(|| TradeId::new(trade.seq.to_string()), TradeId::new);
103
104    let ts_event = millis_to_nanos(trade.time);
105
106    TradeTick::new_checked(
107        instrument.id(),
108        price,
109        size,
110        aggressor,
111        trade_id,
112        ts_event,
113        ts_init,
114    )
115    .context("Failed to construct TradeTick from Kraken futures trade")
116}
117
118pub fn parse_futures_ws_book_snapshot_deltas(
119    snapshot: &KrakenFuturesBookSnapshot,
120    instrument: &InstrumentAny,
121    sequence: u64,
122    ts_init: UnixNanos,
123) -> anyhow::Result<Vec<OrderBookDelta>> {
124    let instrument_id = instrument.id();
125    let price_precision = instrument.price_precision();
126    let size_precision = instrument.size_precision();
127    let ts_event = millis_to_nanos(snapshot.timestamp);
128
129    let capacity = snapshot.bids.len() + snapshot.asks.len() + 1;
130    let mut deltas = Vec::with_capacity(capacity);
131    let mut seq = sequence;
132
133    // Leading CLEAR delta to reset the book
134    deltas.push(OrderBookDelta::clear(instrument_id, seq, ts_event, ts_init));
135    seq += 1;
136
137    for level in &snapshot.bids {
138        if level.qty <= Decimal::ZERO {
139            continue;
140        }
141        let price = Price::from_decimal_dp(level.price, price_precision)?;
142        let size = Quantity::from_decimal_dp(level.qty, size_precision)?;
143        let order_id = price.raw() as u64;
144
145        let order = BookOrder::new(OrderSide::Buy, price, size, order_id);
146        deltas.push(OrderBookDelta::new(
147            instrument_id,
148            BookAction::Add,
149            order,
150            0,
151            seq,
152            ts_event,
153            ts_init,
154        ));
155        seq += 1;
156    }
157
158    for level in &snapshot.asks {
159        if level.qty <= Decimal::ZERO {
160            continue;
161        }
162        let price = Price::from_decimal_dp(level.price, price_precision)?;
163        let size = Quantity::from_decimal_dp(level.qty, size_precision)?;
164        let order_id = price.raw() as u64;
165
166        let order = BookOrder::new(OrderSide::Sell, price, size, order_id);
167        deltas.push(OrderBookDelta::new(
168            instrument_id,
169            BookAction::Add,
170            order,
171            0,
172            seq,
173            ts_event,
174            ts_init,
175        ));
176        seq += 1;
177    }
178
179    Ok(deltas)
180}
181
182pub fn parse_futures_ws_book_delta(
183    delta: &KrakenFuturesBookDelta,
184    instrument: &InstrumentAny,
185    sequence: u64,
186    ts_init: UnixNanos,
187) -> anyhow::Result<OrderBookDelta> {
188    let price_precision = instrument.price_precision();
189    let size_precision = instrument.size_precision();
190
191    let price = Price::from_decimal_dp(delta.price, price_precision)?;
192    let size = Quantity::from_decimal_dp(delta.qty, size_precision)?;
193
194    let action = if size.is_zero() {
195        BookAction::Delete
196    } else {
197        BookAction::Update
198    };
199
200    let side = match delta.side {
201        KrakenOrderSide::Buy => OrderSide::Buy,
202        KrakenOrderSide::Sell => OrderSide::Sell,
203    };
204
205    let order_id = price.raw() as u64;
206
207    let order = BookOrder::new(side, price, size, order_id);
208    let ts_event = millis_to_nanos(delta.timestamp);
209
210    Ok(OrderBookDelta::new(
211        instrument.id(),
212        action,
213        order,
214        0,
215        sequence,
216        ts_event,
217        ts_init,
218    ))
219}
220
221fn parse_ws_direction(direction: i32) -> OrderSide {
222    if direction == 0 {
223        OrderSide::Buy
224    } else {
225        OrderSide::Sell
226    }
227}
228
229fn infer_order_status(order: &KrakenFuturesOpenOrder, is_cancel: bool) -> OrderStatus {
230    if order.filled >= order.qty && order.qty > Decimal::ZERO {
231        OrderStatus::Filled
232    } else if is_cancel {
233        OrderStatus::Canceled
234    } else if order.filled > Decimal::ZERO {
235        OrderStatus::PartiallyFilled
236    } else {
237        OrderStatus::Accepted
238    }
239}
240
241pub fn parse_futures_ws_order_status_report(
242    order: &KrakenFuturesOpenOrder,
243    is_cancel: bool,
244    reason: Option<&str>,
245    instrument: &InstrumentAny,
246    account_id: AccountId,
247    ts_init: UnixNanos,
248) -> anyhow::Result<OrderStatusReport> {
249    let venue_order_id = parse_venue_order_id(&order.order_id, "futures order delta")?;
250    let order_side = parse_ws_direction(order.direction);
251    let order_type = OrderType::from(order.order_type);
252    let order_type = if order_type == OrderType::MarketIfTouched && order.limit_price.is_some() {
253        OrderType::LimitIfTouched
254    } else {
255        order_type
256    };
257    let order_status = infer_order_status(order, is_cancel);
258    let (time_in_force, post_only) = parse_futures_order_type_time_in_force(order.order_type);
259
260    let price_precision = instrument.price_precision();
261    let size_precision = instrument.size_precision();
262
263    let quantity = Quantity::from_decimal_dp(order.qty, size_precision)
264        .context("Failed to parse order qty")?;
265    let filled_qty = Quantity::from_decimal_dp(order.filled, size_precision)
266        .context("Failed to parse order filled")?;
267
268    let ts_accepted = millis_to_nanos(order.time);
269    let ts_last = millis_to_nanos(order.last_update_time);
270
271    let mut report = OrderStatusReport {
272        account_id,
273        instrument_id: instrument.id(),
274        client_order_id: order.cli_ord_id.as_ref().map(ClientOrderId::new),
275        venue_order_id,
276        order_side: order_side.into(),
277        order_type,
278        time_in_force,
279        order_status,
280        quantity,
281        filled_qty,
282        report_id: UUID4::new(),
283        ts_accepted,
284        ts_last,
285        ts_init,
286        order_list_id: None,
287        venue_position_id: None,
288        linked_order_ids: None,
289        parent_order_id: None,
290        contingency_type: None,
291        expire_time: None,
292        price: None,
293        activation_price: None,
294        trigger_price: None,
295        trigger_type: None,
296        limit_offset: None,
297        trailing_offset: None,
298        trailing_offset_type: None,
299        display_qty: None,
300        avg_px: None,
301        post_only,
302        reduce_only: order.reduce_only,
303        cancel_reason: None,
304        ts_triggered: None,
305    };
306
307    if let Some(px) = order.limit_price {
308        report.price = Some(Price::from_decimal_dp(px, price_precision)?);
309    }
310
311    if let Some(px) = order.stop_price {
312        report.trigger_price = Some(Price::from_decimal_dp(px, price_precision)?);
313        report.trigger_type = Some(order.trigger_signal.as_deref().map_or(
314            TriggerType::Default,
315            |s| match s {
316                "mark" | "mark_price" => TriggerType::MarkPrice,
317                "spot" | "spot_price" | "index" | "index_price" => TriggerType::IndexPrice,
318                _ => TriggerType::LastPrice,
319            },
320        ));
321    }
322
323    if let Some(reason) = reason
324        && !reason.is_empty()
325    {
326        report.cancel_reason = Some(reason.to_string());
327    }
328
329    Ok(report)
330}
331
332pub fn parse_futures_ws_fill_report(
333    fill: &KrakenFuturesFill,
334    instrument: &InstrumentAny,
335    account_id: AccountId,
336    ts_init: UnixNanos,
337) -> anyhow::Result<FillReport> {
338    let price_precision = instrument.price_precision();
339    let size_precision = instrument.size_precision();
340
341    let venue_order_id = parse_venue_order_id(
342        &fill.order_id,
343        format_args!("futures fill {}", fill.fill_id),
344    )?;
345    let trade_id = TradeId::new(&fill.fill_id);
346    let order_side = if fill.buy {
347        OrderSide::Buy
348    } else {
349        OrderSide::Sell
350    };
351
352    let last_qty =
353        Quantity::from_decimal_dp(fill.qty, size_precision).context("Failed to parse fill qty")?;
354    let last_px = Price::from_decimal_dp(fill.price, price_precision)
355        .context("Failed to parse fill price")?;
356
357    let liquidity_side = fill.fill_type.into();
358
359    let fee = fill.fee_paid.unwrap_or(Decimal::ZERO);
360    // The venue reports the fee currency, which on an inverse contract is not the quote.
361    let commission_currency = fill.fee_currency.as_deref().map_or_else(
362        || instrument.quote_currency(),
363        |reported| fee_currency(reported, instrument),
364    );
365    let commission = Money::from_decimal(fee, commission_currency)?;
366
367    let ts_event = millis_to_nanos(fill.time);
368
369    let client_order_id = fill
370        .cli_ord_id
371        .as_ref()
372        .filter(|s| !s.is_empty())
373        .map(ClientOrderId::new);
374
375    Ok(FillReport::new(
376        account_id,
377        instrument.id(),
378        venue_order_id,
379        trade_id,
380        order_side,
381        last_qty,
382        last_px,
383        commission,
384        liquidity_side,
385        client_order_id,
386        None, // venue_position_id
387        ts_event,
388        ts_init,
389        None, // report_id
390    ))
391}
392
393pub fn parse_futures_ws_mark_price(
394    ticker: &KrakenFuturesTickerData,
395    instrument: &InstrumentAny,
396    ts_init: UnixNanos,
397) -> Option<MarkPriceUpdate> {
398    let mark_price = ticker.mark_price?;
399    let price = Price::from_decimal_dp(mark_price, instrument.price_precision()).ok()?;
400    let ts_event = ticker.time.map_or(ts_init, millis_to_nanos);
401    Some(MarkPriceUpdate::new(
402        instrument.id(),
403        price,
404        ts_event,
405        ts_init,
406    ))
407}
408
409pub fn parse_futures_ws_index_price(
410    ticker: &KrakenFuturesTickerData,
411    instrument: &InstrumentAny,
412    ts_init: UnixNanos,
413) -> Option<IndexPriceUpdate> {
414    let index = ticker.index?;
415    let price = Price::from_decimal_dp(index, instrument.price_precision()).ok()?;
416    let ts_event = ticker.time.map_or(ts_init, millis_to_nanos);
417    Some(IndexPriceUpdate::new(
418        instrument.id(),
419        price,
420        ts_event,
421        ts_init,
422    ))
423}
424
425pub fn parse_futures_ws_funding_rate(
426    ticker: &KrakenFuturesTickerData,
427    instrument: &InstrumentAny,
428    ts_init: UnixNanos,
429) -> Option<FundingRateUpdate> {
430    let rate = ticker.relative_funding_rate?;
431    let ts_event = ticker.time.map_or(ts_init, millis_to_nanos);
432    let next_funding_ns = ticker
433        .next_funding_rate_time
434        .map(|t| millis_to_nanos(t as i64));
435    Some(FundingRateUpdate::new(
436        instrument.id(),
437        rate,
438        None,
439        next_funding_ns,
440        ts_event,
441        ts_init,
442    ))
443}
444
445#[cfg(test)]
446mod tests {
447    use nautilus_model::{
448        enums::{CurrencyType, LiquiditySide, OrderSide, TimeInForce},
449        identifiers::{InstrumentId, Symbol},
450        instruments::crypto_perpetual::CryptoPerpetual,
451        types::Currency,
452    };
453    use rstest::rstest;
454    use rust_decimal_macros::dec;
455
456    use super::*;
457    use crate::common::{
458        consts::KRAKEN_VENUE,
459        enums::{KrakenFillType, KrakenFuturesOrderType},
460    };
461
462    const TS: UnixNanos = UnixNanos::new(1_700_000_000_000_000_000);
463
464    fn create_mock_perp() -> InstrumentAny {
465        let instrument_id = InstrumentId::new(Symbol::new("PI_XBTUSD"), *KRAKEN_VENUE);
466        InstrumentAny::CryptoPerpetual(
467            CryptoPerpetual::builder()
468                .instrument_id(instrument_id)
469                .raw_symbol(Symbol::new("PI_XBTUSD"))
470                .base_currency(Currency::BTC())
471                .quote_currency(Currency::USD())
472                .settlement_currency(Currency::USD())
473                .is_inverse(false)
474                .price_precision(1)
475                .size_precision(0)
476                .price_increment(Price::from("0.5"))
477                .size_increment(Quantity::from("1"))
478                .ts_event(TS)
479                .ts_init(TS)
480                .build()
481                .unwrap(),
482        )
483    }
484
485    #[rstest]
486    fn test_parse_futures_ws_quote_tick() {
487        let json = include_str!("../../../test_data/ws_futures_ticker.json");
488        let ticker: KrakenFuturesTickerData = serde_json::from_str(json).unwrap();
489        let instrument = create_mock_perp();
490
491        let quote = parse_futures_ws_quote_tick(&ticker, &instrument, TS).unwrap();
492
493        assert_eq!(quote.instrument_id, instrument.id());
494        assert_eq!(quote.bid_price, Price::from("21978.5"));
495        assert_eq!(quote.ask_price, Price::from("21987.0"));
496        assert_eq!(quote.bid_size, Quantity::from("2536.0"));
497        assert_eq!(quote.ask_size, Quantity::from("13948.0"));
498    }
499
500    #[rstest]
501    fn test_parse_futures_ws_trade_tick() {
502        let json = include_str!("../../../test_data/ws_futures_trade.json");
503        let trade: KrakenFuturesTradeData = serde_json::from_str(json).unwrap();
504        let instrument = create_mock_perp();
505
506        let tick = parse_futures_ws_trade_tick(&trade, &instrument, TS).unwrap();
507
508        assert_eq!(tick.instrument_id, instrument.id());
509        assert_eq!(tick.price, Price::from("34969.5"));
510        assert_eq!(tick.size, Quantity::from("15000.0"));
511        assert_eq!(tick.aggressor_side, AggressorSide::Sell);
512    }
513
514    #[rstest]
515    fn test_parse_futures_ws_book_snapshot() {
516        let json = include_str!("../../../test_data/ws_futures_book_snapshot.json");
517        let snapshot: KrakenFuturesBookSnapshot = serde_json::from_str(json).unwrap();
518        let instrument = create_mock_perp();
519
520        let deltas = parse_futures_ws_book_snapshot_deltas(&snapshot, &instrument, 0, TS).unwrap();
521
522        // CLEAR + 2 bids + 2 asks = 5
523        assert_eq!(deltas.len(), 5);
524        assert_eq!(deltas[0].action, BookAction::Clear);
525        assert_eq!(deltas[1].action, BookAction::Add);
526        assert_eq!(deltas[1].order.side, OrderSide::Buy.into());
527        assert_eq!(deltas[3].order.side, OrderSide::Sell.into());
528    }
529
530    #[rstest]
531    fn test_parse_futures_ws_book_snapshot_skips_zero_qty() {
532        let json = include_str!("../../../test_data/ws_futures_book_snapshot_with_zero_qty.json");
533        let snapshot: KrakenFuturesBookSnapshot = serde_json::from_str(json).unwrap();
534        let instrument = create_mock_perp();
535
536        let deltas = parse_futures_ws_book_snapshot_deltas(&snapshot, &instrument, 0, TS).unwrap();
537
538        // CLEAR + 2 bids (skipped qty=0) + 1 ask (skipped qty=0) = 4
539        assert_eq!(deltas.len(), 4);
540        assert_eq!(deltas[0].action, BookAction::Clear);
541        assert_eq!(deltas[1].order.side, OrderSide::Buy.into());
542        assert_eq!(deltas[1].order.price, Price::from("34892.5"));
543        assert_eq!(deltas[2].order.side, OrderSide::Buy.into());
544        assert_eq!(deltas[2].order.price, Price::from("34891.5"));
545        assert_eq!(deltas[3].order.side, OrderSide::Sell.into());
546        assert_eq!(deltas[3].order.price, Price::from("34912.0"));
547    }
548
549    #[rstest]
550    fn test_parse_futures_ws_book_delta() {
551        let json = include_str!("../../../test_data/ws_futures_book_delta.json");
552        let delta_msg: KrakenFuturesBookDelta = serde_json::from_str(json).unwrap();
553        let instrument = create_mock_perp();
554
555        let delta = parse_futures_ws_book_delta(&delta_msg, &instrument, 10, TS).unwrap();
556
557        assert_eq!(delta.instrument_id, instrument.id());
558        assert_eq!(delta.order.side, OrderSide::Sell.into());
559        assert_eq!(delta.action, BookAction::Delete); // qty=0
560        assert_eq!(delta.sequence, 10);
561    }
562
563    #[rstest]
564    fn test_parse_futures_ws_order_status_report_new_order() {
565        let order = KrakenFuturesOpenOrder {
566            instrument: ustr::Ustr::from("PI_XBTUSD"),
567            time: 1700000000000,
568            last_update_time: 1700000000100,
569            qty: dec!(1000),
570            filled: Decimal::ZERO,
571            limit_price: Some(dec!(35000)),
572            stop_price: None,
573            order_type: KrakenFuturesOrderType::Limit,
574            order_id: "abc-123".to_string(),
575            cli_ord_id: Some("my-order-1".to_string()),
576            direction: 0,
577            reduce_only: false,
578            trigger_signal: None,
579        };
580        let instrument = create_mock_perp();
581        let account_id = AccountId::from("KRAKEN-001");
582
583        let report =
584            parse_futures_ws_order_status_report(&order, false, None, &instrument, account_id, TS)
585                .unwrap();
586
587        assert_eq!(report.order_status, OrderStatus::Accepted);
588        assert_eq!(report.order_side, OrderSide::Buy.into());
589        assert_eq!(report.order_type, OrderType::Limit);
590        assert_eq!(report.quantity.as_decimal(), dec!(1000));
591        assert_eq!(report.filled_qty.as_decimal(), Decimal::ZERO);
592        assert_eq!(report.price.unwrap().as_decimal(), dec!(35000));
593    }
594
595    #[rstest]
596    fn test_parse_futures_ws_order_status_report_fails_on_an_invalid_order_id() {
597        let order = KrakenFuturesOpenOrder {
598            instrument: ustr::Ustr::from("PI_XBTUSD"),
599            time: 1700000000000,
600            last_update_time: 1700000000100,
601            qty: dec!(1000),
602            filled: Decimal::ZERO,
603            limit_price: Some(dec!(35000)),
604            stop_price: None,
605            order_type: KrakenFuturesOrderType::Limit,
606            order_id: String::new(),
607            cli_ord_id: None,
608            direction: 0,
609            reduce_only: false,
610            trigger_signal: None,
611        };
612
613        let error = parse_futures_ws_order_status_report(
614            &order,
615            false,
616            None,
617            &create_mock_perp(),
618            AccountId::from("KRAKEN-001"),
619            TS,
620        )
621        .unwrap_err();
622
623        assert_eq!(
624            error.to_string(),
625            "Invalid order_id '' in Kraken futures order delta"
626        );
627    }
628
629    /// The dispatch logs only this message for the fill it drops, so the message names the fill.
630    #[rstest]
631    fn test_parse_futures_ws_fill_report_names_the_fill_of_an_invalid_order_id() {
632        let json = include_str!("../../../test_data/ws_futures_fills_delta.json");
633        let fills_delta: super::super::messages::KrakenFuturesFillsDelta =
634            serde_json::from_str(json).unwrap();
635        let mut fill = fills_delta.fills[0].clone();
636        fill.order_id = String::new();
637
638        let error = parse_futures_ws_fill_report(
639            &fill,
640            &create_mock_perp(),
641            AccountId::from("KRAKEN-001"),
642            TS,
643        )
644        .unwrap_err();
645
646        assert_eq!(
647            error.to_string(),
648            format!(
649                "Invalid order_id '' in Kraken futures fill {}",
650                fill.fill_id
651            )
652        );
653    }
654
655    #[rstest]
656    fn test_parse_futures_ws_order_status_report_canceled() {
657        let order = KrakenFuturesOpenOrder {
658            instrument: ustr::Ustr::from("PI_XBTUSD"),
659            time: 1700000000000,
660            last_update_time: 1700000001000,
661            qty: dec!(1000),
662            filled: Decimal::ZERO,
663            limit_price: Some(dec!(35000)),
664            stop_price: None,
665            order_type: KrakenFuturesOrderType::Limit,
666            order_id: "abc-123".to_string(),
667            cli_ord_id: None,
668            direction: 1,
669            reduce_only: false,
670            trigger_signal: None,
671        };
672        let instrument = create_mock_perp();
673        let account_id = AccountId::from("KRAKEN-001");
674
675        let report = parse_futures_ws_order_status_report(
676            &order,
677            true,
678            Some("cancelled_by_user"),
679            &instrument,
680            account_id,
681            TS,
682        )
683        .unwrap();
684
685        assert_eq!(report.order_status, OrderStatus::Canceled);
686        assert_eq!(report.order_side, OrderSide::Sell.into());
687        assert_eq!(report.cancel_reason.as_deref(), Some("cancelled_by_user"));
688    }
689
690    /// The `ioc` and `post` types reach the report as `IOC` and post-only `GTC`, and any other type
691    /// stays `GTC` and not post-only.
692    #[rstest]
693    #[case::limit(KrakenFuturesOrderType::Limit, TimeInForce::Gtc, false)]
694    #[case::ioc(KrakenFuturesOrderType::Ioc, TimeInForce::Ioc, false)]
695    #[case::post(KrakenFuturesOrderType::Post, TimeInForce::Gtc, true)]
696    #[case::stop(KrakenFuturesOrderType::StopLower, TimeInForce::Gtc, false)]
697    #[case::take_profit(KrakenFuturesOrderType::TakeProfit, TimeInForce::Gtc, false)]
698    fn test_parse_futures_ws_order_status_report_time_in_force(
699        #[case] order_type: KrakenFuturesOrderType,
700        #[case] time_in_force: TimeInForce,
701        #[case] post_only: bool,
702    ) {
703        let order = KrakenFuturesOpenOrder {
704            instrument: ustr::Ustr::from("PI_XBTUSD"),
705            time: 1700000000000,
706            last_update_time: 1700000000100,
707            qty: dec!(1000),
708            filled: Decimal::ZERO,
709            limit_price: Some(dec!(35000)),
710            stop_price: None,
711            order_type,
712            order_id: "abc-123".to_string(),
713            cli_ord_id: None,
714            direction: 0,
715            reduce_only: false,
716            trigger_signal: None,
717        };
718
719        let report = parse_futures_ws_order_status_report(
720            &order,
721            false,
722            None,
723            &create_mock_perp(),
724            AccountId::from("KRAKEN-001"),
725            TS,
726        )
727        .unwrap();
728
729        assert_eq!(report.time_in_force, time_in_force);
730        assert_eq!(report.post_only, post_only);
731    }
732
733    #[rstest]
734    fn test_parse_futures_ws_order_status_report_market_if_touched() {
735        let order = KrakenFuturesOpenOrder {
736            instrument: ustr::Ustr::from("PI_XBTUSD"),
737            time: 1700000000000,
738            last_update_time: 1700000000100,
739            qty: dec!(500),
740            filled: Decimal::ZERO,
741            limit_price: None,
742            stop_price: Some(dec!(36000)),
743            order_type: KrakenFuturesOrderType::TakeProfit,
744            order_id: "tp-001".to_string(),
745            cli_ord_id: Some("my-tp-1".to_string()),
746            direction: 0,
747            reduce_only: true,
748            trigger_signal: None,
749        };
750        let instrument = create_mock_perp();
751        let account_id = AccountId::from("KRAKEN-001");
752
753        let report =
754            parse_futures_ws_order_status_report(&order, false, None, &instrument, account_id, TS)
755                .unwrap();
756
757        assert_eq!(report.order_type, OrderType::MarketIfTouched);
758        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(36000));
759        assert!(report.price.is_none());
760        assert!(report.reduce_only);
761    }
762
763    #[rstest]
764    fn test_parse_futures_ws_order_status_report_limit_if_touched() {
765        let order = KrakenFuturesOpenOrder {
766            instrument: ustr::Ustr::from("PI_XBTUSD"),
767            time: 1700000000000,
768            last_update_time: 1700000000100,
769            qty: dec!(500),
770            filled: Decimal::ZERO,
771            limit_price: Some(dec!(35500)),
772            stop_price: Some(dec!(36000)),
773            order_type: KrakenFuturesOrderType::TakeProfit,
774            order_id: "tpl-001".to_string(),
775            cli_ord_id: Some("my-tpl-1".to_string()),
776            direction: 1,
777            reduce_only: false,
778            trigger_signal: None,
779        };
780        let instrument = create_mock_perp();
781        let account_id = AccountId::from("KRAKEN-001");
782
783        let report =
784            parse_futures_ws_order_status_report(&order, false, None, &instrument, account_id, TS)
785                .unwrap();
786
787        assert_eq!(report.order_type, OrderType::LimitIfTouched);
788        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(36000));
789        assert_eq!(report.price.unwrap().as_decimal(), dec!(35500));
790        assert_eq!(report.order_side, OrderSide::Sell.into());
791    }
792
793    #[rstest]
794    fn test_parse_futures_ws_order_status_report_spot_trigger_signal() {
795        let order = KrakenFuturesOpenOrder {
796            instrument: ustr::Ustr::from("PI_XBTUSD"),
797            time: 1700000000000,
798            last_update_time: 1700000000100,
799            qty: dec!(500),
800            filled: Decimal::ZERO,
801            limit_price: None,
802            stop_price: Some(dec!(36000)),
803            order_type: KrakenFuturesOrderType::TakeProfit,
804            order_id: "tp-spot-001".to_string(),
805            cli_ord_id: Some("my-tp-spot-1".to_string()),
806            direction: 0,
807            reduce_only: false,
808            trigger_signal: Some("spot".to_string()),
809        };
810        let instrument = create_mock_perp();
811        let account_id = AccountId::from("KRAKEN-001");
812
813        let report =
814            parse_futures_ws_order_status_report(&order, false, None, &instrument, account_id, TS)
815                .unwrap();
816
817        assert_eq!(report.trigger_type, Some(TriggerType::IndexPrice));
818    }
819
820    #[rstest]
821    #[case::taker(KrakenFillType::Taker, LiquiditySide::Taker)]
822    #[case::assignee(KrakenFillType::Assignee, LiquiditySide::NoLiquiditySide)]
823    fn test_parse_futures_ws_fill_report(
824        #[case] fill_type: KrakenFillType,
825        #[case] expected_liquidity_side: LiquiditySide,
826    ) {
827        let json = include_str!("../../../test_data/ws_futures_fills_delta.json");
828        let fills_delta: super::super::messages::KrakenFuturesFillsDelta =
829            serde_json::from_str(json).unwrap();
830        let mut fill = fills_delta.fills[0].clone();
831        fill.fill_type = fill_type;
832
833        let instrument_id = InstrumentId::new(Symbol::new("PF_ETHUSD"), *KRAKEN_VENUE);
834        let usd = Currency::new("USD", 6, 0, "USD", CurrencyType::Fiat);
835        let instrument = InstrumentAny::CryptoPerpetual(
836            CryptoPerpetual::builder()
837                .instrument_id(instrument_id)
838                .raw_symbol(Symbol::new("PF_ETHUSD"))
839                .base_currency(Currency::ETH())
840                .quote_currency(usd)
841                .settlement_currency(usd)
842                .is_inverse(false)
843                .price_precision(1)
844                .size_precision(3)
845                .price_increment(Price::from("0.5"))
846                .size_increment(Quantity::from("0.001"))
847                .ts_event(TS)
848                .ts_init(TS)
849                .build()
850                .unwrap(),
851        );
852
853        let account_id = AccountId::from("KRAKEN-001");
854        let report = parse_futures_ws_fill_report(&fill, &instrument, account_id, TS).unwrap();
855
856        assert_eq!(report.instrument_id, instrument_id);
857        assert_eq!(report.order_side, OrderSide::Buy);
858        assert_eq!(report.last_px.as_decimal(), dec!(3162));
859        assert_eq!(report.last_qty.as_decimal(), dec!(0.001));
860        assert_eq!(report.liquidity_side, expected_liquidity_side);
861        assert_eq!(report.commission.as_decimal(), dec!(0.001581));
862        // The fixture reports the quote currency, so the commission stays in it.
863        assert_eq!(report.commission.currency.code, "USD");
864    }
865
866    /// A fee the venue reports in something other than the quote must be booked in that currency.
867    ///
868    /// An inverse contract charges in the base currency, so assuming the quote would record the
869    /// wrong currency against the amount.
870    #[rstest]
871    fn test_parse_futures_ws_fill_report_honors_the_reported_fee_currency() {
872        let json = include_str!("../../../test_data/ws_futures_fills_delta.json");
873        let fills_delta: super::super::messages::KrakenFuturesFillsDelta =
874            serde_json::from_str(json).unwrap();
875        let mut fill = fills_delta.fills[0].clone();
876        fill.fee_currency = Some("XXBT".to_string());
877
878        let instrument_id = InstrumentId::new(Symbol::new("PI_XBTUSD"), *KRAKEN_VENUE);
879        let usd = Currency::new("USD", 6, 0, "USD", CurrencyType::Fiat);
880        let instrument = InstrumentAny::CryptoPerpetual(
881            CryptoPerpetual::builder()
882                .instrument_id(instrument_id)
883                .raw_symbol(Symbol::new("PI_XBTUSD"))
884                .base_currency(Currency::BTC())
885                .quote_currency(usd)
886                .settlement_currency(Currency::BTC())
887                .is_inverse(true)
888                .price_precision(1)
889                .size_precision(3)
890                .price_increment(Price::from("0.5"))
891                .size_increment(Quantity::from("0.001"))
892                .ts_event(TS)
893                .ts_init(TS)
894                .build()
895                .unwrap(),
896        );
897
898        let report =
899            parse_futures_ws_fill_report(&fill, &instrument, AccountId::from("KRAKEN-001"), TS)
900                .unwrap();
901
902        // `XXBT` is Kraken's spelling; the report carries the standard code.
903        assert_eq!(report.commission.currency.code, "BTC");
904        assert_eq!(report.commission.as_decimal(), dec!(0.001581));
905    }
906}