Skip to main content

nautilus_kraken/websocket/spot_v2/
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 streaming data to Nautilus domain models.
17
18use anyhow::Context;
19use jiff::Timestamp;
20use nautilus_core::{UUID4, nanos::UnixNanos};
21use nautilus_model::{
22    data::{Bar, BarSpecification, BarType, BookOrder, OrderBookDelta, QuoteTick, TradeTick},
23    enums::{
24        AggregationSource, AggressorSide, BarAggregation, BookAction, LiquiditySide, OrderSide,
25        OrderStatus, OrderType, PriceType, RecordFlag, TimeInForce, TriggerType,
26    },
27    identifiers::{AccountId, ClientOrderId, InstrumentId, TradeId},
28    instruments::{Instrument, any::InstrumentAny},
29    reports::{FillReport, OrderStatusReport},
30    types::{Money, Price, Quantity},
31};
32use rust_decimal::Decimal;
33
34use super::{
35    enums::{KrakenExecType, KrakenLiquidityInd, KrakenWsOrderStatus},
36    messages::{
37        KrakenSpotWsMessage, KrakenWsBookData, KrakenWsBookLevel, KrakenWsExecutionData,
38        KrakenWsOhlcData, KrakenWsOrderResponse, KrakenWsTickerData, KrakenWsTradeData,
39    },
40};
41use crate::common::{
42    enums::{KrakenOrderSide, KrakenOrderType, KrakenTimeInForce},
43    parse::{get_currency, parse_venue_order_id},
44};
45
46/// Parses Kraken WebSocket ticker data into a Nautilus quote tick.
47///
48/// # Errors
49///
50/// Returns an error if:
51/// - Bid or ask price/quantity cannot be parsed.
52pub fn parse_quote_tick(
53    ticker: &KrakenWsTickerData,
54    instrument: &InstrumentAny,
55    ts_init: UnixNanos,
56) -> anyhow::Result<QuoteTick> {
57    let instrument_id = instrument.id();
58    let price_precision = instrument.price_precision();
59    let size_precision = instrument.size_precision();
60
61    let bid_price = Price::from_decimal_dp(ticker.bid, price_precision).with_context(|| {
62        format!("Failed to construct bid Price with precision {price_precision}")
63    })?;
64    let bid_size =
65        Quantity::from_decimal_dp(ticker.bid_qty, size_precision).with_context(|| {
66            format!("Failed to construct bid Quantity with precision {size_precision}")
67        })?;
68
69    let ask_price = Price::from_decimal_dp(ticker.ask, price_precision).with_context(|| {
70        format!("Failed to construct ask Price with precision {price_precision}")
71    })?;
72    let ask_size =
73        Quantity::from_decimal_dp(ticker.ask_qty, size_precision).with_context(|| {
74            format!("Failed to construct ask Quantity with precision {size_precision}")
75        })?;
76
77    let ts_event = datetime_to_nanos(ticker.timestamp, "ticker.timestamp")?;
78
79    Ok(QuoteTick::new(
80        instrument_id,
81        bid_price,
82        ask_price,
83        bid_size,
84        ask_size,
85        ts_event,
86        ts_init,
87    ))
88}
89
90/// Parses Kraken WebSocket trade data into a Nautilus trade tick.
91///
92/// # Errors
93///
94/// Returns an error if:
95/// - Price or quantity cannot be parsed.
96/// - Timestamp is invalid.
97pub fn parse_trade_tick(
98    trade: &KrakenWsTradeData,
99    instrument: &InstrumentAny,
100    ts_init: UnixNanos,
101) -> anyhow::Result<TradeTick> {
102    let instrument_id = instrument.id();
103    let price_precision = instrument.price_precision();
104    let size_precision = instrument.size_precision();
105
106    let price = Price::from_decimal_dp(trade.price, price_precision)
107        .with_context(|| format!("Failed to construct Price with precision {price_precision}"))?;
108    let size = Quantity::from_decimal_dp(trade.qty, size_precision)
109        .with_context(|| format!("Failed to construct Quantity with precision {size_precision}"))?;
110
111    let aggressor = match trade.side {
112        KrakenOrderSide::Buy => AggressorSide::Buy,
113        KrakenOrderSide::Sell => AggressorSide::Sell,
114    };
115
116    let trade_id = TradeId::new_checked(trade.trade_id.to_string())?;
117    let ts_event = datetime_to_nanos(trade.timestamp, "trade.timestamp")?;
118
119    TradeTick::new_checked(
120        instrument_id,
121        price,
122        size,
123        aggressor,
124        trade_id,
125        ts_event,
126        ts_init,
127    )
128    .context("Failed to construct TradeTick from Kraken WebSocket trade")
129}
130
131/// Parses Kraken WebSocket book data into Nautilus order book deltas.
132///
133/// Returns a vector of deltas, one for each bid and ask level.
134///
135/// # Errors
136///
137/// Returns an error if:
138/// - Price or quantity cannot be parsed.
139/// - Timestamp is invalid.
140pub fn parse_book_deltas(
141    book: &KrakenWsBookData,
142    instrument: &InstrumentAny,
143    sequence: u64,
144    is_snapshot: bool,
145    ts_init: UnixNanos,
146) -> anyhow::Result<Vec<OrderBookDelta>> {
147    let instrument_id = instrument.id();
148    let price_precision = instrument.price_precision();
149    let size_precision = instrument.size_precision();
150
151    let ts_event = datetime_to_nanos(book.timestamp, "book.timestamp")?;
152
153    let mut current_sequence = sequence;
154    let mut deltas = Vec::new();
155
156    if is_snapshot {
157        deltas.push(OrderBookDelta::clear(
158            instrument_id,
159            current_sequence,
160            ts_event,
161            ts_init,
162        ));
163        current_sequence += 1;
164    }
165
166    if let Some(ref bids) = book.bids {
167        parse_book_side_levels(
168            bids,
169            OrderSide::Buy,
170            is_snapshot,
171            instrument_id,
172            price_precision,
173            size_precision,
174            ts_event,
175            ts_init,
176            &mut current_sequence,
177            &mut deltas,
178        )?;
179    }
180
181    if let Some(ref asks) = book.asks {
182        parse_book_side_levels(
183            asks,
184            OrderSide::Sell,
185            is_snapshot,
186            instrument_id,
187            price_precision,
188            size_precision,
189            ts_event,
190            ts_init,
191            &mut current_sequence,
192            &mut deltas,
193        )?;
194    }
195
196    if let Some(last) = deltas.last_mut() {
197        last.flags |= RecordFlag::F_LAST as u8;
198    }
199
200    Ok(deltas)
201}
202
203#[expect(clippy::too_many_arguments)]
204fn parse_book_side_levels(
205    levels: &[KrakenWsBookLevel],
206    side: OrderSide,
207    is_snapshot: bool,
208    instrument_id: InstrumentId,
209    price_precision: u8,
210    size_precision: u8,
211    ts_event: UnixNanos,
212    ts_init: UnixNanos,
213    current_sequence: &mut u64,
214    deltas: &mut Vec<OrderBookDelta>,
215) -> anyhow::Result<()> {
216    for level in levels {
217        let Some(delta) = parse_book_level(
218            level,
219            side,
220            is_snapshot,
221            instrument_id,
222            price_precision,
223            size_precision,
224            *current_sequence,
225            ts_event,
226            ts_init,
227        )?
228        else {
229            continue;
230        };
231        deltas.push(delta);
232        *current_sequence += 1;
233    }
234
235    Ok(())
236}
237
238#[expect(clippy::too_many_arguments)]
239fn parse_book_level(
240    level: &KrakenWsBookLevel,
241    side: OrderSide,
242    is_snapshot: bool,
243    instrument_id: InstrumentId,
244    price_precision: u8,
245    size_precision: u8,
246    sequence: u64,
247    ts_event: UnixNanos,
248    ts_init: UnixNanos,
249) -> anyhow::Result<Option<OrderBookDelta>> {
250    let price = Price::from_decimal_dp(level.price, price_precision)
251        .with_context(|| format!("Failed to construct Price with precision {price_precision}"))?;
252    let size = Quantity::from_decimal_dp(level.qty, size_precision)
253        .with_context(|| format!("Failed to construct Quantity with precision {size_precision}"))?;
254
255    let action = if is_snapshot {
256        if size.is_zero() {
257            return Ok(None);
258        }
259        BookAction::Add
260    } else if size.is_zero() {
261        BookAction::Delete
262    } else {
263        BookAction::Update
264    };
265
266    let order_id = price.raw() as u64;
267
268    let order = BookOrder::new(side, price, size, order_id);
269    let mut flags = RecordFlag::F_MBP as u8;
270    if is_snapshot {
271        flags |= RecordFlag::F_SNAPSHOT as u8;
272    }
273
274    Ok(Some(OrderBookDelta::new(
275        instrument_id,
276        action,
277        order,
278        flags,
279        sequence,
280        ts_event,
281        ts_init,
282    )))
283}
284
285pub(super) fn datetime_to_nanos(value: Timestamp, field: &str) -> anyhow::Result<UnixNanos> {
286    let nanos = u64::try_from(value.as_nanosecond())
287        .with_context(|| format!("Timestamp predates Unix epoch: {field}='{value}'"))?;
288    Ok(UnixNanos::from(nanos))
289}
290
291/// Parses Kraken WebSocket OHLC data into a Nautilus bar.
292///
293/// The bar's `ts_event` is computed as `interval_begin` + `interval` minutes.
294///
295/// # Errors
296///
297/// Returns an error if:
298/// - Price or quantity values cannot be parsed.
299/// - The interval cannot be converted to a valid bar specification.
300pub fn parse_ws_bar(
301    ohlc: &KrakenWsOhlcData,
302    instrument: &InstrumentAny,
303    ts_init: UnixNanos,
304) -> anyhow::Result<Bar> {
305    let instrument_id = instrument.id();
306    let price_precision = instrument.price_precision();
307    let size_precision = instrument.size_precision();
308
309    let open = Price::from_decimal_dp(ohlc.open, price_precision)?;
310    let high = Price::from_decimal_dp(ohlc.high, price_precision)?;
311    let low = Price::from_decimal_dp(ohlc.low, price_precision)?;
312    let close = Price::from_decimal_dp(ohlc.close, price_precision)?;
313    let volume = Quantity::from_decimal_dp(ohlc.volume, size_precision)?;
314
315    let bar_spec = interval_to_bar_spec(ohlc.interval)?;
316    let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::External);
317
318    // Compute bar close time: interval_begin + interval minutes
319    let interval_secs = i64::from(ohlc.interval) * 60;
320    let close_time = ohlc.interval_begin + jiff::SignedDuration::from_secs(interval_secs);
321    let ts_event = UnixNanos::from(u64::try_from(close_time.as_nanosecond()).unwrap_or(0));
322
323    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
324}
325
326/// Converts a Kraken OHLC interval (minutes) to a Nautilus bar specification.
327fn interval_to_bar_spec(interval: u32) -> anyhow::Result<BarSpecification> {
328    let (step, aggregation) = match interval {
329        1 => (1, BarAggregation::Minute),
330        5 => (5, BarAggregation::Minute),
331        15 => (15, BarAggregation::Minute),
332        30 => (30, BarAggregation::Minute),
333        60 => (1, BarAggregation::Hour),
334        240 => (4, BarAggregation::Hour),
335        1440 => (1, BarAggregation::Day),
336        10080 => (1, BarAggregation::Week),
337        21600 => (15, BarAggregation::Day), // 21600 min = 360 hours = 15 days
338        _ => anyhow::bail!("Unsupported Kraken OHLC interval: {interval}"),
339    };
340
341    Ok(BarSpecification::new(step, aggregation, PriceType::Last))
342}
343
344/// Parses Kraken execution type and order status to Nautilus order status.
345fn parse_order_status(
346    exec_type: KrakenExecType,
347    order_status: Option<KrakenWsOrderStatus>,
348) -> OrderStatus {
349    match exec_type {
350        KrakenExecType::Canceled => return OrderStatus::Canceled,
351        KrakenExecType::Expired => return OrderStatus::Expired,
352        KrakenExecType::Filled => return OrderStatus::Filled,
353        KrakenExecType::Trade => {
354            return match order_status {
355                Some(KrakenWsOrderStatus::Filled) => OrderStatus::Filled,
356                Some(KrakenWsOrderStatus::PartiallyFilled) | None => OrderStatus::PartiallyFilled,
357                Some(status) => status.into(),
358            };
359        }
360        _ => {}
361    }
362
363    match order_status {
364        Some(status) => status.into(),
365        None => OrderStatus::Accepted,
366    }
367}
368
369/// Parses Kraken order type to Nautilus order type.
370fn parse_order_type(order_type: Option<KrakenOrderType>) -> OrderType {
371    match order_type {
372        Some(KrakenOrderType::Market) => OrderType::Market,
373        Some(KrakenOrderType::Limit) => OrderType::Limit,
374        Some(KrakenOrderType::StopLoss) => OrderType::StopMarket,
375        Some(KrakenOrderType::TakeProfit) => OrderType::MarketIfTouched,
376        Some(KrakenOrderType::StopLossLimit) => OrderType::StopLimit,
377        Some(KrakenOrderType::TakeProfitLimit) => OrderType::LimitIfTouched,
378        // Trailing stops lack offset fields in WS reports, map to non-trailing equivalents
379        Some(KrakenOrderType::TrailingStop) => OrderType::StopMarket,
380        Some(KrakenOrderType::TrailingStopLimit) => OrderType::StopLimit,
381        Some(KrakenOrderType::SettlePosition) => OrderType::Market,
382        None => OrderType::Limit,
383    }
384}
385
386/// Parses Kraken time-in-force to Nautilus time-in-force.
387fn parse_time_in_force(
388    time_in_force: Option<KrakenTimeInForce>,
389    post_only: Option<bool>,
390) -> TimeInForce {
391    // Handle post_only flag
392    if post_only == Some(true) {
393        return TimeInForce::Gtc;
394    }
395
396    match time_in_force {
397        Some(KrakenTimeInForce::GoodTilCancelled) => TimeInForce::Gtc,
398        Some(KrakenTimeInForce::ImmediateOrCancel) => TimeInForce::Ioc,
399        Some(KrakenTimeInForce::GoodTilDate) => TimeInForce::Gtd,
400        Some(KrakenTimeInForce::FillOrKill) => TimeInForce::Fok,
401        None => TimeInForce::Gtc,
402    }
403}
404
405fn parse_liquidity_side(liquidity_ind: Option<KrakenLiquidityInd>) -> LiquiditySide {
406    liquidity_ind.map_or(LiquiditySide::NoLiquiditySide, Into::into)
407}
408
409/// Parses a Kraken WebSocket execution message into an [`OrderStatusReport`].
410///
411/// # Errors
412///
413/// Returns an error if required fields are missing or cannot be parsed.
414pub fn parse_ws_order_status_report(
415    exec: &KrakenWsExecutionData,
416    instrument: &InstrumentAny,
417    account_id: AccountId,
418    cached_order_qty: Option<Decimal>,
419    ts_init: UnixNanos,
420) -> anyhow::Result<OrderStatusReport> {
421    let instrument_id = instrument.id();
422    let venue_order_id = parse_venue_order_id(
423        &exec.order_id,
424        format_args!("execution, cl_ord_id={:?}", exec.cl_ord_id),
425    )?;
426    let order_side = exec.side.map(Into::into);
427    let order_type = parse_order_type(exec.order_type);
428    let time_in_force = parse_time_in_force(exec.time_in_force, exec.post_only);
429    let order_status = parse_order_status(exec.exec_type, exec.order_status);
430
431    let price_precision = instrument.price_precision();
432    let size_precision = instrument.size_precision();
433
434    // Quantity fallback: order_qty -> cached -> cum_qty -> last_qty (for trade snapshots)
435    let last_qty = exec
436        .last_qty
437        .map(|qty| Quantity::from_decimal_dp(qty, size_precision))
438        .transpose()
439        .context("Failed to parse last_qty")?;
440
441    let filled_qty = exec
442        .cum_qty
443        .map(|qty| Quantity::from_decimal_dp(qty, size_precision))
444        .transpose()
445        .context("Failed to parse cum_qty")?
446        .or(last_qty)
447        .unwrap_or_else(|| Quantity::zero(size_precision));
448
449    let quantity = exec
450        .order_qty
451        .or(cached_order_qty)
452        .map(|qty| Quantity::from_decimal_dp(qty, size_precision))
453        .transpose()
454        .context("Failed to parse order_qty")?
455        .unwrap_or(filled_qty);
456
457    let ts_event = datetime_to_nanos(exec.timestamp, "execution.timestamp")?;
458
459    let mut report = OrderStatusReport::new(
460        account_id,
461        instrument_id,
462        None, // client_order_id set below if present
463        venue_order_id,
464        order_side,
465        order_type,
466        time_in_force,
467        order_status,
468        quantity,
469        filled_qty,
470        ts_event,
471        ts_event,
472        ts_init,
473        Some(UUID4::new()),
474    );
475
476    if let Some(ref cl_ord_id) = exec.cl_ord_id
477        && !cl_ord_id.is_empty()
478    {
479        report = report.with_client_order_id(ClientOrderId::new(cl_ord_id));
480    }
481
482    // The order's price is its limit alone: a fill price is `avg_px`, and a frame without the
483    // limit states no price
484    if let Some(px) = exec.limit_price.filter(|p| *p > Decimal::ZERO) {
485        let price =
486            Price::from_decimal_dp(px, price_precision).context("Failed to parse order price")?;
487        report = report.with_price(price);
488    }
489
490    // avg_px fallback: avg_price -> cum_cost / cum_qty -> last_price (for single trades/snapshots)
491    let avg_px = exec
492        .avg_price
493        .filter(|p| *p > Decimal::ZERO)
494        .or_else(|| match (exec.cum_cost, exec.cum_qty) {
495            (Some(cost), Some(qty)) if qty > Decimal::ZERO => Some(cost / qty),
496            _ => None,
497        })
498        .or_else(|| exec.last_price.filter(|p| *p > Decimal::ZERO));
499
500    if let Some(avg_price) = avg_px {
501        report.avg_px = Some(avg_price);
502    }
503
504    if exec.post_only == Some(true) {
505        report = report.with_post_only(true);
506    }
507
508    if exec.reduce_only == Some(true) {
509        report = report.with_reduce_only(true);
510    }
511
512    if let Some(ref reason) = exec.reason
513        && !reason.is_empty()
514    {
515        report = report.with_cancel_reason(reason.clone());
516    }
517
518    // Set trigger type for conditional orders (WebSocket doesn't provide trigger field)
519    let is_conditional = matches!(
520        order_type,
521        OrderType::StopMarket
522            | OrderType::StopLimit
523            | OrderType::MarketIfTouched
524            | OrderType::LimitIfTouched
525    );
526
527    if is_conditional {
528        report = report.with_trigger_type(TriggerType::Default);
529    }
530
531    Ok(report)
532}
533
534/// Parses a Kraken WebSocket trade execution into a [`FillReport`].
535///
536/// This should only be called when exec_type is "trade".
537///
538/// # Errors
539///
540/// Returns an error if required fields are missing or cannot be parsed.
541pub fn parse_ws_fill_report(
542    exec: &KrakenWsExecutionData,
543    instrument: &InstrumentAny,
544    account_id: AccountId,
545    ts_init: UnixNanos,
546) -> anyhow::Result<FillReport> {
547    let instrument_id = instrument.id();
548
549    let exec_id = exec
550        .exec_id
551        .as_ref()
552        .context("Missing exec_id for trade execution")?;
553    let trade_id =
554        TradeId::new_checked(exec_id).context("Invalid exec_id in Kraken trade execution")?;
555    let venue_order_id =
556        parse_venue_order_id(&exec.order_id, format_args!("trade execution {exec_id}"))?;
557
558    let order_side = exec
559        .side
560        .map(Into::into)
561        .context("Missing side for trade execution")?;
562
563    let price_precision = instrument.price_precision();
564    let size_precision = instrument.size_precision();
565
566    let last_qty = exec
567        .last_qty
568        .map(|qty| Quantity::from_decimal_dp(qty, size_precision))
569        .transpose()
570        .context("Failed to parse last_qty")?
571        .context("Missing last_qty for trade execution")?;
572
573    let last_px = exec
574        .last_price
575        .map(|px| Price::from_decimal_dp(px, price_precision))
576        .transpose()
577        .context("Failed to parse last_price")?
578        .context("Missing last_price for trade execution")?;
579
580    let liquidity_side = parse_liquidity_side(exec.liquidity_ind);
581
582    // Calculate commission from fees array
583    let commission = if let Some(ref fees) = exec.fees {
584        if let Some(fee) = fees.first() {
585            let currency = get_currency(&fee.asset);
586            Money::from_decimal(fee.qty.abs(), currency).context("Failed to parse fill fee")?
587        } else {
588            Money::zero(instrument.quote_currency())
589        }
590    } else {
591        Money::zero(instrument.quote_currency())
592    };
593
594    let ts_event = datetime_to_nanos(exec.timestamp, "execution.timestamp")?;
595
596    let client_order_id = exec
597        .cl_ord_id
598        .as_ref()
599        .filter(|s| !s.is_empty())
600        .map(ClientOrderId::new);
601
602    Ok(FillReport::new(
603        account_id,
604        instrument_id,
605        venue_order_id,
606        trade_id,
607        order_side,
608        last_qty,
609        last_px,
610        commission,
611        liquidity_side,
612        client_order_id,
613        None, // venue_position_id
614        ts_event,
615        ts_init,
616        None, // report_id
617    ))
618}
619
620/// Parses a raw WebSocket JSON string and returns [`KrakenSpotWsMessage::OrderResponse`] if the
621/// message is an order-method response envelope, or `Ok(None)` for unrecognized messages.
622///
623/// # Errors
624///
625/// Returns an error if the message appears to be an order response but cannot be deserialized.
626pub fn parse_order_response(text: &str) -> anyhow::Result<Option<KrakenSpotWsMessage>> {
627    let value: serde_json::Value =
628        serde_json::from_str(text).with_context(|| format!("Failed to parse JSON: {text}"))?;
629
630    let method_str = match value.get("method").and_then(|m| m.as_str()) {
631        Some(s) => s.to_owned(),
632        None => return Ok(None),
633    };
634
635    if !matches!(
636        method_str.as_str(),
637        "add_order" | "amend_order" | "cancel_order" | "batch_add"
638    ) {
639        return Ok(None);
640    }
641
642    let response: KrakenWsOrderResponse = serde_json::from_value(value).with_context(|| {
643        format!("Failed to deserialize order response for method '{method_str}'")
644    })?;
645    Ok(Some(KrakenSpotWsMessage::OrderResponse(response)))
646}
647
648#[cfg(test)]
649mod tests {
650    use nautilus_model::{identifiers::Symbol, types::Currency};
651    use rstest::rstest;
652    use rust_decimal_macros::dec;
653    use ustr::Ustr;
654
655    use super::*;
656    use crate::{common::consts::KRAKEN_VENUE, websocket::spot_v2::messages::KrakenWsRawMessage};
657
658    const TS: UnixNanos = UnixNanos::new(1_700_000_000_000_000_000);
659
660    #[rstest]
661    fn test_parse_time_in_force_fok() {
662        assert_eq!(
663            parse_time_in_force(Some(KrakenTimeInForce::FillOrKill), None),
664            TimeInForce::Fok
665        );
666    }
667
668    fn load_test_json(filename: &str) -> String {
669        let path = format!("test_data/{filename}");
670        std::fs::read_to_string(&path)
671            .unwrap_or_else(|e| panic!("Failed to load test data from {path}: {e}"))
672    }
673
674    fn create_mock_instrument() -> InstrumentAny {
675        use nautilus_model::instruments::currency_pair::CurrencyPair;
676
677        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
678        InstrumentAny::CurrencyPair(
679            CurrencyPair::builder()
680                .instrument_id(instrument_id)
681                .raw_symbol(Symbol::new("XBTUSDT"))
682                .base_currency(Currency::BTC())
683                .quote_currency(Currency::USDT())
684                .price_precision(1)
685                .size_precision(8)
686                .price_increment(Price::from("0.1"))
687                .size_increment(Quantity::from("0.00000001"))
688                .ts_event(TS)
689                .ts_init(TS)
690                .build()
691                .unwrap(),
692        )
693    }
694
695    #[rstest]
696    fn test_parse_quote_tick() {
697        let json = load_test_json("ws_ticker_snapshot.json");
698        let message: KrakenWsRawMessage = serde_json::from_str(&json).unwrap();
699        let ticker: KrakenWsTickerData = serde_json::from_str(message.data[0].get()).unwrap();
700
701        let instrument = create_mock_instrument();
702        let quote_tick = parse_quote_tick(&ticker, &instrument, TS).unwrap();
703
704        assert_eq!(quote_tick.instrument_id, instrument.id());
705        assert_eq!(quote_tick.bid_price, Price::from("105944.20"));
706        assert_eq!(quote_tick.ask_price, Price::from("105944.30"));
707        assert_eq!(quote_tick.bid_size, Quantity::from("2.5"));
708        assert_eq!(quote_tick.ask_size, Quantity::from("3.2"));
709        assert_eq!(
710            quote_tick.ts_event,
711            UnixNanos::from(1_671_960_659_123_456_000)
712        );
713        assert_eq!(quote_tick.ts_init, TS);
714    }
715
716    #[rstest]
717    fn test_parse_trade_tick() {
718        let json = load_test_json("ws_trade_update.json");
719        let message: KrakenWsRawMessage = serde_json::from_str(&json).unwrap();
720        let trade: KrakenWsTradeData = serde_json::from_str(message.data[0].get()).unwrap();
721
722        let instrument = create_mock_instrument();
723        let trade_tick = parse_trade_tick(&trade, &instrument, TS).unwrap();
724
725        assert_eq!(trade_tick.instrument_id, instrument.id());
726        assert_eq!(trade_tick.price, Price::from("105944.20"));
727        assert_eq!(trade_tick.size, Quantity::from("0.00027625"));
728        assert!(matches!(
729            trade_tick.aggressor_side,
730            AggressorSide::Buy | AggressorSide::Sell
731        ));
732        assert_eq!(
733            trade_tick.ts_event,
734            UnixNanos::from(1_696_613_755_440_295_000)
735        );
736        assert_eq!(trade_tick.ts_init, TS);
737    }
738
739    #[rstest]
740    fn test_parse_book_deltas_snapshot() {
741        let json = load_test_json("ws_book_snapshot.json");
742        let message: KrakenWsRawMessage = serde_json::from_str(&json).unwrap();
743        let book: KrakenWsBookData = serde_json::from_str(message.data[0].get()).unwrap();
744
745        let instrument = create_mock_instrument();
746        let deltas = parse_book_deltas(&book, &instrument, 1, true, TS).unwrap();
747
748        assert!(!deltas.is_empty());
749
750        let bid_count = deltas
751            .iter()
752            .filter(|d| d.order.side == OrderSide::Buy.into())
753            .count();
754        let ask_count = deltas
755            .iter()
756            .filter(|d| d.order.side == OrderSide::Sell.into())
757            .count();
758
759        assert!(bid_count > 0);
760        assert!(ask_count > 0);
761
762        let first_delta = &deltas[0];
763        assert_eq!(first_delta.instrument_id, instrument.id());
764        assert_eq!(first_delta.action, BookAction::Clear);
765        assert!(RecordFlag::F_SNAPSHOT.matches(first_delta.flags));
766        assert!(!RecordFlag::F_LAST.matches(first_delta.flags));
767
768        assert!(deltas[1..].iter().all(|d| d.action == BookAction::Add));
769        assert!(
770            deltas[1..]
771                .iter()
772                .all(|d| RecordFlag::F_MBP.matches(d.flags))
773        );
774        assert!(
775            deltas[1..]
776                .iter()
777                .all(|d| RecordFlag::F_SNAPSHOT.matches(d.flags))
778        );
779        assert!(RecordFlag::F_LAST.matches(deltas.last().unwrap().flags));
780
781        let expected_ts_event = UnixNanos::from(1_696_613_755_440_295_000);
782        assert!(deltas.iter().all(|d| d.ts_event == expected_ts_event));
783        assert!(deltas.iter().all(|d| d.ts_init == TS));
784    }
785
786    #[rstest]
787    fn test_parse_book_deltas_update() {
788        let json = load_test_json("ws_book_update.json");
789        let message: KrakenWsRawMessage = serde_json::from_str(&json).unwrap();
790        let book: KrakenWsBookData = serde_json::from_str(message.data[0].get()).unwrap();
791
792        let instrument = create_mock_instrument();
793        let deltas = parse_book_deltas(&book, &instrument, 1, false, TS).unwrap();
794
795        assert!(!deltas.is_empty());
796
797        let first_delta = &deltas[0];
798        assert_eq!(first_delta.instrument_id, instrument.id());
799        assert_eq!(first_delta.action, BookAction::Update);
800        assert_eq!(first_delta.order.side, OrderSide::Buy.into());
801        assert_eq!(first_delta.order.price, Price::from("45283.5"));
802        assert!(RecordFlag::F_MBP.matches(first_delta.flags));
803        assert!(RecordFlag::F_LAST.matches(first_delta.flags));
804        assert!(!RecordFlag::F_SNAPSHOT.matches(first_delta.flags));
805
806        let expected_ts_event = UnixNanos::from(1_696_613_755_440_295_000);
807        assert!(deltas.iter().all(|d| d.ts_event == expected_ts_event));
808        assert!(deltas.iter().all(|d| d.ts_init == TS));
809    }
810
811    #[rstest]
812    fn test_parse_book_deltas_snapshot_skips_zero_qty_levels() {
813        let book = KrakenWsBookData {
814            symbol: Ustr::from("BTC/USD"),
815            bids: Some(vec![KrakenWsBookLevel {
816                price: dec!(100),
817                qty: Decimal::ZERO,
818            }]),
819            asks: Some(vec![KrakenWsBookLevel {
820                price: dec!(101),
821                qty: dec!(2),
822            }]),
823            checksum: Some(0),
824            timestamp: "2024-01-01T00:00:00Z".parse().unwrap(),
825        };
826
827        let instrument = create_mock_instrument();
828        let deltas = parse_book_deltas(&book, &instrument, 7, true, TS).unwrap();
829
830        assert_eq!(deltas.len(), 2);
831        assert_eq!(deltas[0].action, BookAction::Clear);
832        assert_eq!(deltas[0].sequence, 7);
833        assert!(RecordFlag::F_SNAPSHOT.matches(deltas[0].flags));
834        assert!(!RecordFlag::F_LAST.matches(deltas[0].flags));
835
836        let add = &deltas[1];
837        assert_eq!(add.action, BookAction::Add);
838        assert_eq!(add.sequence, 8);
839        assert_eq!(add.order.side, OrderSide::Sell.into());
840        assert_eq!(add.order.price, Price::from("101.0"));
841        assert!(RecordFlag::F_MBP.matches(add.flags));
842        assert!(RecordFlag::F_SNAPSHOT.matches(add.flags));
843        assert!(RecordFlag::F_LAST.matches(add.flags));
844    }
845
846    #[rstest]
847    fn test_parse_book_deltas_update_zero_qty_deletes_level() {
848        let book = KrakenWsBookData {
849            symbol: Ustr::from("BTC/USD"),
850            bids: Some(vec![KrakenWsBookLevel {
851                price: dec!(100),
852                qty: Decimal::ZERO,
853            }]),
854            asks: Some(vec![]),
855            checksum: Some(0),
856            timestamp: "2024-01-01T00:00:00Z".parse().unwrap(),
857        };
858
859        let instrument = create_mock_instrument();
860        let deltas = parse_book_deltas(&book, &instrument, 11, false, TS).unwrap();
861
862        assert_eq!(deltas.len(), 1);
863        let delete = &deltas[0];
864        assert_eq!(delete.action, BookAction::Delete);
865        assert_eq!(delete.sequence, 11);
866        assert_eq!(delete.order.side, OrderSide::Buy.into());
867        assert_eq!(delete.order.price, Price::from("100.0"));
868        assert_eq!(delete.order.size.raw(), 0);
869        assert!(RecordFlag::F_MBP.matches(delete.flags));
870        assert!(RecordFlag::F_LAST.matches(delete.flags));
871        assert!(!RecordFlag::F_SNAPSHOT.matches(delete.flags));
872    }
873
874    #[rstest]
875    fn test_parse_ws_order_status_report_preserves_decimal_avg_px() {
876        let execution = ws_execution_data(Some(KrakenOrderSide::Buy));
877
878        let report = parse_ws_order_status_report(
879            &execution,
880            &create_mock_instrument(),
881            AccountId::from("KRAKEN-001"),
882            None,
883            TS,
884        )
885        .unwrap();
886
887        assert_eq!(report.avg_px, Some(dec!(0.1234567890123456789012345678)));
888    }
889
890    #[rstest]
891    fn test_parse_ws_order_status_report_preserves_missing_side() {
892        let execution = ws_execution_data(None);
893
894        let report = parse_ws_order_status_report(
895            &execution,
896            &create_mock_instrument(),
897            AccountId::from("KRAKEN-001"),
898            None,
899            TS,
900        )
901        .unwrap();
902
903        assert_eq!(report.order_side, None);
904    }
905
906    /// A report's price is the order's limit alone, never a fill price. Kraken's executions
907    /// example places a sell limit at 26500.0, then fills part of it at 26599.9 in a trade frame,
908    /// which carries no limit and so states no price.
909    #[rstest]
910    #[case::pending_new_frame("ws_executions_pending_new_doc_example.json", Some("26500.0"), None)]
911    #[case::trade_frame(
912        "ws_executions_trade_doc_example.json",
913        None,
914        Some(dec!(26599.9))
915    )]
916    fn test_parse_ws_order_status_report_prices_the_order_at_its_limit(
917        #[case] filename: &str,
918        #[case] expected_price: Option<&str>,
919        #[case] expected_avg_px: Option<Decimal>,
920    ) {
921        let message: KrakenWsRawMessage = serde_json::from_str(&load_test_json(filename)).unwrap();
922        let execution: KrakenWsExecutionData = serde_json::from_str(message.data[0].get()).unwrap();
923
924        let report = parse_ws_order_status_report(
925            &execution,
926            &create_mock_instrument(),
927            AccountId::from("KRAKEN-001"),
928            None,
929            TS,
930        )
931        .unwrap();
932
933        assert_eq!(report.price, expected_price.map(Price::from));
934        assert_eq!(report.avg_px, expected_avg_px);
935    }
936
937    #[rstest]
938    fn test_parse_ws_order_status_report_fails_on_an_invalid_order_id() {
939        let mut execution = ws_execution_data(Some(KrakenOrderSide::Buy));
940        execution.order_id = String::new();
941        execution.cl_ord_id = Some("cl-1".to_string());
942
943        let error = parse_ws_order_status_report(
944            &execution,
945            &create_mock_instrument(),
946            AccountId::from("KRAKEN-001"),
947            None,
948            TS,
949        )
950        .unwrap_err();
951
952        assert_eq!(
953            error.to_string(),
954            "Invalid order_id '' in Kraken execution, cl_ord_id=Some(\"cl-1\")"
955        );
956    }
957
958    /// The dispatch logs only this message for the fill it drops, so the message names the fill.
959    #[rstest]
960    fn test_parse_ws_fill_report_names_the_execution_of_an_invalid_order_id() {
961        let mut execution = ws_execution_data(Some(KrakenOrderSide::Buy));
962        execution.order_id = String::new();
963        execution.exec_type = KrakenExecType::Trade;
964        execution.exec_id = Some("TRADE-1".to_string());
965        execution.last_qty = Some(dec!(1));
966        execution.last_price = Some(dec!(100));
967
968        let error = parse_ws_fill_report(
969            &execution,
970            &create_mock_instrument(),
971            AccountId::from("KRAKEN-001"),
972            TS,
973        )
974        .unwrap_err();
975
976        assert_eq!(
977            error.to_string(),
978            "Invalid order_id '' in Kraken trade execution TRADE-1"
979        );
980    }
981
982    #[rstest]
983    fn test_parse_ws_fill_report_rejects_missing_side() {
984        let mut execution = ws_execution_data(None);
985        execution.exec_type = KrakenExecType::Trade;
986        execution.exec_id = Some("TRADE-1".to_string());
987        execution.last_qty = Some(dec!(1));
988        execution.last_price = Some(dec!(100));
989
990        let error = parse_ws_fill_report(
991            &execution,
992            &create_mock_instrument(),
993            AccountId::from("KRAKEN-001"),
994            TS,
995        )
996        .expect_err("a trade execution without a side must be rejected");
997
998        assert_eq!(error.to_string(), "Missing side for trade execution");
999    }
1000
1001    fn ws_execution_data(side: Option<KrakenOrderSide>) -> KrakenWsExecutionData {
1002        KrakenWsExecutionData {
1003            exec_type: KrakenExecType::Status,
1004            order_id: "ORDER-1".to_string(),
1005            cl_ord_id: Some("CLIENT-1".to_string()),
1006            symbol: Some("BTC/USD".to_string()),
1007            side,
1008            order_type: Some(KrakenOrderType::Limit),
1009            order_qty: Some(dec!(3)),
1010            limit_price: None,
1011            order_status: Some(KrakenWsOrderStatus::PartiallyFilled),
1012            cum_qty: Some(dec!(3)),
1013            cum_cost: Some(dec!(0.3703703670370370367037037034)),
1014            avg_price: None,
1015            time_in_force: Some(KrakenTimeInForce::GoodTilCancelled),
1016            post_only: Some(false),
1017            reduce_only: Some(false),
1018            timestamp: "2024-01-01T00:00:00Z".parse().unwrap(),
1019            exec_id: None,
1020            last_qty: None,
1021            last_price: None,
1022            cost: None,
1023            liquidity_ind: None,
1024            fees: None,
1025            fee_usd_equiv: None,
1026            reason: None,
1027        }
1028    }
1029
1030    #[rstest]
1031    fn test_datetime_to_nanos() {
1032        let dt = "2023-10-06T17:35:55.440295Z".parse::<Timestamp>().unwrap();
1033        let result = datetime_to_nanos(dt, "test").unwrap();
1034        assert_eq!(result, UnixNanos::from(1_696_613_755_440_295_000));
1035    }
1036
1037    #[rstest]
1038    fn test_datetime_to_nanos_out_of_range_errors() {
1039        let dt = "1500-01-01T00:00:00Z".parse::<Timestamp>().unwrap();
1040        let result = datetime_to_nanos(dt, "test");
1041        assert!(result.is_err());
1042        let err = result.unwrap_err().to_string();
1043        assert!(err.contains("test"));
1044    }
1045
1046    #[rstest]
1047    fn test_parse_ws_bar() {
1048        let json = load_test_json("ws_ohlc_update.json");
1049        let message: KrakenWsRawMessage = serde_json::from_str(&json).unwrap();
1050        let ohlc: KrakenWsOhlcData = serde_json::from_str(message.data[0].get()).unwrap();
1051
1052        let instrument = create_mock_instrument();
1053        let bar = parse_ws_bar(&ohlc, &instrument, TS).unwrap();
1054
1055        assert_eq!(bar.bar_type.instrument_id(), instrument.id());
1056        assert_eq!(bar.open, Price::from("106038.2"));
1057        assert_eq!(bar.high, Price::from("106044.3"));
1058        assert_eq!(bar.low, Price::from("106038.1"));
1059        assert_eq!(bar.close, Price::from("106040.1"));
1060        assert_eq!(bar.volume, Quantity::from("30927.68066226"));
1061
1062        let spec = bar.bar_type.spec();
1063        assert_eq!(spec.step.get(), 1);
1064        assert_eq!(spec.aggregation, BarAggregation::Minute);
1065        assert_eq!(spec.price_type, PriceType::Last);
1066
1067        // Verify ts_event is computed as interval_begin + interval (close time)
1068        // interval_begin is 2023-10-04T16:25:00Z, interval is 1 minute, so close is 16:26:00Z
1069        let expected_close = ohlc.interval_begin + jiff::SignedDuration::from_mins(1);
1070        let expected_ts_event =
1071            UnixNanos::from(u64::try_from(expected_close.as_nanosecond()).unwrap());
1072        assert_eq!(bar.ts_event, expected_ts_event);
1073    }
1074
1075    #[rstest]
1076    fn test_interval_to_bar_spec() {
1077        let test_cases = [
1078            (1, 1, BarAggregation::Minute),
1079            (5, 5, BarAggregation::Minute),
1080            (15, 15, BarAggregation::Minute),
1081            (30, 30, BarAggregation::Minute),
1082            (60, 1, BarAggregation::Hour),
1083            (240, 4, BarAggregation::Hour),
1084            (1440, 1, BarAggregation::Day),
1085            (10080, 1, BarAggregation::Week),
1086            (21600, 15, BarAggregation::Day), // 21600 min = 15 days
1087        ];
1088
1089        for (interval, expected_step, expected_aggregation) in test_cases {
1090            let spec = interval_to_bar_spec(interval).unwrap();
1091            assert_eq!(
1092                spec.step.get(),
1093                expected_step,
1094                "Failed for interval {interval}"
1095            );
1096            assert_eq!(
1097                spec.aggregation, expected_aggregation,
1098                "Failed for interval {interval}"
1099            );
1100            assert_eq!(spec.price_type, PriceType::Last);
1101        }
1102    }
1103
1104    #[rstest]
1105    fn test_interval_to_bar_spec_invalid() {
1106        let result = interval_to_bar_spec(999);
1107        assert!(result.is_err());
1108    }
1109
1110    #[rstest]
1111    fn test_parse_order_response_envelope_returns_order_response_variant() {
1112        use crate::websocket::spot_v2::enums::KrakenWsMethod;
1113
1114        let raw = load_test_json("ws_add_order_response_success.json");
1115        let parsed = parse_order_response(&raw).expect("parse ok");
1116        match parsed {
1117            Some(KrakenSpotWsMessage::OrderResponse(resp)) => {
1118                assert_eq!(resp.method, KrakenWsMethod::AddOrder);
1119                assert_eq!(resp.req_id, Some(42));
1120                assert!(resp.success);
1121            }
1122            other => panic!("expected OrderResponse, was {other:?}"),
1123        }
1124    }
1125
1126    #[rstest]
1127    fn test_parse_order_response_returns_none_for_non_order_method() {
1128        let json = r#"{"method":"subscribe","req_id":1,"success":true}"#;
1129        let result = parse_order_response(json).expect("parse ok");
1130        assert!(result.is_none());
1131    }
1132
1133    #[rstest]
1134    fn test_parse_order_response_returns_none_for_data_message() {
1135        let json = r#"{"channel":"ticker","type":"snapshot","data":[]}"#;
1136        let result = parse_order_response(json).expect("parse ok");
1137        assert!(result.is_none());
1138    }
1139}