Skip to main content

nautilus_kraken/common/
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//! Converters that translate Kraken API schemas into Nautilus domain models.
17
18use std::{fmt::Display, str::FromStr};
19
20use anyhow::Context;
21use indexmap::IndexMap;
22use nautilus_core::{Params, datetime::NANOSECONDS_IN_MILLISECOND, nanos::UnixNanos, uuid::UUID4};
23use nautilus_model::{
24    data::{Bar, BarType, TradeTick},
25    enums::{
26        AggressorSide, AssetClass, AvgPxReconciliation, BarAggregation, LiquiditySide, OrderSide,
27        OrderStatus, OrderType, PositionSide, TimeInForce, TriggerType,
28    },
29    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, TradeId, VenueOrderId},
30    instruments::{
31        Instrument, any::InstrumentAny, crypto_perpetual::CryptoPerpetual,
32        currency_pair::CurrencyPair, tokenized_asset::TokenizedAsset,
33    },
34    reports::{FillReport, OrderStatusReport, PositionStatusReport},
35    types::{Currency, Money, Price, Quantity, fixed::FIXED_PRECISION},
36};
37use rust_decimal::Decimal;
38use rust_decimal_macros::dec;
39
40use crate::{
41    common::{
42        consts::{KRAKEN_ALTNAME_KEY, KRAKEN_PAIR_DECIMALS_KEY, KRAKEN_VENUE},
43        enums::{
44            KrakenFuturesOrderEventType, KrakenFuturesOrderLifecycleStatus, KrakenFuturesOrderType,
45            KrakenInstrumentType, KrakenOrderSide, KrakenOrderType, KrakenPositionSide,
46            KrakenSpotTrigger, KrakenTriggerSignal,
47        },
48    },
49    http::models::{
50        AssetPairInfo, FuturesFill, FuturesInstrument, FuturesOpenOrder, FuturesOrderEvent,
51        FuturesOrderStatusDetails, FuturesPosition, FuturesPublicExecution, OhlcData, SpotOrder,
52        SpotTrade,
53    },
54};
55
56/// Parse a decimal string, handling empty strings and "0" values.
57pub fn parse_decimal(value: &str) -> anyhow::Result<Decimal> {
58    if value.is_empty() || value == "0" {
59        return Ok(dec!(0));
60    }
61    value
62        .parse::<Decimal>()
63        .map_err(|e| anyhow::anyhow!("Failed to parse decimal '{value}': {e}"))
64}
65
66fn parse_rfc3339_timestamp(value: &str, field: &str) -> anyhow::Result<UnixNanos> {
67    value
68        .parse::<UnixNanos>()
69        .map_err(|e| anyhow::anyhow!("Failed to parse {field}='{value}': {e}"))
70}
71
72/// Maps a Kraken asset code to the standard code the platform uses.
73///
74/// Kraken prefixes some legacy assets with `X` or `Z`, but the prefix is not a rule: `XTZ`, `ZRX`
75/// and `XAUT` legitimately begin with those letters. The mapping is therefore an explicit table,
76/// and a code it does not list is returned unchanged.
77#[inline]
78pub fn normalize_currency_code(code: &str) -> &str {
79    KRAKEN_ASSET_CODES
80        .iter()
81        .find(|(kraken, _)| *kraken == code)
82        .map_or(code, |(_, standard)| *standard)
83}
84
85/// Normalizes a venue asset key whose casing is not guaranteed.
86///
87/// The Kraken Futures account endpoints key balances by their own spelling, which is not
88/// consistently upper case, so match on the upper-cased key and return the standard code.
89pub fn normalize_asset_key(code: &str) -> String {
90    let upper = code.to_uppercase();
91    normalize_currency_code(&upper).to_string()
92}
93
94/// Maps Kraken's asset codes to the standard code the platform uses.
95///
96/// Kraken prefixes some legacy assets with `X` or `Z`, but the prefix is not a rule: `XTZ`, `ZRX`,
97/// `XAUT` and others legitimately begin with those letters and must survive untouched. Enumerate
98/// the mappings and pass everything else through, as Kraken's own CLI does.
99///
100/// `XXDG` and `XDG` map to `DOGE` rather than Kraken's own `XDG`, for the same reason `XBT` maps to
101/// `BTC`: the goal is the standard code, which is also what Kraken's WebSocket v2 API uses.
102const KRAKEN_ASSET_CODES: &[(&str, &str)] = &[
103    ("XXBT", "BTC"),
104    ("XBT", "BTC"),
105    ("XXDG", "DOGE"),
106    ("XDG", "DOGE"),
107    ("XETC", "ETC"),
108    ("XETH", "ETH"),
109    ("XLTC", "LTC"),
110    ("XMLN", "MLN"),
111    ("XREP", "REP"),
112    ("XXLM", "XLM"),
113    ("XXMR", "XMR"),
114    ("XXRP", "XRP"),
115    ("XZEC", "ZEC"),
116    ("ZARS", "ARS"),
117    ("ZAUD", "AUD"),
118    ("ZCAD", "CAD"),
119    ("ZCLP", "CLP"),
120    ("ZCOP", "COP"),
121    ("ZDKK", "DKK"),
122    ("ZEUR", "EUR"),
123    ("ZGBP", "GBP"),
124    ("ZGEL", "GEL"),
125    ("ZGHS", "GHS"),
126    ("ZJPY", "JPY"),
127    ("ZLKR", "LKR"),
128    ("ZMXN", "MXN"),
129    ("ZPLN", "PLN"),
130    ("ZSEK", "SEK"),
131    ("ZUGX", "UGX"),
132    ("ZUSD", "USD"),
133    ("ZVND", "VND"),
134    ("ZXOF", "XOF"),
135    ("KFEE", "FEE"),
136];
137
138/// Normalizes a Kraken spot `wsname` symbol to the form accepted by WS v2.
139///
140/// Kraken's REST API `wsname` field is supposed to be the WS-ready symbol, but some
141/// codes are stale and differ from what WS v2 actually accepts. This function applies
142/// all known renames so that instruments and subscriptions use consistent symbols.
143/// Renames are applied to both the base and quote leg of the pair.
144#[inline]
145pub fn normalize_spot_symbol(symbol: &str) -> String {
146    let Some((base, quote)) = symbol.split_once('/') else {
147        return symbol.to_string();
148    };
149    let base = normalize_currency_code(base);
150    let quote = normalize_currency_code(quote);
151    format!("{base}/{quote}")
152}
153
154/// Parse an optional decimal string.
155pub fn parse_decimal_opt(value: Option<&str>) -> anyhow::Result<Option<Decimal>> {
156    match value {
157        Some(s) if !s.is_empty() && s != "0" => Ok(Some(parse_decimal(s)?)),
158        _ => Ok(None),
159    }
160}
161
162/// Parse Kraken spot trigger to Nautilus TriggerType.
163fn parse_trigger_type(
164    order_type: OrderType,
165    trigger: Option<KrakenSpotTrigger>,
166) -> Option<TriggerType> {
167    let is_conditional = matches!(
168        order_type,
169        OrderType::StopMarket
170            | OrderType::StopLimit
171            | OrderType::MarketIfTouched
172            | OrderType::LimitIfTouched
173    );
174
175    if !is_conditional {
176        return None;
177    }
178
179    match trigger {
180        Some(KrakenSpotTrigger::Last) => Some(TriggerType::LastPrice),
181        Some(KrakenSpotTrigger::Index) => Some(TriggerType::IndexPrice),
182        None => Some(TriggerType::Default),
183    }
184}
185
186/// Parse Kraken futures trigger signal to Nautilus TriggerType.
187fn parse_futures_trigger_type(
188    order_type: OrderType,
189    trigger_signal: Option<KrakenTriggerSignal>,
190) -> Option<TriggerType> {
191    let is_conditional = matches!(
192        order_type,
193        OrderType::StopMarket
194            | OrderType::StopLimit
195            | OrderType::MarketIfTouched
196            | OrderType::LimitIfTouched
197    );
198
199    if !is_conditional {
200        return None;
201    }
202
203    match trigger_signal {
204        Some(KrakenTriggerSignal::Last) => Some(TriggerType::LastPrice),
205        Some(KrakenTriggerSignal::Mark) => Some(TriggerType::MarkPrice),
206        Some(KrakenTriggerSignal::Index) => Some(TriggerType::IndexPrice),
207        Some(KrakenTriggerSignal::Unknown) => {
208            log::warn!(
209                "KrakenTriggerSignal::Unknown received from venue, defaulting to Default trigger"
210            );
211            Some(TriggerType::Default)
212        }
213        None => Some(TriggerType::Default),
214    }
215}
216
217/// Parses a Kraken asset pair definition into a Nautilus currency pair instrument.
218///
219/// # Errors
220///
221/// Returns an error if:
222/// - Tick size, order minimum, or cost minimum cannot be parsed.
223/// - Price or quantity precision is invalid.
224/// - Currency codes are invalid.
225pub fn parse_spot_instrument(
226    pair_name: &str,
227    definition: &AssetPairInfo,
228    ts_event: UnixNanos,
229    ts_init: UnixNanos,
230) -> anyhow::Result<InstrumentAny> {
231    let symbol_str = definition.wsname.as_ref().unwrap_or(&definition.altname);
232    let normalized_symbol = normalize_spot_symbol(symbol_str);
233    let instrument_id = InstrumentId::new(Symbol::new(&normalized_symbol), *KRAKEN_VENUE);
234    let raw_symbol = Symbol::new(pair_name);
235
236    let base_currency = get_currency(definition.base.as_str());
237    let quote_currency = get_currency(definition.quote.as_str());
238
239    let price_increment = parse_price(
240        definition
241            .tick_size
242            .as_ref()
243            .context("tick_size is required")?,
244        "tick_size",
245    )?;
246
247    // lot_decimals specifies the decimal precision for the lot size
248    let size_precision = definition.lot_decimals;
249    let size_increment = Quantity::from_decimal_dp(
250        Decimal::try_new(1, u32::from(size_precision)).context("Invalid lot_decimals")?,
251        size_precision,
252    )?;
253
254    let min_quantity = definition
255        .ordermin
256        .as_ref()
257        .map(|s| parse_quantity(s, "ordermin"))
258        .transpose()?;
259
260    let instrument = CurrencyPair::builder()
261        .instrument_id(instrument_id)
262        .raw_symbol(raw_symbol)
263        .base_currency(base_currency)
264        .quote_currency(quote_currency)
265        .price_precision(price_increment.precision)
266        .size_precision(size_increment.precision)
267        .price_increment(price_increment)
268        .size_increment(size_increment)
269        .maybe_min_quantity(min_quantity)
270        .maybe_info(pair_info(pair_name, definition, price_increment.precision))
271        .ts_event(ts_event)
272        .ts_init(ts_init)
273        .build()
274        .unwrap();
275
276    Ok(InstrumentAny::CurrencyPair(instrument))
277}
278
279/// Parses a Kraken tokenized asset pair into a Nautilus tokenized asset instrument.
280///
281/// Tokenized assets (xStocks) use the same API schema as spot pairs but represent
282/// real-world equities, ETFs, or other tokenized securities.
283///
284/// # Errors
285///
286/// Returns an error if tick size or order minimum cannot be parsed.
287pub fn parse_tokenized_instrument(
288    pair_name: &str,
289    definition: &AssetPairInfo,
290    ts_event: UnixNanos,
291    ts_init: UnixNanos,
292) -> anyhow::Result<InstrumentAny> {
293    let symbol_str = definition.wsname.as_ref().unwrap_or(&definition.altname);
294    let normalized_symbol = normalize_spot_symbol(symbol_str);
295    let instrument_id = InstrumentId::new(Symbol::new(&normalized_symbol), *KRAKEN_VENUE);
296    let raw_symbol = Symbol::new(pair_name);
297
298    let base_currency = get_currency(definition.base.as_str());
299    let quote_currency = get_currency(definition.quote.as_str());
300
301    let price_increment = parse_price(
302        definition
303            .tick_size
304            .as_ref()
305            .context("tick_size is required")?,
306        "tick_size",
307    )?;
308
309    let size_precision = definition.lot_decimals;
310    let size_increment = Quantity::from_decimal_dp(
311        Decimal::try_new(1, u32::from(size_precision)).context("Invalid lot_decimals")?,
312        size_precision,
313    )?;
314
315    let min_quantity = definition
316        .ordermin
317        .as_ref()
318        .map(|s| parse_quantity(s, "ordermin"))
319        .transpose()?;
320
321    let instrument = TokenizedAsset::builder()
322        .instrument_id(instrument_id)
323        .raw_symbol(raw_symbol)
324        .asset_class(AssetClass::Equity)
325        .base_currency(base_currency)
326        .quote_currency(quote_currency)
327        .price_precision(price_increment.precision)
328        .size_precision(size_increment.precision)
329        .price_increment(price_increment)
330        .maybe_info(price_scale_info(definition, price_increment.precision))
331        .size_increment(size_increment)
332        .maybe_min_quantity(min_quantity)
333        .ts_event(ts_event)
334        .ts_init(ts_init)
335        .build()
336        .unwrap();
337
338    Ok(InstrumentAny::TokenizedAsset(instrument))
339}
340
341/// Parses a Kraken futures instrument definition into a Nautilus crypto perpetual instrument.
342///
343/// # Errors
344///
345/// Returns an error if:
346/// - Tick size cannot be parsed as a valid price.
347/// - Contract size cannot be parsed as a valid quantity.
348/// - Tick size, contract value trade precision, or contract size exceeds the active fixed
349///   precision.
350/// - Currency codes are invalid.
351///
352/// In standard-precision builds, an unsupported-precision error identifies the instrument,
353/// required precision, supported maximum, and the `high-precision` rebuild action.
354pub fn parse_futures_instrument(
355    instrument: &FuturesInstrument,
356    ts_event: UnixNanos,
357    ts_init: UnixNanos,
358) -> anyhow::Result<InstrumentAny> {
359    let instrument_id = InstrumentId::new(Symbol::new(&instrument.symbol), *KRAKEN_VENUE);
360    let raw_symbol = Symbol::new(&instrument.symbol);
361
362    let base_currency = get_currency(&instrument.base);
363    let quote_currency = get_currency(&instrument.quote);
364
365    let is_inverse = instrument.instrument_type == KrakenInstrumentType::FuturesInverse;
366    let settlement_currency = if is_inverse {
367        base_currency
368    } else {
369        quote_currency
370    };
371
372    // Normalize before deriving precision so wire padding does not overstate the tick precision
373    let tick_size = instrument.tick_size.normalize();
374    let price_precision = tick_size.scale();
375    check_futures_precision(&instrument.symbol, "tick_size", tick_size, price_precision)?;
376    let price_precision = u8::try_from(price_precision).context("Invalid tick_size precision")?;
377    let price_increment = Price::from_decimal_dp(tick_size, price_precision)?;
378
379    // Use contract_value_trade_precision for the tradeable size increment
380    // Positive values (e.g., 3) mean fractional sizes (0.001)
381    // Negative values (e.g., -3) mean multiples of powers of 10 (1000) - used for meme coins
382    // Zero means whole number increments (1)
383    let size_increment = if instrument.contract_value_trade_precision >= 0 {
384        let precision = u32::try_from(instrument.contract_value_trade_precision)
385            .context("Invalid contract_value_trade_precision")?;
386        check_futures_precision(
387            &instrument.symbol,
388            "contract_value_trade_precision",
389            instrument.contract_value_trade_precision,
390            precision,
391        )?;
392        let precision =
393            u8::try_from(precision).context("Invalid contract_value_trade_precision")?;
394        Quantity::from_decimal_dp(
395            Decimal::try_new(1, u32::from(precision))
396                .context("Invalid contract_value_trade_precision")?,
397            precision,
398        )?
399    } else {
400        // Negative precision: increment is 10^abs(precision), e.g., -3 means 1000
401        let exponent = instrument.contract_value_trade_precision.unsigned_abs();
402        let increment_value = 10_i64
403            .checked_pow(exponent)
404            .context("contract_value_trade_precision exceeds supported range")?;
405        Quantity::from_decimal_dp(Decimal::from(increment_value), 0)?
406    };
407
408    let contract_size = instrument.contract_size.normalize();
409    let multiplier_precision = contract_size.scale();
410    check_futures_precision(
411        &instrument.symbol,
412        "contract_size",
413        contract_size,
414        multiplier_precision,
415    )?;
416    let multiplier_precision =
417        u8::try_from(multiplier_precision).context("Invalid contract_size precision")?;
418    let multiplier = Some(Quantity::from_decimal_dp(
419        contract_size,
420        multiplier_precision,
421    )?);
422
423    // Use first margin level if available
424    let (margin_init, margin_maint) = instrument
425        .margin_levels
426        .first()
427        .map_or((None, None), |level| {
428            (Some(level.initial_margin), Some(level.maintenance_margin))
429        });
430
431    let instrument = CryptoPerpetual::builder()
432        .instrument_id(instrument_id)
433        .raw_symbol(raw_symbol)
434        .base_currency(base_currency)
435        .quote_currency(quote_currency)
436        .settlement_currency(settlement_currency)
437        .is_inverse(is_inverse)
438        .price_precision(price_increment.precision)
439        .size_precision(size_increment.precision)
440        .price_increment(price_increment)
441        .size_increment(size_increment)
442        .maybe_multiplier(multiplier)
443        .maybe_margin_init(margin_init)
444        .maybe_margin_maint(margin_maint)
445        .ts_event(ts_event)
446        .ts_init(ts_init)
447        .build()
448        .unwrap();
449
450    Ok(InstrumentAny::CryptoPerpetual(instrument))
451}
452
453fn check_futures_precision(
454    symbol: &str,
455    field: &str,
456    value: impl Display,
457    precision: u32,
458) -> anyhow::Result<()> {
459    if precision <= u32::from(FIXED_PRECISION) {
460        return Ok(());
461    }
462
463    #[cfg(feature = "high-precision")]
464    anyhow::bail!(
465        "Cannot parse Kraken Futures instrument '{symbol}': {field} {value} requires precision \
466         {precision}, but this build supports at most {FIXED_PRECISION}"
467    );
468
469    #[cfg(not(feature = "high-precision"))]
470    anyhow::bail!(
471        "Cannot parse Kraken Futures instrument '{symbol}': {field} {value} requires precision \
472         {precision}, but this build supports at most {FIXED_PRECISION}; enable the \
473         'high-precision' Cargo feature and rebuild"
474    );
475}
476
477fn parse_price(value: &str, field: &str) -> anyhow::Result<Price> {
478    Price::from_str(value).map_err(|e| anyhow::anyhow!("Failed to parse {field}='{value}': {e}"))
479}
480
481fn parse_quantity(value: &str, field: &str) -> anyhow::Result<Quantity> {
482    Quantity::from_str(value).map_err(|e| anyhow::anyhow!("Failed to parse {field}='{value}': {e}"))
483}
484
485/// Resolves a venue-reported fee currency, preferring the instrument's own definition.
486///
487/// A code the instrument already carries keeps that definition, so its precision is preserved
488/// rather than replaced by whatever the registry holds. Anything else, such as a base-currency fee
489/// on an inverse contract, resolves normally.
490pub fn fee_currency(reported: &str, instrument: &InstrumentAny) -> Currency {
491    let code = normalize_currency_code(reported);
492
493    for candidate in [
494        Some(instrument.quote_currency()),
495        instrument.base_currency(),
496        Some(instrument.settlement_currency()),
497    ]
498    .into_iter()
499    .flatten()
500    {
501        if candidate.code.as_str() == code {
502            return candidate;
503        }
504    }
505
506    get_currency(code)
507}
508
509/// Returns a currency from the internal map or creates a new crypto currency.
510///
511/// Uses [`Currency::get_or_create_crypto`] to handle unknown currency codes,
512/// which automatically registers newly listed Kraken assets.
513pub fn get_currency(code: &str) -> Currency {
514    Currency::get_or_create_crypto(normalize_currency_code(code))
515}
516
517/// Parses a Kraken trade array into a Nautilus trade tick.
518///
519/// The Kraken API returns trades as arrays: [price, volume, time, side, type, misc, trade_id]
520///
521/// # Errors
522///
523/// Returns an error if:
524/// - Price or volume cannot be parsed.
525/// - Timestamp is invalid.
526/// - Trade ID is invalid.
527pub fn parse_trade_tick_from_array(
528    trade_array: &[serde_json::Value],
529    instrument: &InstrumentAny,
530    ts_init: UnixNanos,
531) -> anyhow::Result<TradeTick> {
532    let price_str = trade_array
533        .first()
534        .and_then(|v| v.as_str())
535        .context("Missing or invalid price")?;
536    let price = parse_price_with_precision(price_str, instrument.price_precision(), "trade.price")?;
537
538    let size_str = trade_array
539        .get(1)
540        .and_then(|v| v.as_str())
541        .context("Missing or invalid volume")?;
542    let size = parse_quantity_with_precision(size_str, instrument.size_precision(), "trade.size")?;
543
544    let time = trade_array
545        .get(2)
546        .and_then(|v| v.as_f64())
547        .context("Missing or invalid timestamp")?;
548    let ts_event = parse_millis_timestamp(time, "trade.time")?;
549
550    let side_str = trade_array
551        .get(3)
552        .and_then(|v| v.as_str())
553        .context("Missing or invalid side")?;
554    let aggressor = match side_str {
555        "b" => AggressorSide::Buy,
556        "s" => AggressorSide::Sell,
557        _ => AggressorSide::NoAggressor,
558    };
559
560    let trade_id_value = trade_array.get(6).context("Missing trade_id")?;
561    let trade_id = if let Some(id) = trade_id_value.as_i64() {
562        TradeId::new_checked(id.to_string())?
563    } else if let Some(id_str) = trade_id_value.as_str() {
564        TradeId::new_checked(id_str)?
565    } else {
566        anyhow::bail!("Invalid trade_id format");
567    };
568
569    TradeTick::new_checked(
570        instrument.id(),
571        price,
572        size,
573        aggressor,
574        trade_id,
575        ts_event,
576        ts_init,
577    )
578    .context("Failed to construct TradeTick from Kraken trade")
579}
580
581/// Parses a Kraken Futures public execution into a Nautilus trade tick.
582///
583/// # Errors
584///
585/// Returns an error if:
586/// - Price or quantity cannot be parsed.
587/// - Trade ID is invalid.
588pub fn parse_futures_public_execution(
589    execution: &FuturesPublicExecution,
590    instrument: &InstrumentAny,
591    ts_init: UnixNanos,
592) -> anyhow::Result<TradeTick> {
593    let price =
594        parse_price_with_precision(&execution.price, instrument.price_precision(), "price")?;
595    let size = parse_quantity_with_precision(
596        &execution.quantity,
597        instrument.size_precision(),
598        "quantity",
599    )?;
600
601    // Timestamp is in milliseconds
602    let ts_event = UnixNanos::from((execution.timestamp as u64) * 1_000_000);
603
604    // Aggressor side is determined by the taker's direction
605    let aggressor = match execution.taker_order.direction.to_lowercase().as_str() {
606        "buy" => AggressorSide::Buy,
607        "sell" => AggressorSide::Sell,
608        _ => AggressorSide::NoAggressor,
609    };
610
611    let trade_id = TradeId::new_checked(&execution.uid)?;
612
613    TradeTick::new_checked(
614        instrument.id(),
615        price,
616        size,
617        aggressor,
618        trade_id,
619        ts_event,
620        ts_init,
621    )
622    .context("Failed to construct TradeTick from Kraken futures execution")
623}
624
625/// Parses a Kraken OHLC entry into a Nautilus bar.
626///
627/// # Errors
628///
629/// Returns an error if:
630/// - OHLC values cannot be parsed.
631/// - Timestamp is invalid.
632pub fn parse_bar(
633    ohlc: &OhlcData,
634    instrument: &InstrumentAny,
635    bar_type: BarType,
636    ts_init: UnixNanos,
637) -> anyhow::Result<Bar> {
638    let price_precision = instrument.price_precision();
639    let size_precision = instrument.size_precision();
640
641    let open = parse_price_with_precision(&ohlc.open, price_precision, "ohlc.open")?;
642    let high = parse_price_with_precision(&ohlc.high, price_precision, "ohlc.high")?;
643    let low = parse_price_with_precision(&ohlc.low, price_precision, "ohlc.low")?;
644    let close = parse_price_with_precision(&ohlc.close, price_precision, "ohlc.close")?;
645    let volume = parse_quantity_with_precision(&ohlc.volume, size_precision, "ohlc.volume")?;
646
647    let ts_event = UnixNanos::from((ohlc.time as u64) * 1_000_000_000);
648
649    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
650        .context("Failed to construct Bar from Kraken OHLC")
651}
652
653fn parse_price_with_precision(value: &str, precision: u8, field: &str) -> anyhow::Result<Price> {
654    let parsed = value
655        .parse::<Decimal>()
656        .with_context(|| format!("Failed to parse {field}='{value}' as Decimal"))?;
657    Price::from_decimal_dp(parsed, precision).with_context(|| {
658        format!("Failed to construct Price for {field} with precision {precision}")
659    })
660}
661
662fn parse_quantity_with_precision(
663    value: &str,
664    precision: u8,
665    field: &str,
666) -> anyhow::Result<Quantity> {
667    let parsed = value
668        .parse::<Decimal>()
669        .with_context(|| format!("Failed to parse {field}='{value}' as Decimal"))?;
670    Quantity::from_decimal_dp(parsed, precision).with_context(|| {
671        format!("Failed to construct Quantity for {field} with precision {precision}")
672    })
673}
674
675pub fn parse_millis_timestamp(value: f64, field: &str) -> anyhow::Result<UnixNanos> {
676    let millis = (value * 1000.0) as u64;
677    let nanos = millis
678        .checked_mul(NANOSECONDS_IN_MILLISECOND)
679        .with_context(|| format!("{field} timestamp overflowed when converting to nanoseconds"))?;
680    Ok(UnixNanos::from(nanos))
681}
682
683/// Builds the `info` of a Spot currency pair: Kraken's `altname` when it differs from the
684/// `AssetPairs` key, and the wire price scale when it differs from the tick-size precision.
685///
686/// The key is the instrument `raw_symbol`, while `OpenOrders`, `ClosedOrders` and `TradesHistory`
687/// spell the pair with the altname. A client whose instruments arrive through the cache APIs never
688/// sees the `AssetPairs` response, so the alias has to travel with the instrument.
689fn pair_info(pair_name: &str, definition: &AssetPairInfo, price_precision: u8) -> Option<Params> {
690    let mut map = IndexMap::new();
691
692    if definition.altname.as_str() != pair_name {
693        map.insert(
694            KRAKEN_ALTNAME_KEY.to_string(),
695            serde_json::Value::String(definition.altname.to_string()),
696        );
697    }
698
699    insert_price_scale(&mut map, definition, price_precision);
700    (!map.is_empty()).then(|| Params::new(map))
701}
702
703/// Builds the `info` of a tokenized pair: the wire price scale alone, when it differs from the
704/// tick-size precision.
705///
706/// The altname is left out, so the alias index built from cached instruments covers currency pairs
707/// only.
708fn price_scale_info(definition: &AssetPairInfo, price_precision: u8) -> Option<Params> {
709    let mut map = IndexMap::new();
710    insert_price_scale(&mut map, definition, price_precision);
711    (!map.is_empty()).then(|| Params::new(map))
712}
713
714/// Records `pair_decimals` under [`KRAKEN_PAIR_DECIMALS_KEY`] when it is finer than
715/// `price_precision`; the checksum falls back to the tick-size precision when the key is absent.
716///
717/// A coarser `pair_decimals` is not recorded: rendering a price at fewer decimals than its
718/// precision truncates rather than rounds, so hashing at that scale would mismatch every message,
719/// while the tick-size precision reproduces the venue's digits.
720fn insert_price_scale(
721    map: &mut IndexMap<String, serde_json::Value>,
722    definition: &AssetPairInfo,
723    price_precision: u8,
724) {
725    if definition.pair_decimals > price_precision {
726        map.insert(
727            KRAKEN_PAIR_DECIMALS_KEY.to_string(),
728            serde_json::Value::from(u64::from(definition.pair_decimals)),
729        );
730    }
731}
732
733/// Parses a venue order ID received from Kraken, naming `payload` in the error.
734///
735/// # Errors
736///
737/// Returns an error if `order_id` is empty, blank, or not ASCII.
738pub(crate) fn parse_venue_order_id(
739    order_id: &str,
740    payload: impl Display,
741) -> anyhow::Result<VenueOrderId> {
742    VenueOrderId::new_checked(order_id)
743        .with_context(|| format!("Invalid order_id '{order_id}' in Kraken {payload}"))
744}
745
746/// Parses a Kraken spot order into a Nautilus OrderStatusReport.
747///
748/// # Errors
749///
750/// Returns an error if:
751/// - Order ID, quantities, or prices cannot be parsed.
752/// - Order status mapping fails.
753/// - A row mapped to `LimitIfTouched` has its trigger above a buy limit or below a sell
754///   limit.
755pub fn parse_order_status_report(
756    order_id: &str,
757    order: &SpotOrder,
758    instrument: &InstrumentAny,
759    account_id: AccountId,
760    ts_init: UnixNanos,
761) -> anyhow::Result<OrderStatusReport> {
762    let instrument_id = instrument.id();
763    let venue_order_id = parse_venue_order_id(order_id, "spot order")?;
764
765    let order_side = OrderSide::from(order.descr.order_side).into();
766    let order_type = order.descr.ordertype.into();
767    let order_status = order.status.into();
768
769    // Kraken returns expiretm=0 for GTC orders, so check for actual expiration value
770    let has_expiration = order.expiretm.is_some_and(|t| t > 0.0);
771    let time_in_force = if has_expiration {
772        TimeInForce::Gtd
773    } else if order.oflags.contains("ioc") {
774        TimeInForce::Ioc
775    } else {
776        TimeInForce::Gtc
777    };
778
779    let quantity =
780        parse_quantity_with_precision(&order.vol, instrument.size_precision(), "order.vol")?;
781
782    let filled_qty = parse_quantity_with_precision(
783        &order.vol_exec,
784        instrument.size_precision(),
785        "order.vol_exec",
786    )?;
787
788    let ts_accepted = parse_millis_timestamp(order.opentm, "order.opentm")?;
789
790    let ts_last = order
791        .closetm
792        .map(|t| parse_millis_timestamp(t, "order.closetm"))
793        .transpose()?
794        .unwrap_or(ts_accepted);
795
796    // The row's top-level `price` is the average fill price, which `avg_px` carries, so the
797    // order's prices come from the fields that hold them
798    let price_precision = instrument.price_precision();
799    let row_price =
800        |value: &str, field: &str| parse_spot_order_price(order_id, value, price_precision, field);
801    let price = match order.descr.ordertype {
802        KrakenOrderType::Limit => row_price(&order.descr.price, "descr.price")?,
803        KrakenOrderType::StopLossLimit | KrakenOrderType::TakeProfitLimit => {
804            row_price(&order.descr.price2, "descr.price2")?
805        }
806        // A trailing-stop-limit's `descr.price2` holds the offset AddOrder took until `misc` marks
807        // the order `stopped` and the limit after, while its `limitprice` holds the peak price in
808        // both states
809        KrakenOrderType::TrailingStopLimit
810            if order.misc.split(',').any(|info| info == "stopped") =>
811        {
812            row_price(&order.descr.price2, "descr.price2")?
813        }
814        KrakenOrderType::Market
815        | KrakenOrderType::SettlePosition
816        | KrakenOrderType::StopLoss
817        | KrakenOrderType::TakeProfit
818        | KrakenOrderType::TrailingStop
819        | KrakenOrderType::TrailingStopLimit => None,
820    };
821
822    let stop_price = order
823        .stopprice
824        .as_deref()
825        .map(|value| row_price(value, "stopprice"))
826        .transpose()?
827        .flatten();
828
829    // AddOrder takes a non-trailing conditional order's trigger as its `price`, which the
830    // description holds, so it stands in for a zero `stopprice`
831    let trigger_price = match order.descr.ordertype {
832        KrakenOrderType::StopLoss
833        | KrakenOrderType::TakeProfit
834        | KrakenOrderType::StopLossLimit
835        | KrakenOrderType::TakeProfitLimit => match stop_price {
836            Some(price) => Some(price),
837            None => row_price(&order.descr.price, "descr.price")?,
838        },
839        KrakenOrderType::Market
840        | KrakenOrderType::Limit
841        | KrakenOrderType::SettlePosition
842        | KrakenOrderType::TrailingStop
843        | KrakenOrderType::TrailingStopLimit => stop_price,
844    };
845
846    // A LimitIfTouched row with its trigger on the wrong side of its limit states an order
847    // Nautilus cannot represent, so fail it with both prices instead of an anonymous drop.
848    if order_type == OrderType::LimitIfTouched
849        && let (Some(limit), Some(trigger)) = (price, trigger_price)
850    {
851        let (side, relation, violates) = match order.descr.order_side {
852            KrakenOrderSide::Buy => ("Buy", "above", trigger > limit),
853            KrakenOrderSide::Sell => ("Sell", "below", trigger < limit),
854        };
855
856        if violates {
857            let kraken_type = order.descr.ordertype;
858            anyhow::bail!(
859                "{side} {kraken_type} with trigger price {trigger} {relation} limit price {limit} cannot be represented as LimitIfTouched"
860            );
861        }
862    }
863
864    let expire_time = if has_expiration {
865        order
866            .expiretm
867            .map(|t| parse_millis_timestamp(t, "order.expiretm"))
868            .transpose()?
869    } else {
870        None
871    };
872
873    let trigger_type = parse_trigger_type(order_type, order.trigger);
874
875    Ok(OrderStatusReport {
876        account_id,
877        instrument_id,
878        client_order_id: None,
879        venue_order_id,
880        order_side,
881        order_type,
882        time_in_force,
883        order_status,
884        quantity,
885        filled_qty,
886        report_id: UUID4::new(),
887        ts_accepted,
888        ts_last,
889        ts_init,
890        order_list_id: None,
891        venue_position_id: None,
892        linked_order_ids: None,
893        parent_order_id: None,
894        contingency_type: None,
895        expire_time,
896        price,
897        activation_price: None,
898        trigger_price,
899        trigger_type,
900        limit_offset: None,
901        trailing_offset: None,
902        trailing_offset_type: None,
903        display_qty: None,
904        avg_px: compute_avg_px(order),
905        post_only: order.oflags.contains("post"),
906        reduce_only: false,
907        cancel_reason: order.reason.clone(),
908        ts_triggered: None,
909    })
910}
911
912/// Parses a price field of a spot order row, an empty or zero value stating no price.
913///
914/// AddOrder also takes a price relative to the market, as an expression with a `+`, `-` or `#`
915/// prefix or a `%` suffix. Such a value is not a price, so it reads as none, with a warning,
916/// rather than failing the read.
917fn parse_spot_order_price(
918    order_id: &str,
919    value: &str,
920    precision: u8,
921    field: &str,
922) -> anyhow::Result<Option<Price>> {
923    if value.is_empty() {
924        return Ok(None);
925    }
926
927    if value.starts_with(['+', '-', '#']) || value.ends_with('%') {
928        log::warn!("Spot order {order_id} {field}='{value}' is a relative price, reporting none");
929        return Ok(None);
930    }
931
932    let price = parse_price_with_precision(value, precision, field)?;
933    Ok((!price.is_zero()).then_some(price))
934}
935
936/// Computes the average price for a Kraken spot order.
937///
938/// Prefers the direct `avg_price` field if available, otherwise calculates from `cost / vol_exec`.
939fn compute_avg_px(order: &SpotOrder) -> Option<Decimal> {
940    if let Some(ref avg) = order.avg_price
941        && let Ok(v) = parse_decimal(avg)
942        && v > dec!(0)
943    {
944        return Some(v);
945    }
946
947    let cost = parse_decimal(&order.cost);
948    let vol_exec = parse_decimal(&order.vol_exec);
949    match (&cost, &vol_exec) {
950        (Ok(c), Ok(v)) if *v > dec!(0) => Some(*c / *v),
951        _ => {
952            if let Ok(v) = &vol_exec
953                && *v > dec!(0)
954            {
955                log::warn!("Cannot compute avg_px: cost={cost:?}, vol_exec={vol_exec:?}");
956            }
957            None
958        }
959    }
960}
961
962/// Parses a Kraken spot trade into a Nautilus FillReport.
963///
964/// # Errors
965///
966/// Returns an error if:
967/// - Order ID, quantities, or prices cannot be parsed.
968pub fn parse_fill_report(
969    trade_id: &str,
970    trade: &SpotTrade,
971    instrument: &InstrumentAny,
972    account_id: AccountId,
973    ts_init: UnixNanos,
974) -> anyhow::Result<FillReport> {
975    let instrument_id = instrument.id();
976    let venue_order_id = parse_venue_order_id(&trade.ordertxid, "spot trade")?;
977    let trade_id_obj = TradeId::new(trade_id);
978
979    let order_side = trade.trade_type.into();
980
981    let last_qty =
982        parse_quantity_with_precision(&trade.vol, instrument.size_precision(), "trade.vol")?;
983
984    let last_px =
985        parse_price_with_precision(&trade.price, instrument.price_precision(), "trade.price")?;
986
987    let fee_decimal = parse_decimal(&trade.fee)?;
988    let quote_currency = match instrument {
989        InstrumentAny::CurrencyPair(pair) => pair.quote_currency,
990        InstrumentAny::CryptoPerpetual(perp) => perp.quote_currency,
991        InstrumentAny::TokenizedAsset(ta) => ta.quote_currency,
992        _ => anyhow::bail!("Unsupported instrument type for fill report"),
993    };
994
995    let commission = Money::from_decimal(fee_decimal, quote_currency)?;
996
997    let liquidity_side = match trade.maker {
998        Some(true) => LiquiditySide::Maker,
999        Some(false) => LiquiditySide::Taker,
1000        None => LiquiditySide::NoLiquiditySide,
1001    };
1002
1003    let ts_event = parse_millis_timestamp(trade.time, "trade.time")?;
1004
1005    Ok(FillReport {
1006        account_id,
1007        instrument_id,
1008        venue_order_id,
1009        trade_id: trade_id_obj,
1010        order_side,
1011        last_qty,
1012        last_px,
1013        commission,
1014        liquidity_side,
1015        avg_px: None,
1016        report_id: UUID4::new(),
1017        ts_event,
1018        ts_init,
1019        client_order_id: None,
1020        venue_position_id: None,
1021    })
1022}
1023
1024/// Returns the time in force and post-only flag the adapter reports for a Kraken futures order
1025/// type: `ioc` is `IOC`, `post` is post-only `GTC`, and every other type is reported as `GTC` and
1026/// not post-only.
1027pub(crate) fn parse_futures_order_type_time_in_force(
1028    order_type: KrakenFuturesOrderType,
1029) -> (TimeInForce, bool) {
1030    match order_type {
1031        KrakenFuturesOrderType::Ioc => (TimeInForce::Ioc, false),
1032        KrakenFuturesOrderType::Post => (TimeInForce::Gtc, true),
1033        KrakenFuturesOrderType::Limit
1034        | KrakenFuturesOrderType::Market
1035        | KrakenFuturesOrderType::Stop
1036        | KrakenFuturesOrderType::StopLower
1037        | KrakenFuturesOrderType::TakeProfit
1038        | KrakenFuturesOrderType::StopLoss
1039        | KrakenFuturesOrderType::Unknown => (TimeInForce::Gtc, false),
1040    }
1041}
1042
1043/// Parses a Kraken futures open order into a Nautilus OrderStatusReport.
1044///
1045/// # Errors
1046///
1047/// Returns an error if order ID, quantities, or prices cannot be parsed.
1048pub fn parse_futures_order_status_report(
1049    order: &FuturesOpenOrder,
1050    instrument: &InstrumentAny,
1051    account_id: AccountId,
1052    fallback_quantity: Option<Decimal>,
1053    ts_init: UnixNanos,
1054) -> anyhow::Result<OrderStatusReport> {
1055    let instrument_id = instrument.id();
1056    let venue_order_id = parse_venue_order_id(&order.order_id, "futures open order")?;
1057
1058    let order_side = OrderSide::from(order.side).into();
1059    let order_type: OrderType = order.order_type.into();
1060    let order_type = if order_type == OrderType::MarketIfTouched && order.limit_price.is_some() {
1061        OrderType::LimitIfTouched
1062    } else {
1063        order_type
1064    };
1065    let order_status = order.status.into();
1066    let (time_in_force, post_only) = parse_futures_order_type_time_in_force(order.order_type);
1067
1068    let quantity_value = order
1069        .unfilled_size
1070        .map(|unfilled_size| unfilled_size + order.filled_size)
1071        .or(fallback_quantity)
1072        .context("missing unfilled size and fallback quantity")?;
1073    let quantity = Quantity::from_decimal_dp(quantity_value, instrument.size_precision())?;
1074
1075    let filled_qty = Quantity::from_decimal_dp(order.filled_size, instrument.size_precision())?;
1076
1077    let ts_accepted = parse_rfc3339_timestamp(&order.received_time, "order.received_time")?;
1078    let ts_last = parse_rfc3339_timestamp(&order.last_update_time, "order.last_update_time")?;
1079
1080    let price = order
1081        .limit_price
1082        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1083        .transpose()?;
1084
1085    let trigger_price = order
1086        .stop_price
1087        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1088        .transpose()?;
1089
1090    let trigger_type = parse_futures_trigger_type(order_type, order.trigger_signal);
1091
1092    Ok(OrderStatusReport {
1093        account_id,
1094        instrument_id,
1095        client_order_id: echoed_client_order_id(order.client_order_id()),
1096        venue_order_id,
1097        order_side,
1098        order_type,
1099        time_in_force,
1100        order_status,
1101        quantity,
1102        filled_qty,
1103        report_id: UUID4::new(),
1104        ts_accepted,
1105        ts_last,
1106        ts_init,
1107        order_list_id: None,
1108        venue_position_id: None,
1109        linked_order_ids: None,
1110        parent_order_id: None,
1111        contingency_type: None,
1112        expire_time: None,
1113        price,
1114        activation_price: None,
1115        trigger_price,
1116        trigger_type,
1117        limit_offset: None,
1118        trailing_offset: None,
1119        trailing_offset_type: None,
1120        display_qty: None,
1121        avg_px: None,
1122        post_only,
1123        reduce_only: order.reduce_only.unwrap_or(false),
1124        cancel_reason: None,
1125        ts_triggered: None,
1126    })
1127}
1128
1129/// Parses a Kraken futures order event (historical order) into a Nautilus OrderStatusReport.
1130///
1131/// # Errors
1132///
1133/// Returns an error if order ID, quantities, or prices cannot be parsed.
1134pub fn parse_futures_order_event_status_report(
1135    event: &FuturesOrderEvent,
1136    event_type: Option<KrakenFuturesOrderEventType>,
1137    instrument: &InstrumentAny,
1138    account_id: AccountId,
1139    ts_init: UnixNanos,
1140) -> anyhow::Result<OrderStatusReport> {
1141    let instrument_id = instrument.id();
1142    let venue_order_id = parse_venue_order_id(&event.order_id, "futures order event")?;
1143
1144    let order_side = OrderSide::from(event.side).into();
1145    let order_type: OrderType = event.order_type.into();
1146    let order_type = if order_type == OrderType::MarketIfTouched && event.limit_price.is_some() {
1147        OrderType::LimitIfTouched
1148    } else {
1149        order_type
1150    };
1151
1152    let order_status = parse_futures_order_event_status(event_type, event.filled, event.quantity);
1153
1154    let quantity = Quantity::from_decimal_dp(event.quantity, instrument.size_precision())?;
1155    let filled_qty = Quantity::from_decimal_dp(event.filled, instrument.size_precision())?;
1156
1157    let ts_accepted = parse_rfc3339_timestamp(&event.timestamp, "event.timestamp")?;
1158    let ts_last =
1159        parse_rfc3339_timestamp(&event.last_update_timestamp, "event.last_update_timestamp")?;
1160
1161    let price = event
1162        .limit_price
1163        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1164        .transpose()?;
1165
1166    let trigger_price = event
1167        .stop_price
1168        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1169        .transpose()?;
1170
1171    let trigger_type = parse_futures_trigger_type(order_type, None);
1172
1173    Ok(OrderStatusReport {
1174        account_id,
1175        instrument_id,
1176        client_order_id: echoed_client_order_id(event.cli_ord_id.as_deref()),
1177        venue_order_id,
1178        order_side,
1179        order_type,
1180        time_in_force: event.time_in_force,
1181        order_status,
1182        quantity,
1183        filled_qty,
1184        report_id: UUID4::new(),
1185        ts_accepted,
1186        ts_last,
1187        ts_init,
1188        order_list_id: None,
1189        venue_position_id: None,
1190        linked_order_ids: None,
1191        parent_order_id: None,
1192        contingency_type: None,
1193        expire_time: None,
1194        price,
1195        activation_price: None,
1196        trigger_price,
1197        trigger_type,
1198        limit_offset: None,
1199        trailing_offset: None,
1200        trailing_offset_type: None,
1201        display_qty: None,
1202        avg_px: None,
1203        post_only: event.post_only,
1204        reduce_only: event.reduce_only,
1205        cancel_reason: None,
1206        ts_triggered: None,
1207    })
1208}
1209
1210/// The client order ID a futures response echoes, if it carries a valid one. An empty or invalid
1211/// echo, which another tool on the account may have sent, names no order rather than failing the
1212/// read.
1213fn echoed_client_order_id(echoed: Option<&str>) -> Option<ClientOrderId> {
1214    echoed
1215        .filter(|id| !id.is_empty())
1216        .and_then(|id| ClientOrderId::new_checked(id).ok())
1217}
1218
1219/// Parses a Kraken futures `/orders/status` entry into a Nautilus
1220/// OrderStatusReport.
1221///
1222/// The endpoint reports orders which are open or were filled/cancelled in the
1223/// last 5 seconds, so the entry's cumulative `filled` is authoritative for
1224/// reconciliation even when the order is absent from the open-orders snapshot.
1225///
1226/// # Errors
1227///
1228/// Returns an error if order ID, quantities, prices, or timestamps cannot be
1229/// parsed.
1230pub fn parse_futures_order_status_details_report(
1231    details: &FuturesOrderStatusDetails,
1232    instrument: &InstrumentAny,
1233    account_id: AccountId,
1234    ts_init: UnixNanos,
1235) -> anyhow::Result<OrderStatusReport> {
1236    let venue_order_id = parse_venue_order_id(&details.order.order_id, "futures order status")?;
1237
1238    let order_side = OrderSide::from(details.order.side).into();
1239
1240    let order_type = if details.order.limit_price.is_some() {
1241        OrderType::Limit
1242    } else {
1243        OrderType::Market
1244    };
1245
1246    let filled = details.order.filled.unwrap_or(Decimal::ZERO);
1247
1248    let order_status = match details.status {
1249        KrakenFuturesOrderLifecycleStatus::EnteredBook
1250        | KrakenFuturesOrderLifecycleStatus::TriggerPlaced => {
1251            if filled > Decimal::ZERO {
1252                OrderStatus::PartiallyFilled
1253            } else {
1254                OrderStatus::Accepted
1255            }
1256        }
1257        KrakenFuturesOrderLifecycleStatus::FullyExecuted => OrderStatus::Filled,
1258        KrakenFuturesOrderLifecycleStatus::Rejected
1259        | KrakenFuturesOrderLifecycleStatus::TriggerActivationFailure => OrderStatus::Rejected,
1260        KrakenFuturesOrderLifecycleStatus::Cancelled => OrderStatus::Canceled,
1261    };
1262
1263    let quantity_value = details
1264        .order
1265        .quantity
1266        .context("order status details missing quantity")?;
1267    let quantity = Quantity::from_decimal_dp(quantity_value, instrument.size_precision())?;
1268    let filled_qty = Quantity::from_decimal_dp(filled, instrument.size_precision())?;
1269
1270    let ts_accepted = parse_rfc3339_timestamp(&details.order.timestamp, "order.timestamp")?;
1271    let ts_last = parse_rfc3339_timestamp(
1272        &details.order.last_update_timestamp,
1273        "order.last_update_timestamp",
1274    )?;
1275
1276    let price = details
1277        .order
1278        .limit_price
1279        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1280        .transpose()?;
1281
1282    let cancel_reason = match details.status {
1283        KrakenFuturesOrderLifecycleStatus::Cancelled
1284        | KrakenFuturesOrderLifecycleStatus::Rejected
1285        | KrakenFuturesOrderLifecycleStatus::TriggerActivationFailure => {
1286            details.update_reason.clone()
1287        }
1288        _ => None,
1289    };
1290
1291    Ok(OrderStatusReport {
1292        account_id,
1293        instrument_id: instrument.id(),
1294        client_order_id: echoed_client_order_id(details.order.cli_ord_id.as_deref()),
1295        venue_order_id,
1296        order_side,
1297        order_type,
1298        time_in_force: TimeInForce::Gtc,
1299        order_status,
1300        quantity,
1301        filled_qty,
1302        report_id: UUID4::new(),
1303        ts_accepted,
1304        ts_last,
1305        ts_init,
1306        order_list_id: None,
1307        venue_position_id: None,
1308        linked_order_ids: None,
1309        parent_order_id: None,
1310        contingency_type: None,
1311        expire_time: None,
1312        price,
1313        activation_price: None,
1314        trigger_price: None,
1315        trigger_type: None,
1316        limit_offset: None,
1317        trailing_offset: None,
1318        trailing_offset_type: None,
1319        display_qty: None,
1320        avg_px: None,
1321        post_only: false,
1322        reduce_only: details.order.reduce_only,
1323        cancel_reason,
1324        ts_triggered: None,
1325    })
1326}
1327
1328fn parse_futures_order_event_status(
1329    event_type: Option<KrakenFuturesOrderEventType>,
1330    filled: Decimal,
1331    quantity: Decimal,
1332) -> OrderStatus {
1333    match event_type {
1334        Some(KrakenFuturesOrderEventType::Cancel) => OrderStatus::Canceled,
1335        Some(KrakenFuturesOrderEventType::Reject) => OrderStatus::Rejected,
1336        Some(KrakenFuturesOrderEventType::Expire) => OrderStatus::Expired,
1337        Some(
1338            KrakenFuturesOrderEventType::Fill
1339            | KrakenFuturesOrderEventType::Execution
1340            | KrakenFuturesOrderEventType::Place
1341            | KrakenFuturesOrderEventType::Edit,
1342        ) => {
1343            if filled >= quantity {
1344                OrderStatus::Filled
1345            } else if filled > Decimal::ZERO {
1346                OrderStatus::PartiallyFilled
1347            } else {
1348                OrderStatus::Accepted
1349            }
1350        }
1351        _ => {
1352            if filled >= quantity {
1353                OrderStatus::Filled
1354            } else if filled > Decimal::ZERO {
1355                OrderStatus::PartiallyFilled
1356            } else {
1357                OrderStatus::Canceled
1358            }
1359        }
1360    }
1361}
1362
1363/// Parses a Kraken futures fill into a Nautilus FillReport.
1364///
1365/// # Errors
1366///
1367/// Returns an error if order ID, quantities, or prices cannot be parsed.
1368pub fn parse_futures_fill_report(
1369    fill: &FuturesFill,
1370    instrument: &InstrumentAny,
1371    account_id: AccountId,
1372    ts_init: UnixNanos,
1373) -> anyhow::Result<FillReport> {
1374    let instrument_id = instrument.id();
1375    let venue_order_id = parse_venue_order_id(&fill.order_id, "futures fill")?;
1376    let trade_id = TradeId::new(&fill.fill_id);
1377
1378    let order_side = fill.side.into();
1379
1380    let last_qty = Quantity::from_decimal_dp(fill.size, instrument.size_precision())?;
1381    let last_px = Price::from_decimal_dp(fill.price, instrument.price_precision())?;
1382
1383    let quote_currency = match instrument {
1384        InstrumentAny::CryptoPerpetual(perp) => perp.quote_currency,
1385        InstrumentAny::CryptoFuture(future) => future.quote_currency,
1386        _ => anyhow::bail!("Unsupported instrument type for futures fill report"),
1387    };
1388
1389    // The venue reports the fee currency, which on an inverse contract is not the quote.
1390    let commission_currency = fill
1391        .fee_currency
1392        .as_deref()
1393        .map_or(quote_currency, |reported| {
1394            fee_currency(reported, instrument)
1395        });
1396    let commission =
1397        Money::from_decimal(fill.fee_paid.unwrap_or(Decimal::ZERO), commission_currency)?;
1398
1399    let liquidity_side = fill.fill_type.into();
1400
1401    let ts_event = parse_rfc3339_timestamp(&fill.fill_time, "fill.fill_time")?;
1402
1403    Ok(FillReport {
1404        account_id,
1405        instrument_id,
1406        venue_order_id,
1407        trade_id,
1408        order_side,
1409        last_qty,
1410        last_px,
1411        commission,
1412        liquidity_side,
1413        avg_px: None,
1414        report_id: UUID4::new(),
1415        ts_event,
1416        ts_init,
1417        client_order_id: echoed_client_order_id(fill.client_order_id()),
1418        venue_position_id: None,
1419    })
1420}
1421
1422/// Parses a Kraken futures position into a Nautilus PositionStatusReport.
1423///
1424/// # Errors
1425///
1426/// Returns an error if position quantities or prices cannot be parsed.
1427pub fn parse_futures_position_status_report(
1428    position: &FuturesPosition,
1429    instrument: &InstrumentAny,
1430    account_id: AccountId,
1431    ts_init: UnixNanos,
1432) -> anyhow::Result<PositionStatusReport> {
1433    let instrument_id = instrument.id();
1434
1435    let position_side = match position.side {
1436        KrakenPositionSide::Long => PositionSide::Long,
1437        KrakenPositionSide::Short => PositionSide::Short,
1438    };
1439
1440    let quantity = Quantity::from_decimal_dp(position.size, instrument.size_precision())?;
1441    let signed_decimal_qty = match position_side {
1442        PositionSide::Long => position.size,
1443        PositionSide::Short => -position.size,
1444        PositionSide::Flat => dec!(0),
1445    };
1446
1447    let avg_px_open = Some(position.price);
1448
1449    Ok(PositionStatusReport {
1450        account_id,
1451        instrument_id,
1452        position_side,
1453        quantity,
1454        signed_decimal_qty,
1455        report_id: UUID4::new(),
1456        ts_last: ts_init,
1457        ts_init,
1458        venue_position_id: None,
1459        avg_px_open,
1460        avg_px_open_reconciliation: AvgPxReconciliation::default(),
1461        avg_px_open_precision: None,
1462        liquidation_price: None,
1463    })
1464}
1465
1466/// Converts a Nautilus BarType to Kraken Spot API interval (in minutes).
1467///
1468/// # Errors
1469///
1470/// Returns an error if:
1471/// - Bar aggregation type is not supported (only Minute, Hour, Day are valid).
1472/// - Bar step is not supported for the aggregation type.
1473pub fn bar_type_to_spot_interval(bar_type: BarType) -> anyhow::Result<u32> {
1474    let step = bar_type.spec().step.get() as u32;
1475    let base_interval = match bar_type.spec().aggregation {
1476        BarAggregation::Minute => 1,
1477        BarAggregation::Hour => 60,
1478        BarAggregation::Day => 1440,
1479        other => {
1480            anyhow::bail!("Unsupported bar aggregation for Kraken Spot: {other:?}");
1481        }
1482    };
1483    Ok(base_interval * step)
1484}
1485
1486/// Converts a Nautilus BarType to Kraken Futures API resolution string.
1487///
1488/// Supported resolutions: 1m, 5m, 15m, 1h, 4h, 12h, 1d, 1w
1489///
1490/// # Errors
1491///
1492/// Returns an error if:
1493/// - Bar aggregation type is not supported.
1494/// - Bar step is not supported for the aggregation type.
1495pub fn bar_type_to_futures_resolution(bar_type: BarType) -> anyhow::Result<&'static str> {
1496    let step = bar_type.spec().step.get() as u32;
1497    match bar_type.spec().aggregation {
1498        BarAggregation::Minute => match step {
1499            1 => Ok("1m"),
1500            5 => Ok("5m"),
1501            15 => Ok("15m"),
1502            _ => anyhow::bail!("Unsupported minute step for Kraken Futures: {step}"),
1503        },
1504        BarAggregation::Hour => match step {
1505            1 => Ok("1h"),
1506            4 => Ok("4h"),
1507            12 => Ok("12h"),
1508            _ => anyhow::bail!("Unsupported hour step for Kraken Futures: {step}"),
1509        },
1510        BarAggregation::Day => {
1511            if step == 1 {
1512                Ok("1d")
1513            } else {
1514                anyhow::bail!("Unsupported day step for Kraken Futures: {step}")
1515            }
1516        }
1517        BarAggregation::Week => {
1518            if step == 1 {
1519                Ok("1w")
1520            } else {
1521                anyhow::bail!("Unsupported week step for Kraken Futures: {step}")
1522            }
1523        }
1524        other => {
1525            anyhow::bail!("Unsupported bar aggregation for Kraken Futures: {other:?}");
1526        }
1527    }
1528}
1529
1530/// Truncates a `ClientOrderId` for Kraken's `cl_ord_id` field.
1531///
1532/// Kraken accepts three formats:
1533/// - Long UUID (36 chars with hyphens): passed through
1534/// - Short UUID (32 hex chars): passed through
1535/// - Free text: max 18 chars
1536///
1537/// Sequential NautilusTrader IDs (e.g. `O202602270023210040011`) exceed the
1538/// 18-char free-text limit. These are truncated to 'O' + last 17 chars,
1539/// preserving the counter portion for maximum entropy.
1540pub fn truncate_cl_ord_id(client_order_id: &ClientOrderId) -> String {
1541    let id = client_order_id.as_str();
1542
1543    if id.len() <= 18 {
1544        return id.to_string();
1545    }
1546
1547    if id.len() == 36 && id.bytes().filter(|b| *b == b'-').count() == 4 {
1548        return id.to_string();
1549    }
1550
1551    if id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit()) {
1552        return id.to_string();
1553    }
1554
1555    format!("O{}", &id[id.len() - 17..])
1556}
1557
1558#[cfg(test)]
1559mod tests {
1560    use indexmap::IndexMap;
1561    use nautilus_model::{
1562        data::BarSpecification,
1563        enums::{AggregationSource, BarAggregation, OrderSide, OrderStatus, PriceType},
1564        instruments::crypto_perpetual::CryptoPerpetual,
1565    };
1566    use rstest::rstest;
1567
1568    use super::*;
1569    use crate::{
1570        common::enums::{KrakenFuturesOrderEventType, KrakenFuturesOrderStatus, KrakenOrderSide},
1571        http::{
1572            futures::models::{
1573                FuturesFillsResponse, FuturesOpenOrder, FuturesOpenOrdersResponse,
1574                FuturesOrderEvent, FuturesOrdersStatusResponse,
1575            },
1576            models::{
1577                AssetPairsResponse, KrakenResponse, SpotClosedOrdersResult, SpotOpenOrdersResult,
1578            },
1579        },
1580    };
1581
1582    const TS: UnixNanos = UnixNanos::new(1_700_000_000_000_000_000);
1583
1584    fn load_test_json(filename: &str) -> String {
1585        let path = format!("test_data/{filename}");
1586        std::fs::read_to_string(&path)
1587            .unwrap_or_else(|e| panic!("Failed to load test data from {path}: {e}"))
1588    }
1589
1590    /// A futures response can echo a client order ID another tool on the account sent, so an empty
1591    /// or otherwise invalid one names no order rather than failing the parse.
1592    #[rstest]
1593    #[case::valid(Some("O-1"), Some("O-1"))]
1594    #[case::absent(None, None)]
1595    #[case::empty(Some(""), None)]
1596    #[case::whitespace(Some(" "), None)]
1597    #[case::non_ascii(Some("ordre-\u{e9}"), None)]
1598    fn test_echoed_client_order_id(#[case] echoed: Option<&str>, #[case] expected: Option<&str>) {
1599        assert_eq!(
1600            echoed_client_order_id(echoed),
1601            expected.map(ClientOrderId::from)
1602        );
1603    }
1604
1605    #[rstest]
1606    fn test_parse_decimal() {
1607        assert_eq!(parse_decimal("123.45").unwrap(), dec!(123.45));
1608        assert_eq!(parse_decimal("0").unwrap(), dec!(0));
1609        assert_eq!(parse_decimal("").unwrap(), dec!(0));
1610    }
1611
1612    #[rstest]
1613    fn test_parse_decimal_opt() {
1614        assert_eq!(
1615            parse_decimal_opt(Some("123.45")).unwrap(),
1616            Some(dec!(123.45))
1617        );
1618        assert_eq!(parse_decimal_opt(Some("0")).unwrap(), None);
1619        assert_eq!(parse_decimal_opt(Some("")).unwrap(), None);
1620        assert_eq!(parse_decimal_opt(None).unwrap(), None);
1621    }
1622
1623    #[rstest]
1624    fn test_parse_spot_instrument() {
1625        let json = load_test_json("http_asset_pairs.json");
1626        let response: KrakenResponse<AssetPairsResponse> = serde_json::from_str(&json).unwrap();
1627        let pairs = response.result.unwrap();
1628
1629        let (pair_name, definition) = pairs.iter().next().unwrap();
1630
1631        let instrument = parse_spot_instrument(pair_name, definition, TS, TS).unwrap();
1632
1633        match instrument {
1634            InstrumentAny::CurrencyPair(pair) => {
1635                assert_eq!(pair.id.venue.as_str(), "KRAKEN");
1636                assert_eq!(pair.base_currency.code, "BTC");
1637                assert_eq!(pair.quote_currency.code, "USDT");
1638                assert_eq!(pair.price_increment.as_decimal(), dec!(0.1));
1639                assert_eq!(pair.size_increment.as_decimal(), dec!(0.00000001));
1640                assert!(pair.min_quantity.is_some());
1641                assert_eq!(pair.margin_init, dec!(0));
1642                assert_eq!(pair.margin_maint, dec!(0));
1643            }
1644            _ => panic!("Expected CurrencyPair"),
1645        }
1646    }
1647
1648    #[rstest]
1649    fn test_parse_futures_instrument_inverse() {
1650        let json = load_test_json("http_futures_instruments.json");
1651        let response: crate::http::models::FuturesInstrumentsResponse =
1652            serde_json::from_str(&json).unwrap();
1653
1654        let fut_instrument = &response.instruments[0];
1655
1656        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1657
1658        match instrument {
1659            InstrumentAny::CryptoPerpetual(perp) => {
1660                assert_eq!(perp.id.venue.as_str(), "KRAKEN");
1661                assert_eq!(perp.id.symbol.as_str(), "PI_XBTUSD");
1662                assert_eq!(perp.raw_symbol.as_str(), "PI_XBTUSD");
1663                assert_eq!(perp.base_currency.code, "BTC");
1664                assert_eq!(perp.quote_currency.code, "USD");
1665                assert_eq!(perp.settlement_currency.code, "BTC");
1666                assert!(perp.is_inverse);
1667                assert_eq!(perp.price_increment.as_decimal(), dec!(0.5));
1668                assert_eq!(perp.size_increment.as_decimal(), dec!(1));
1669                assert_eq!(perp.size_precision(), 0);
1670                assert_eq!(perp.margin_init, dec!(0.02));
1671                assert_eq!(perp.margin_maint, dec!(0.01));
1672            }
1673            _ => panic!("Expected CryptoPerpetual"),
1674        }
1675    }
1676
1677    #[rstest]
1678    fn test_parse_futures_instrument_flexible() {
1679        let json = load_test_json("http_futures_instruments.json");
1680        let response: crate::http::models::FuturesInstrumentsResponse =
1681            serde_json::from_str(&json).unwrap();
1682
1683        let fut_instrument = &response.instruments[1];
1684
1685        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1686
1687        match instrument {
1688            InstrumentAny::CryptoPerpetual(perp) => {
1689                assert_eq!(perp.id.venue.as_str(), "KRAKEN");
1690                assert_eq!(perp.id.symbol.as_str(), "PF_ETHUSD");
1691                assert_eq!(perp.raw_symbol.as_str(), "PF_ETHUSD");
1692                assert_eq!(perp.base_currency.code, "ETH");
1693                assert_eq!(perp.quote_currency.code, "USD");
1694                assert_eq!(perp.settlement_currency.code, "USD");
1695                assert!(!perp.is_inverse);
1696                assert_eq!(perp.price_increment.as_decimal(), dec!(0.1));
1697                assert_eq!(perp.size_increment.as_decimal(), dec!(0.001));
1698                assert_eq!(perp.size_precision(), 3);
1699                assert_eq!(perp.margin_init, dec!(0.02));
1700                assert_eq!(perp.margin_maint, dec!(0.01));
1701            }
1702            _ => panic!("Expected CryptoPerpetual"),
1703        }
1704    }
1705
1706    #[rstest]
1707    fn test_parse_futures_instrument_accepts_max_precision() {
1708        let json = load_test_json("http_futures_instruments.json");
1709        let response: crate::http::models::FuturesInstrumentsResponse =
1710            serde_json::from_str(&json).unwrap();
1711        let mut fut_instrument = response.instruments[1].clone();
1712        let tick_size = Decimal::try_new(1, u32::from(FIXED_PRECISION)).unwrap();
1713        fut_instrument.tick_size = tick_size;
1714
1715        let instrument = parse_futures_instrument(&fut_instrument, TS, TS).unwrap();
1716
1717        match instrument {
1718            InstrumentAny::CryptoPerpetual(perp) => {
1719                assert_eq!(perp.price_precision(), FIXED_PRECISION);
1720                assert_eq!(perp.price_increment.as_decimal(), tick_size);
1721            }
1722            _ => panic!("Expected CryptoPerpetual"),
1723        }
1724    }
1725
1726    #[cfg(feature = "high-precision")]
1727    #[rstest]
1728    fn test_parse_futures_instrument_negative_precision() {
1729        let json = load_test_json("http_futures_instruments.json");
1730        let response: crate::http::models::FuturesInstrumentsResponse =
1731            serde_json::from_str(&json).unwrap();
1732
1733        // PF_PEPEUSD has contractValueTradePrecision: -3 (trades in multiples of 1000)
1734        let fut_instrument = &response.instruments[2];
1735
1736        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1737
1738        match instrument {
1739            InstrumentAny::CryptoPerpetual(perp) => {
1740                assert_eq!(perp.id.symbol.as_str(), "PF_PEPEUSD");
1741                assert_eq!(perp.base_currency.code, "PEPE");
1742                assert!(!perp.is_inverse);
1743                assert_eq!(perp.size_increment.as_decimal(), dec!(1000));
1744                assert_eq!(perp.size_precision(), 0);
1745            }
1746            _ => panic!("Expected CryptoPerpetual"),
1747        }
1748    }
1749
1750    #[cfg(feature = "high-precision")]
1751    #[rstest]
1752    fn test_parse_futures_instrument_rejects_precision_above_high_max() {
1753        let json = load_test_json("http_futures_instruments.json");
1754        let response: crate::http::models::FuturesInstrumentsResponse =
1755            serde_json::from_str(&json).unwrap();
1756        let mut fut_instrument = response.instruments[1].clone();
1757        fut_instrument.tick_size = dec!(0.00000000000000001);
1758
1759        let error = parse_futures_instrument(&fut_instrument, TS, TS).unwrap_err();
1760
1761        assert_eq!(
1762            error.to_string(),
1763            "Cannot parse Kraken Futures instrument 'PF_ETHUSD': tick_size \
1764             0.00000000000000001 requires precision 17, but this build supports at most 16"
1765        );
1766    }
1767
1768    #[cfg(not(feature = "high-precision"))]
1769    #[rstest]
1770    fn test_parse_futures_instrument_rejects_unsupported_precision() {
1771        let json = load_test_json("http_futures_instruments.json");
1772        let response: crate::http::models::FuturesInstrumentsResponse =
1773            serde_json::from_str(&json).unwrap();
1774
1775        let tick_error = parse_futures_instrument(&response.instruments[2], TS, TS).unwrap_err();
1776
1777        let mut trade_precision_instrument = response.instruments[1].clone();
1778        trade_precision_instrument.contract_value_trade_precision = 256;
1779        let trade_precision_error =
1780            parse_futures_instrument(&trade_precision_instrument, TS, TS).unwrap_err();
1781
1782        let mut contract_size_instrument = response.instruments[1].clone();
1783        contract_size_instrument.contract_size = dec!(0.0000000001);
1784        let contract_size_error =
1785            parse_futures_instrument(&contract_size_instrument, TS, TS).unwrap_err();
1786
1787        assert_eq!(
1788            tick_error.to_string(),
1789            "Cannot parse Kraken Futures instrument 'PF_PEPEUSD': tick_size 0.0000000001 requires \
1790             precision 10, but this build supports at most 9; enable the 'high-precision' Cargo \
1791             feature and rebuild"
1792        );
1793        assert_eq!(
1794            trade_precision_error.to_string(),
1795            "Cannot parse Kraken Futures instrument 'PF_ETHUSD': contract_value_trade_precision 256 \
1796             requires precision 256, but this build supports at most 9; enable the 'high-precision' \
1797             Cargo feature and rebuild"
1798        );
1799        assert_eq!(
1800            contract_size_error.to_string(),
1801            "Cannot parse Kraken Futures instrument 'PF_ETHUSD': contract_size 0.0000000001 requires \
1802             precision 10, but this build supports at most 9; enable the 'high-precision' Cargo \
1803             feature and rebuild"
1804        );
1805    }
1806
1807    #[rstest]
1808    fn test_parse_futures_instrument_tokenized_underlying() {
1809        let json = load_test_json("http_futures_instruments.json");
1810        let response: crate::http::models::FuturesInstrumentsResponse =
1811            serde_json::from_str(&json).unwrap();
1812
1813        let fut_instrument = &response.instruments[3];
1814
1815        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1816
1817        match instrument {
1818            InstrumentAny::CryptoPerpetual(perp) => {
1819                assert_eq!(perp.id.symbol.as_str(), "PF_AAPLxUSD");
1820                assert_eq!(perp.raw_symbol.as_str(), "PF_AAPLxUSD");
1821                assert_eq!(perp.base_currency.code, "AAPLx");
1822                assert_eq!(perp.quote_currency.code, "USD");
1823                assert_eq!(perp.settlement_currency.code, "USD");
1824                assert!(!perp.is_inverse);
1825                assert_eq!(perp.price_increment.as_decimal(), dec!(0.01));
1826                assert_eq!(perp.size_increment.as_decimal(), dec!(0.01));
1827                assert_eq!(perp.size_precision(), 2);
1828                assert_eq!(perp.margin_init, dec!(0.2));
1829                assert_eq!(perp.margin_maint, dec!(0.1));
1830            }
1831            _ => panic!("Expected CryptoPerpetual"),
1832        }
1833    }
1834
1835    #[rstest]
1836    fn test_parse_futures_instrument_without_fee_schedule_uid() {
1837        let json = load_test_json("http_futures_instrument_no_fee_schedule.json");
1838        let response: crate::http::models::FuturesInstrumentsResponse =
1839            serde_json::from_str(&json).unwrap();
1840
1841        let fut_instrument = &response.instruments[0];
1842        assert!(fut_instrument.fee_schedule_uid.is_none());
1843
1844        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1845        match instrument {
1846            InstrumentAny::CryptoPerpetual(perp) => {
1847                assert_eq!(perp.id.symbol.as_str(), "PF_ETHUSD");
1848            }
1849            _ => panic!("Expected CryptoPerpetual"),
1850        }
1851    }
1852
1853    #[rstest]
1854    fn test_parse_trade_tick_from_array() {
1855        let json = load_test_json("http_trades.json");
1856        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
1857        let result = wrapper.get("result").unwrap();
1858        let trades_map = result.as_object().unwrap();
1859
1860        // Get first pair's trades
1861        let (_pair, trades_value) = trades_map.iter().find(|(k, _)| *k != "last").unwrap();
1862        let trades = trades_value.as_array().unwrap();
1863        let trade_array = trades[0].as_array().unwrap();
1864
1865        // Create a mock instrument for testing
1866        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
1867        let instrument = InstrumentAny::CurrencyPair(
1868            CurrencyPair::builder()
1869                .instrument_id(instrument_id)
1870                .raw_symbol(Symbol::new("XBTUSDT"))
1871                .base_currency(Currency::BTC())
1872                .quote_currency(Currency::USDT())
1873                .price_precision(1)
1874                .size_precision(8)
1875                .price_increment(Price::from("0.1"))
1876                .size_increment(Quantity::from("0.00000001"))
1877                .ts_event(TS)
1878                .ts_init(TS)
1879                .build()
1880                .unwrap(),
1881        );
1882
1883        let trade_tick = parse_trade_tick_from_array(trade_array, &instrument, TS).unwrap();
1884
1885        assert_eq!(trade_tick.instrument_id, instrument_id);
1886        assert_eq!(trade_tick.price, Price::from("105433.60000"));
1887        assert_eq!(trade_tick.size, Quantity::from("0.00027625"));
1888    }
1889
1890    #[rstest]
1891    fn test_parse_bar() {
1892        let json = load_test_json("http_ohlc.json");
1893        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
1894        let result = wrapper.get("result").unwrap();
1895        let ohlc_map = result.as_object().unwrap();
1896
1897        // Get first pair's OHLC data
1898        let (_pair, ohlc_value) = ohlc_map.iter().find(|(k, _)| *k != "last").unwrap();
1899        let ohlcs = ohlc_value.as_array().unwrap();
1900
1901        // Parse first OHLC array into OhlcData
1902        let ohlc_array = ohlcs[0].as_array().unwrap();
1903        let ohlc = OhlcData {
1904            time: ohlc_array[0].as_i64().unwrap(),
1905            open: ohlc_array[1].as_str().unwrap().to_string(),
1906            high: ohlc_array[2].as_str().unwrap().to_string(),
1907            low: ohlc_array[3].as_str().unwrap().to_string(),
1908            close: ohlc_array[4].as_str().unwrap().to_string(),
1909            vwap: ohlc_array[5].as_str().unwrap().to_string(),
1910            volume: ohlc_array[6].as_str().unwrap().to_string(),
1911            count: ohlc_array[7].as_i64().unwrap(),
1912        };
1913
1914        // Create a mock instrument
1915        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
1916        let instrument = InstrumentAny::CurrencyPair(
1917            CurrencyPair::builder()
1918                .instrument_id(instrument_id)
1919                .raw_symbol(Symbol::new("XBTUSDT"))
1920                .base_currency(Currency::BTC())
1921                .quote_currency(Currency::USDT())
1922                .price_precision(1)
1923                .size_precision(8)
1924                .price_increment(Price::from("0.1"))
1925                .size_increment(Quantity::from("0.00000001"))
1926                .ts_event(TS)
1927                .ts_init(TS)
1928                .build()
1929                .unwrap(),
1930        );
1931
1932        let bar_type = BarType::new(
1933            instrument_id,
1934            BarSpecification::new(1, BarAggregation::Minute, PriceType::Last),
1935            AggregationSource::External,
1936        );
1937
1938        let bar = parse_bar(&ohlc, &instrument, bar_type, TS).unwrap();
1939
1940        assert_eq!(bar.bar_type, bar_type);
1941        assert_eq!(bar.open, Price::from("106038.2"));
1942        assert_eq!(bar.high, Price::from("106038.2"));
1943        assert_eq!(bar.low, Price::from("106038.2"));
1944        assert_eq!(bar.close, Price::from("106038.2"));
1945        assert_eq!(bar.volume, Quantity::from("0.00000000"));
1946    }
1947
1948    #[rstest]
1949    fn test_parse_millis_timestamp() {
1950        let timestamp = 1762795433.9717445;
1951        let result = parse_millis_timestamp(timestamp, "test").unwrap();
1952        assert!(result.as_u64() > 0);
1953    }
1954
1955    #[rstest]
1956    #[case(1, BarAggregation::Minute, 1)]
1957    #[case(5, BarAggregation::Minute, 5)]
1958    #[case(15, BarAggregation::Minute, 15)]
1959    #[case(1, BarAggregation::Hour, 60)]
1960    #[case(4, BarAggregation::Hour, 240)]
1961    #[case(1, BarAggregation::Day, 1440)]
1962    fn test_bar_type_to_spot_interval(
1963        #[case] step: usize,
1964        #[case] aggregation: BarAggregation,
1965        #[case] expected: u32,
1966    ) {
1967        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
1968        let bar_type = BarType::new(
1969            instrument_id,
1970            BarSpecification::new(step, aggregation, PriceType::Last),
1971            AggregationSource::External,
1972        );
1973
1974        let result = bar_type_to_spot_interval(bar_type).unwrap();
1975        assert_eq!(result, expected);
1976    }
1977
1978    #[rstest]
1979    fn test_bar_type_to_spot_interval_unsupported() {
1980        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
1981        let bar_type = BarType::new(
1982            instrument_id,
1983            BarSpecification::new(1, BarAggregation::Second, PriceType::Last),
1984            AggregationSource::External,
1985        );
1986
1987        let result = bar_type_to_spot_interval(bar_type);
1988        assert!(result.is_err());
1989        assert!(result.unwrap_err().to_string().contains("Unsupported"));
1990    }
1991
1992    #[rstest]
1993    #[case(1, BarAggregation::Minute, "1m")]
1994    #[case(5, BarAggregation::Minute, "5m")]
1995    #[case(15, BarAggregation::Minute, "15m")]
1996    #[case(1, BarAggregation::Hour, "1h")]
1997    #[case(4, BarAggregation::Hour, "4h")]
1998    #[case(12, BarAggregation::Hour, "12h")]
1999    #[case(1, BarAggregation::Day, "1d")]
2000    #[case(1, BarAggregation::Week, "1w")]
2001    fn test_bar_type_to_futures_resolution(
2002        #[case] step: usize,
2003        #[case] aggregation: BarAggregation,
2004        #[case] expected: &str,
2005    ) {
2006        let instrument_id = InstrumentId::new(Symbol::new("PI_XBTUSD"), *KRAKEN_VENUE);
2007        let bar_type = BarType::new(
2008            instrument_id,
2009            BarSpecification::new(step, aggregation, PriceType::Last),
2010            AggregationSource::External,
2011        );
2012
2013        let result = bar_type_to_futures_resolution(bar_type).unwrap();
2014        assert_eq!(result, expected);
2015    }
2016
2017    #[rstest]
2018    #[case(30, BarAggregation::Minute)] // Unsupported minute step
2019    #[case(2, BarAggregation::Hour)] // Unsupported hour step
2020    #[case(2, BarAggregation::Day)] // Unsupported day step
2021    #[case(1, BarAggregation::Second)] // Unsupported aggregation
2022    fn test_bar_type_to_futures_resolution_unsupported(
2023        #[case] step: usize,
2024        #[case] aggregation: BarAggregation,
2025    ) {
2026        let instrument_id = InstrumentId::new(Symbol::new("PI_XBTUSD"), *KRAKEN_VENUE);
2027        let bar_type = BarType::new(
2028            instrument_id,
2029            BarSpecification::new(step, aggregation, PriceType::Last),
2030            AggregationSource::External,
2031        );
2032
2033        let result = bar_type_to_futures_resolution(bar_type);
2034        assert!(result.is_err());
2035        assert!(result.unwrap_err().to_string().contains("Unsupported"));
2036    }
2037
2038    #[rstest]
2039    fn test_parse_order_status_report() {
2040        let json = load_test_json("http_open_orders.json");
2041        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
2042        let result = wrapper.get("result").unwrap();
2043        let open_map = result.get("open").unwrap();
2044        let orders: IndexMap<String, SpotOrder> = serde_json::from_value(open_map.clone()).unwrap();
2045
2046        let account_id = AccountId::new("KRAKEN-001");
2047        let instrument_id = InstrumentId::new(Symbol::new("BTC/USDT"), *KRAKEN_VENUE);
2048        let instrument = InstrumentAny::CurrencyPair(
2049            CurrencyPair::builder()
2050                .instrument_id(instrument_id)
2051                .raw_symbol(Symbol::new("XBTUSDT"))
2052                .base_currency(Currency::BTC())
2053                .quote_currency(Currency::USDT())
2054                .price_precision(2)
2055                .size_precision(8)
2056                .price_increment(Price::from("0.01"))
2057                .size_increment(Quantity::from("0.00000001"))
2058                .ts_event(TS)
2059                .ts_init(TS)
2060                .build()
2061                .unwrap(),
2062        );
2063
2064        let (order_id, order) = orders.iter().next().unwrap();
2065
2066        let report =
2067            parse_order_status_report(order_id, order, &instrument, account_id, TS).unwrap();
2068
2069        assert_eq!(report.account_id, account_id);
2070        assert_eq!(report.instrument_id, instrument_id);
2071        assert_eq!(report.venue_order_id.as_str(), order_id);
2072        assert_eq!(report.order_status, OrderStatus::Accepted);
2073        assert_eq!(report.quantity, Quantity::from("0.50000000"));
2074    }
2075
2076    /// An order ID with the price, trigger price and average fill price its report carries.
2077    type ExpectedPrices<'a> = (&'a str, Option<&'a str>, Option<&'a str>, Option<Decimal>);
2078
2079    /// A spot report carries the order's own prices, never the row's top-level `price`, which is
2080    /// the average fill price. The limit comes from `descr.price` for a limit order and from
2081    /// `descr.price2` for a stop-loss-limit or take-profit-limit order, or a trailing-stop-limit
2082    /// order once `misc` marks it `stopped`; a trailing-stop-limit's `limitprice`, the peak price,
2083    /// never stands in. The trigger comes from `stopprice`, which a non-trailing order fills only
2084    /// once triggered, so `descr.price` stands in before. Each row is a Kraken response listed in
2085    /// `test_data/README.md`.
2086    #[rstest]
2087    #[case::untriggered_open_orders(
2088        "http_open_orders_conditional.json",
2089        usdc_eur_instrument(),
2090        &[
2091            ("OCAP01-STOPL-000001", None, Some("1.3403"), None),
2092            ("OCAP02-STOPL-000002", None, Some("1.3402"), None),
2093            ("OCAP03-TAKEP-000003", None, Some("0.4467"), None),
2094            ("OCAP04-STLMT-000004", Some("1.3403"), Some("1.3403"), None),
2095            ("OCAP05-TPLMT-000005", Some("0.4467"), Some("0.4467"), None),
2096            ("OCAP06-TRAIL-000006", None, Some("1.3402"), None),
2097            ("OCAP07-TRLMT-000007", None, Some("1.3402"), None),
2098            ("OCAP08-LIMIT-000008", Some("0.4467"), None, None),
2099        ]
2100    )]
2101    #[case::untriggered_canceled_orders_one_amended(
2102        "http_closed_orders_conditional_canceled.json",
2103        usdc_eur_instrument(),
2104        &[
2105            ("OCAP01-STOPL-000001", None, Some("1.4296"), None),
2106            ("OCAP02-STOPL-000002", None, Some("1.3402"), None),
2107            ("OCAP03-TAKEP-000003", None, Some("0.4467"), None),
2108            ("OCAP04-STLMT-000004", Some("1.3403"), Some("1.3403"), None),
2109            ("OCAP05-TPLMT-000005", Some("0.4467"), Some("0.4467"), None),
2110            ("OCAP06-TRAIL-000006", None, Some("1.3401"), None),
2111            ("OCAP07-TRLMT-000007", None, Some("1.3401"), None),
2112            ("OCAP08-LIMIT-000008", Some("0.4467"), None, None),
2113        ]
2114    )]
2115    #[case::canceled_orders_three_triggered(
2116        "http_closed_orders_conditional_triggered.json",
2117        usdc_eur_instrument(),
2118        &[
2119            ("OCAP09-STLMT-000009", Some("0.4464"), Some("1.3394"), None),
2120            // The two take-profit-limit rows violate the LimitIfTouched relation, so the
2121            // rejection tests below assert them instead of this priced table.
2122            ("OCAP11-STLMT-000011", Some("0.4464"), Some("0.8929"), None),
2123            ("OCAP13-TRLMT-000013", Some("0.4465"), Some("0.8930"), None),
2124        ]
2125    )]
2126    #[case::documented_open_limit_orders(
2127        "http_open_orders_doc_example.json",
2128        xbt_usd_instrument(),
2129        &[
2130            ("OQCLML-BW3P3-BUCMWZ", Some("30010.0"), None, Some(dec!(11253.7) / dec!(0.375))),
2131            ("OB5VMB-B4U2U-DK2WRW", Some("14500.0"), None, None),
2132        ]
2133    )]
2134    #[case::documented_filled_market_order(
2135        "http_query_orders_doc_example.json",
2136        xbt_usd_instrument(),
2137        &[("OMMDB2-FSB6Z-7W3HPO", None, None, Some(dec!(30000)))]
2138    )]
2139    fn test_parse_order_status_report_prices_the_order_from_its_own_fields(
2140        #[case] filename: &str,
2141        #[case] instrument: InstrumentAny,
2142        #[case] expected: &[ExpectedPrices],
2143    ) {
2144        let rows = spot_order_rows(filename);
2145
2146        for &(order_id, expected_price, expected_trigger_price, expected_avg_px) in expected {
2147            let report = parse_order_status_report(
2148                order_id,
2149                &rows[order_id],
2150                &instrument,
2151                AccountId::new("KRAKEN-001"),
2152                TS,
2153            )
2154            .unwrap();
2155
2156            assert_eq!(report.price, expected_price.map(Price::from), "{order_id}");
2157            assert_eq!(
2158                report.trigger_price,
2159                expected_trigger_price.map(Price::from),
2160                "{order_id}"
2161            );
2162            assert_eq!(report.avg_px, expected_avg_px, "{order_id}");
2163        }
2164    }
2165
2166    /// A description price that is neither a price nor a relative expression fails the row. The
2167    /// input is synthetic: a captured limit row with its `descr.price` replaced.
2168    #[rstest]
2169    fn test_parse_order_status_report_fails_on_a_malformed_order_price() {
2170        let order_id = "OCAP08-LIMIT-000008";
2171        let mut order = spot_order_rows("http_open_orders_conditional.json")
2172            .swap_remove(order_id)
2173            .unwrap();
2174        order.descr.price = "abc".to_string();
2175
2176        let result = parse_order_status_report(
2177            order_id,
2178            &order,
2179            &usdc_eur_instrument(),
2180            AccountId::new("KRAKEN-001"),
2181            TS,
2182        );
2183
2184        assert!(result.is_err(), "{result:?}");
2185    }
2186
2187    /// An empty price or a relative expression reads as none rather than failing the row. The
2188    /// inputs are synthetic: a captured stop-loss row with its `stopprice` replaced, so
2189    /// `descr.price` stands in.
2190    #[rstest]
2191    #[case::empty("")]
2192    #[case::relative("+1.5%")]
2193    fn test_parse_order_status_report_reads_an_unpriced_stop_price_as_none(
2194        #[case] stop_price: &str,
2195    ) {
2196        let order_id = "OCAP02-STOPL-000002";
2197        let mut order = spot_order_rows("http_open_orders_conditional.json")
2198            .swap_remove(order_id)
2199            .unwrap();
2200        order.stopprice = Some(stop_price.to_string());
2201
2202        let report = parse_order_status_report(
2203            order_id,
2204            &order,
2205            &usdc_eur_instrument(),
2206            AccountId::new("KRAKEN-001"),
2207            TS,
2208        )
2209        .unwrap();
2210
2211        assert_eq!(report.trigger_price, Some(Price::from("1.3402")));
2212    }
2213
2214    /// An untriggered trailing-stop-limit carries no price whatever its `descr.price2` holds, so an
2215    /// unsigned offset, the form Nautilus submits, never reads as its limit. The input is
2216    /// synthetic: a captured untriggered row with its offset written unsigned.
2217    #[rstest]
2218    fn test_parse_order_status_report_prices_no_untriggered_trailing_stop_limit() {
2219        let order_id = "OCAP07-TRLMT-000007";
2220        let mut order = spot_order_rows("http_open_orders_conditional.json")
2221            .swap_remove(order_id)
2222            .unwrap();
2223        order.descr.price2 = "1.0000".to_string();
2224
2225        let report = parse_order_status_report(
2226            order_id,
2227            &order,
2228            &usdc_eur_instrument(),
2229            AccountId::new("KRAKEN-001"),
2230            TS,
2231        )
2232        .unwrap();
2233
2234        assert_eq!(report.price, None);
2235        assert_eq!(report.trigger_price, Some(Price::from("1.3402")));
2236    }
2237
2238    /// A buy take-profit-limit with its trigger above its limit cannot be a LimitIfTouched, so
2239    /// the row fails naming both prices instead of reaching reconciliation, where the manager
2240    /// would drop it without naming the order. Both inputs are captured rows, one triggered and
2241    /// one canceled untriggered.
2242    #[rstest]
2243    #[case::triggered(
2244        "OCAP12-TPLMT-000012",
2245        "Buy take-profit-limit with trigger price 0.8929 above limit price 0.4464 cannot be represented as LimitIfTouched"
2246    )]
2247    #[case::untriggered(
2248        "OCAP10-TPLMT-000010",
2249        "Buy take-profit-limit with trigger price 0.4465 above limit price 0.4455 cannot be represented as LimitIfTouched"
2250    )]
2251    fn test_parse_order_status_report_rejects_a_take_profit_limit_buy_with_trigger_above_limit(
2252        #[case] order_id: &str,
2253        #[case] expected: &str,
2254    ) {
2255        let order = spot_order_rows("http_closed_orders_conditional_triggered.json")
2256            .swap_remove(order_id)
2257            .unwrap();
2258
2259        let error = parse_order_status_report(
2260            order_id,
2261            &order,
2262            &usdc_eur_instrument(),
2263            AccountId::new("KRAKEN-001"),
2264            TS,
2265        )
2266        .unwrap_err();
2267
2268        assert_eq!(error.to_string(), expected);
2269    }
2270
2271    /// The sell mirror: a take-profit-limit with its trigger below its limit likewise violates
2272    /// the LimitIfTouched relation. The input is synthetic: a captured triggered row with its
2273    /// side flipped and its trigger and limit exchanged.
2274    #[rstest]
2275    fn test_parse_order_status_report_rejects_a_take_profit_limit_sell_with_trigger_below_limit() {
2276        let order_id = "OCAP12-TPLMT-000012";
2277        let mut order = spot_order_rows("http_closed_orders_conditional_triggered.json")
2278            .swap_remove(order_id)
2279            .unwrap();
2280        order.descr.order_side = KrakenOrderSide::Sell;
2281        order.descr.price = "0.4464".to_string();
2282        order.descr.price2 = "0.8929".to_string();
2283        order.stopprice = Some("0.44640000".to_string());
2284        order.limitprice = Some("0.89290000".to_string());
2285
2286        let error = parse_order_status_report(
2287            order_id,
2288            &order,
2289            &usdc_eur_instrument(),
2290            AccountId::new("KRAKEN-001"),
2291            TS,
2292        )
2293        .unwrap_err();
2294
2295        assert_eq!(
2296            error.to_string(),
2297            "Sell take-profit-limit with trigger price 0.4464 below limit price 0.8929 cannot be represented as LimitIfTouched"
2298        );
2299    }
2300
2301    /// A sell take-profit-limit with its trigger at its limit satisfies the LimitIfTouched
2302    /// relation, so the row parses. The input is synthetic: a captured triggered row with its
2303    /// side flipped and both prices at the captured limit.
2304    #[rstest]
2305    fn test_parse_order_status_report_prices_a_take_profit_limit_sell_with_trigger_at_limit() {
2306        let order_id = "OCAP12-TPLMT-000012";
2307        let mut order = spot_order_rows("http_closed_orders_conditional_triggered.json")
2308            .swap_remove(order_id)
2309            .unwrap();
2310        order.descr.order_side = KrakenOrderSide::Sell;
2311        order.descr.price = "0.4464".to_string();
2312        order.descr.price2 = "0.4464".to_string();
2313        order.stopprice = Some("0.44640000".to_string());
2314        order.limitprice = Some("0.44640000".to_string());
2315
2316        let report = parse_order_status_report(
2317            order_id,
2318            &order,
2319            &usdc_eur_instrument(),
2320            AccountId::new("KRAKEN-001"),
2321            TS,
2322        )
2323        .unwrap();
2324
2325        assert_eq!(report.order_type, OrderType::LimitIfTouched);
2326        assert_eq!(report.price, Some(Price::from("0.4464")));
2327        assert_eq!(report.trigger_price, Some(Price::from("0.4464")));
2328    }
2329
2330    /// The rows of a spot OpenOrders, ClosedOrders or QueryOrders response in `test_data`.
2331    fn spot_order_rows(filename: &str) -> IndexMap<String, SpotOrder> {
2332        let json = load_test_json(filename);
2333        if filename.starts_with("http_open_orders") {
2334            let response: KrakenResponse<SpotOpenOrdersResult> =
2335                serde_json::from_str(&json).unwrap();
2336            response.result.unwrap().open
2337        } else if filename.starts_with("http_closed_orders") {
2338            let response: KrakenResponse<SpotClosedOrdersResult> =
2339                serde_json::from_str(&json).unwrap();
2340            response.result.unwrap().closed
2341        } else {
2342            let response: KrakenResponse<IndexMap<String, SpotOrder>> =
2343                serde_json::from_str(&json).unwrap();
2344            response.result.unwrap()
2345        }
2346    }
2347
2348    fn usdc_eur_instrument() -> InstrumentAny {
2349        InstrumentAny::CurrencyPair(
2350            CurrencyPair::builder()
2351                .instrument_id(InstrumentId::new(Symbol::new("USDC/EUR"), *KRAKEN_VENUE))
2352                .raw_symbol(Symbol::new("USDCEUR"))
2353                .base_currency(Currency::USDC())
2354                .quote_currency(Currency::EUR())
2355                .price_precision(4)
2356                .size_precision(8)
2357                .price_increment(Price::from("0.0001"))
2358                .size_increment(Quantity::from("0.00000001"))
2359                .ts_event(TS)
2360                .ts_init(TS)
2361                .build()
2362                .unwrap(),
2363        )
2364    }
2365
2366    fn xbt_usd_instrument() -> InstrumentAny {
2367        InstrumentAny::CurrencyPair(
2368            CurrencyPair::builder()
2369                .instrument_id(InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE))
2370                .raw_symbol(Symbol::new("XBTUSD"))
2371                .base_currency(Currency::BTC())
2372                .quote_currency(Currency::USD())
2373                .price_precision(1)
2374                .size_precision(8)
2375                .price_increment(Price::from("0.1"))
2376                .size_increment(Quantity::from("0.00000001"))
2377                .ts_event(TS)
2378                .ts_init(TS)
2379                .build()
2380                .unwrap(),
2381        )
2382    }
2383
2384    fn create_mock_perp() -> InstrumentAny {
2385        let instrument_id = InstrumentId::new(Symbol::new("PI_XBTUSD"), *KRAKEN_VENUE);
2386        InstrumentAny::CryptoPerpetual(
2387            CryptoPerpetual::builder()
2388                .instrument_id(instrument_id)
2389                .raw_symbol(Symbol::new("PI_XBTUSD"))
2390                .base_currency(Currency::BTC())
2391                .quote_currency(Currency::USD())
2392                .settlement_currency(Currency::USD())
2393                .is_inverse(false)
2394                .price_precision(1)
2395                .size_precision(0)
2396                .price_increment(Price::from("0.5"))
2397                .size_increment(Quantity::from("1"))
2398                .ts_event(TS)
2399                .ts_init(TS)
2400                .build()
2401                .unwrap(),
2402        )
2403    }
2404
2405    #[rstest]
2406    fn test_parse_futures_assignee_fill_report() {
2407        let json = load_test_json("http_futures_fills.json");
2408        let response: FuturesFillsResponse = serde_json::from_str(&json).unwrap();
2409        let fill = &response.fills[2];
2410        let instrument = create_mock_perp();
2411        let account_id = AccountId::new("KRAKEN-001");
2412
2413        let report = parse_futures_fill_report(fill, &instrument, account_id, TS).unwrap();
2414
2415        assert_eq!(report.account_id, account_id);
2416        assert_eq!(report.instrument_id, instrument.id());
2417        assert_eq!(
2418            report.venue_order_id,
2419            VenueOrderId::new("f8a7b6c5-d4e3-2f1a-0b9c-8d7e6f5a4b3c")
2420        );
2421        assert_eq!(
2422            report.trade_id,
2423            TradeId::new("d3f4e5a6-b7c8-9d0e-1f2a-3b4c5d6e7f8a")
2424        );
2425        assert_eq!(report.order_side, OrderSide::Sell);
2426        assert_eq!(report.last_qty, Quantity::from("2500"));
2427        assert_eq!(report.last_px, Price::from("28050.0"));
2428        assert_eq!(report.commission, Money::zero(Currency::USD()));
2429        assert_eq!(report.liquidity_side, LiquiditySide::NoLiquiditySide);
2430        assert_eq!(report.avg_px, None);
2431        assert_eq!(
2432            report.ts_event,
2433            "2023-04-07T15:55:20.123Z".parse::<UnixNanos>().unwrap()
2434        );
2435        assert_eq!(report.ts_init, TS);
2436        assert_eq!(report.client_order_id, None);
2437        assert_eq!(report.venue_position_id, None);
2438    }
2439
2440    #[rstest]
2441    fn test_parse_venue_order_id_returns_a_valid_id() {
2442        assert_eq!(
2443            parse_venue_order_id("OABCDE-12345-FGHIJ", "spot order").unwrap(),
2444            VenueOrderId::new("OABCDE-12345-FGHIJ")
2445        );
2446    }
2447
2448    /// An order ID the model cannot hold is an error, whichever way it is invalid: the panicking
2449    /// constructor would abort a release build. The error names the payload the caller gives.
2450    #[rstest]
2451    #[case::empty("")]
2452    #[case::whitespace("   ")]
2453    #[case::non_ascii("\u{e9}")]
2454    fn test_parse_venue_order_id_fails_on_an_invalid_id(#[case] order_id: &str) {
2455        let fill_id = "F-1";
2456
2457        let error =
2458            parse_venue_order_id(order_id, format_args!("futures fill {fill_id}")).unwrap_err();
2459
2460        assert_eq!(
2461            error.to_string(),
2462            format!("Invalid order_id '{order_id}' in Kraken futures fill F-1")
2463        );
2464    }
2465
2466    #[rstest]
2467    fn test_parse_order_status_report_fails_on_an_invalid_order_id() {
2468        let order = spot_order_rows("http_open_orders_conditional.json")
2469            .swap_remove("OCAP08-LIMIT-000008")
2470            .unwrap();
2471
2472        let error = parse_order_status_report(
2473            "",
2474            &order,
2475            &usdc_eur_instrument(),
2476            AccountId::new("KRAKEN-001"),
2477            TS,
2478        )
2479        .unwrap_err();
2480
2481        assert_eq!(
2482            error.to_string(),
2483            "Invalid order_id '' in Kraken spot order"
2484        );
2485    }
2486
2487    #[rstest]
2488    fn test_parse_fill_report_fails_on_an_invalid_order_id() {
2489        let json = load_test_json("http_trades_history.json");
2490        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
2491        let mut trades: IndexMap<String, SpotTrade> =
2492            serde_json::from_value(wrapper["result"]["trades"].clone()).unwrap();
2493        let (trade_id, trade) = trades.first_mut().unwrap();
2494        trade.ordertxid = String::new();
2495
2496        let error = parse_fill_report(
2497            trade_id,
2498            trade,
2499            &usdc_eur_instrument(),
2500            AccountId::new("KRAKEN-001"),
2501            TS,
2502        )
2503        .unwrap_err();
2504
2505        assert_eq!(
2506            error.to_string(),
2507            "Invalid order_id '' in Kraken spot trade"
2508        );
2509    }
2510
2511    #[rstest]
2512    fn test_parse_futures_order_status_report_fails_on_an_invalid_order_id() {
2513        let json = load_test_json("http_futures_open_orders.json");
2514        let mut response: FuturesOpenOrdersResponse = serde_json::from_str(&json).unwrap();
2515        let mut order = response.open_orders.swap_remove(0);
2516        order.order_id = String::new();
2517
2518        let error = parse_futures_order_status_report(
2519            &order,
2520            &create_mock_perp(),
2521            AccountId::new("KRAKEN-001"),
2522            None,
2523            TS,
2524        )
2525        .unwrap_err();
2526
2527        assert_eq!(
2528            error.to_string(),
2529            "Invalid order_id '' in Kraken futures open order"
2530        );
2531    }
2532
2533    /// The history decoder validates its uid; the post-submit send events reach this parser with
2534    /// an ID nothing has checked.
2535    #[rstest]
2536    fn test_parse_futures_order_event_status_report_fails_on_an_invalid_order_id() {
2537        let event = FuturesOrderEvent {
2538            order_id: String::new(),
2539            cli_ord_id: None,
2540            order_type: KrakenFuturesOrderType::Limit,
2541            symbol: "PI_XBTUSD".to_string(),
2542            side: KrakenOrderSide::Sell,
2543            quantity: dec!(200),
2544            filled: Decimal::ZERO,
2545            limit_price: Some(dec!(39500)),
2546            stop_price: None,
2547            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2548            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2549            reduce_only: false,
2550            time_in_force: TimeInForce::Gtc,
2551            post_only: false,
2552        };
2553
2554        let error = parse_futures_order_event_status_report(
2555            &event,
2556            None,
2557            &create_mock_perp(),
2558            AccountId::new("KRAKEN-001"),
2559            TS,
2560        )
2561        .unwrap_err();
2562
2563        assert_eq!(
2564            error.to_string(),
2565            "Invalid order_id '' in Kraken futures order event"
2566        );
2567    }
2568
2569    #[rstest]
2570    fn test_parse_futures_order_status_details_report_fails_on_an_invalid_order_id() {
2571        let json = load_test_json("http_futures_orders_status.json");
2572        let mut response: FuturesOrdersStatusResponse = serde_json::from_str(&json).unwrap();
2573        let mut details = response.orders.swap_remove(0);
2574        details.order.order_id = String::new();
2575
2576        let error = parse_futures_order_status_details_report(
2577            &details,
2578            &create_mock_perp(),
2579            AccountId::new("KRAKEN-001"),
2580            TS,
2581        )
2582        .unwrap_err();
2583
2584        assert_eq!(
2585            error.to_string(),
2586            "Invalid order_id '' in Kraken futures order status"
2587        );
2588    }
2589
2590    #[rstest]
2591    fn test_parse_futures_fill_report_fails_on_an_invalid_order_id() {
2592        let json = load_test_json("http_futures_fills.json");
2593        let mut response: FuturesFillsResponse = serde_json::from_str(&json).unwrap();
2594        let mut fill = response.fills.swap_remove(0);
2595        fill.order_id = String::new();
2596
2597        let error =
2598            parse_futures_fill_report(&fill, &create_mock_perp(), AccountId::new("KRAKEN-001"), TS)
2599                .unwrap_err();
2600
2601        assert_eq!(
2602            error.to_string(),
2603            "Invalid order_id '' in Kraken futures fill"
2604        );
2605    }
2606
2607    #[rstest]
2608    fn test_parse_futures_order_status_report_market_if_touched() {
2609        let order = FuturesOpenOrder {
2610            order_id: "tp-001".to_string(),
2611            symbol: "PI_XBTUSD".to_string(),
2612            side: KrakenOrderSide::Buy,
2613            order_type: KrakenFuturesOrderType::TakeProfit,
2614            limit_price: None,
2615            stop_price: Some(dec!(36000)),
2616            unfilled_size: Some(dec!(500)),
2617            received_time: "2023-11-14T22:13:20.000Z".to_string(),
2618            status: KrakenFuturesOrderStatus::PartiallyFilled,
2619            filled_size: dec!(25),
2620            reduce_only: Some(true),
2621            last_update_time: "2023-11-14T22:13:20.000Z".to_string(),
2622            trigger_signal: None,
2623            cli_ord_id: Some("my-tp-1".to_string()),
2624            cli_ord_id_snake_case: None,
2625        };
2626        let instrument = create_mock_perp();
2627        let account_id = AccountId::new("KRAKEN-001");
2628
2629        let report =
2630            parse_futures_order_status_report(&order, &instrument, account_id, None, TS).unwrap();
2631
2632        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2633        assert_eq!(report.quantity.as_decimal(), dec!(525));
2634        assert_eq!(report.filled_qty.as_decimal(), dec!(25));
2635        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(36000));
2636        assert!(report.price.is_none());
2637        assert!(report.reduce_only);
2638        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
2639    }
2640
2641    /// The `ioc` and `post` types reach the report as `IOC` and post-only `GTC`, and any other type
2642    /// stays `GTC` and not post-only.
2643    #[rstest]
2644    #[case::limit(KrakenFuturesOrderType::Limit, TimeInForce::Gtc, false)]
2645    #[case::ioc(KrakenFuturesOrderType::Ioc, TimeInForce::Ioc, false)]
2646    #[case::post(KrakenFuturesOrderType::Post, TimeInForce::Gtc, true)]
2647    #[case::stop(KrakenFuturesOrderType::StopLower, TimeInForce::Gtc, false)]
2648    #[case::take_profit(KrakenFuturesOrderType::TakeProfit, TimeInForce::Gtc, false)]
2649    #[case::market(KrakenFuturesOrderType::Market, TimeInForce::Gtc, false)]
2650    #[case::stp(KrakenFuturesOrderType::Stop, TimeInForce::Gtc, false)]
2651    #[case::stop_loss(KrakenFuturesOrderType::StopLoss, TimeInForce::Gtc, false)]
2652    #[case::unknown(KrakenFuturesOrderType::Unknown, TimeInForce::Gtc, false)]
2653    fn test_parse_futures_order_status_report_time_in_force(
2654        #[case] order_type: KrakenFuturesOrderType,
2655        #[case] time_in_force: TimeInForce,
2656        #[case] post_only: bool,
2657    ) {
2658        let order = FuturesOpenOrder {
2659            order_id: "tif-001".to_string(),
2660            symbol: "PI_XBTUSD".to_string(),
2661            side: KrakenOrderSide::Buy,
2662            order_type,
2663            limit_price: Some(dec!(36000)),
2664            stop_price: None,
2665            unfilled_size: Some(dec!(500)),
2666            received_time: "2023-11-14T22:13:20.000Z".to_string(),
2667            status: KrakenFuturesOrderStatus::Untouched,
2668            filled_size: Decimal::ZERO,
2669            reduce_only: Some(false),
2670            last_update_time: "2023-11-14T22:13:20.000Z".to_string(),
2671            trigger_signal: None,
2672            cli_ord_id: None,
2673            cli_ord_id_snake_case: None,
2674        };
2675
2676        let report = parse_futures_order_status_report(
2677            &order,
2678            &create_mock_perp(),
2679            AccountId::new("KRAKEN-001"),
2680            None,
2681            TS,
2682        )
2683        .unwrap();
2684
2685        assert_eq!(report.time_in_force, time_in_force);
2686        assert_eq!(report.post_only, post_only);
2687    }
2688
2689    #[rstest]
2690    fn test_parse_futures_order_status_report_limit_if_touched() {
2691        let order = FuturesOpenOrder {
2692            order_id: "tpl-001".to_string(),
2693            symbol: "PI_XBTUSD".to_string(),
2694            side: KrakenOrderSide::Sell,
2695            order_type: KrakenFuturesOrderType::TakeProfit,
2696            limit_price: Some(dec!(35500)),
2697            stop_price: Some(dec!(36000)),
2698            unfilled_size: Some(dec!(500)),
2699            received_time: "2023-11-14T22:13:20.000Z".to_string(),
2700            status: KrakenFuturesOrderStatus::Untouched,
2701            filled_size: dec!(0),
2702            reduce_only: None,
2703            last_update_time: "2023-11-14T22:13:20.000Z".to_string(),
2704            trigger_signal: None,
2705            cli_ord_id: Some("my-tpl-1".to_string()),
2706            cli_ord_id_snake_case: None,
2707        };
2708        let instrument = create_mock_perp();
2709        let account_id = AccountId::new("KRAKEN-001");
2710
2711        let report =
2712            parse_futures_order_status_report(&order, &instrument, account_id, None, TS).unwrap();
2713
2714        assert_eq!(report.order_type, OrderType::LimitIfTouched);
2715        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(36000));
2716        assert_eq!(report.price.unwrap().as_decimal(), dec!(35500));
2717        assert_eq!(report.order_side, OrderSide::Sell.into());
2718        assert!(!report.reduce_only);
2719    }
2720
2721    #[rstest]
2722    fn test_parse_futures_order_event_market_if_touched() {
2723        let event = FuturesOrderEvent {
2724            order_id: "tp-evt-001".to_string(),
2725            cli_ord_id: None,
2726            order_type: KrakenFuturesOrderType::TakeProfit,
2727            symbol: "PI_XBTUSD".to_string(),
2728            side: KrakenOrderSide::Buy,
2729            quantity: dec!(100),
2730            filled: dec!(100),
2731            limit_price: None,
2732            stop_price: Some(dec!(40000)),
2733            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2734            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2735            reduce_only: false,
2736            time_in_force: TimeInForce::Gtc,
2737            post_only: false,
2738        };
2739        let instrument = create_mock_perp();
2740        let account_id = AccountId::new("KRAKEN-001");
2741
2742        let report = parse_futures_order_event_status_report(
2743            &event,
2744            Some(KrakenFuturesOrderEventType::Fill),
2745            &instrument,
2746            account_id,
2747            TS,
2748        )
2749        .unwrap();
2750
2751        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2752        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(40000));
2753        assert!(report.price.is_none());
2754        assert_eq!(report.order_status, OrderStatus::Filled);
2755    }
2756
2757    #[rstest]
2758    fn test_parse_futures_order_event_limit_if_touched() {
2759        let event = FuturesOrderEvent {
2760            order_id: "tpl-evt-001".to_string(),
2761            cli_ord_id: Some("my-tpl-evt".to_string()),
2762            order_type: KrakenFuturesOrderType::TakeProfit,
2763            symbol: "PI_XBTUSD".to_string(),
2764            side: KrakenOrderSide::Sell,
2765            quantity: dec!(200),
2766            filled: Decimal::ZERO,
2767            limit_price: Some(dec!(39500)),
2768            stop_price: Some(dec!(40000)),
2769            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2770            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2771            reduce_only: true,
2772            time_in_force: TimeInForce::Gtc,
2773            post_only: false,
2774        };
2775        let instrument = create_mock_perp();
2776        let account_id = AccountId::new("KRAKEN-001");
2777
2778        let report = parse_futures_order_event_status_report(
2779            &event,
2780            Some(KrakenFuturesOrderEventType::Place),
2781            &instrument,
2782            account_id,
2783            TS,
2784        )
2785        .unwrap();
2786
2787        assert_eq!(report.order_type, OrderType::LimitIfTouched);
2788        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(40000));
2789        assert_eq!(report.price.unwrap().as_decimal(), dec!(39500));
2790        assert_eq!(report.order_side, OrderSide::Sell.into());
2791        assert_eq!(report.order_status, OrderStatus::Accepted);
2792        assert!(report.reduce_only);
2793    }
2794
2795    #[rstest]
2796    fn test_parse_futures_order_event_cancel_status() {
2797        let event = FuturesOrderEvent {
2798            order_id: "cancel-evt-001".to_string(),
2799            cli_ord_id: Some("cancel-evt".to_string()),
2800            order_type: KrakenFuturesOrderType::Stop,
2801            symbol: "PI_XBTUSD".to_string(),
2802            side: KrakenOrderSide::Sell,
2803            quantity: dec!(200),
2804            filled: Decimal::ZERO,
2805            limit_price: None,
2806            stop_price: Some(dec!(39000)),
2807            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2808            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2809            reduce_only: true,
2810            time_in_force: TimeInForce::Gtc,
2811            post_only: false,
2812        };
2813        let instrument = create_mock_perp();
2814        let account_id = AccountId::new("KRAKEN-001");
2815
2816        let report = parse_futures_order_event_status_report(
2817            &event,
2818            Some(KrakenFuturesOrderEventType::Cancel),
2819            &instrument,
2820            account_id,
2821            TS,
2822        )
2823        .unwrap();
2824
2825        assert_eq!(report.order_status, OrderStatus::Canceled);
2826        assert!(report.reduce_only);
2827    }
2828
2829    #[rstest]
2830    fn test_parse_futures_order_event_reject_status() {
2831        let event = FuturesOrderEvent {
2832            order_id: "reject-evt-001".to_string(),
2833            cli_ord_id: Some("reject-evt".to_string()),
2834            order_type: KrakenFuturesOrderType::Limit,
2835            symbol: "PI_XBTUSD".to_string(),
2836            side: KrakenOrderSide::Buy,
2837            quantity: dec!(200),
2838            filled: Decimal::ZERO,
2839            limit_price: Some(dec!(35000)),
2840            stop_price: None,
2841            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2842            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2843            reduce_only: false,
2844            time_in_force: TimeInForce::Gtc,
2845            post_only: false,
2846        };
2847        let instrument = create_mock_perp();
2848        let account_id = AccountId::new("KRAKEN-001");
2849
2850        let report = parse_futures_order_event_status_report(
2851            &event,
2852            Some(KrakenFuturesOrderEventType::Reject),
2853            &instrument,
2854            account_id,
2855            TS,
2856        )
2857        .unwrap();
2858
2859        assert_eq!(report.order_status, OrderStatus::Rejected);
2860    }
2861
2862    #[rstest]
2863    fn test_parse_futures_order_event_expire_status() {
2864        let event = FuturesOrderEvent {
2865            order_id: "expire-evt-001".to_string(),
2866            cli_ord_id: Some("expire-evt".to_string()),
2867            order_type: KrakenFuturesOrderType::Limit,
2868            symbol: "PI_XBTUSD".to_string(),
2869            side: KrakenOrderSide::Buy,
2870            quantity: dec!(200),
2871            filled: Decimal::ZERO,
2872            limit_price: Some(dec!(35000)),
2873            stop_price: None,
2874            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2875            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2876            reduce_only: false,
2877            time_in_force: TimeInForce::Gtc,
2878            post_only: false,
2879        };
2880        let instrument = create_mock_perp();
2881        let account_id = AccountId::new("KRAKEN-001");
2882
2883        let report = parse_futures_order_event_status_report(
2884            &event,
2885            Some(KrakenFuturesOrderEventType::Expire),
2886            &instrument,
2887            account_id,
2888            TS,
2889        )
2890        .unwrap();
2891
2892        assert_eq!(report.order_status, OrderStatus::Expired);
2893    }
2894
2895    #[rstest]
2896    fn test_parse_futures_order_event_execution_status() {
2897        let event = FuturesOrderEvent {
2898            order_id: "execution-evt-001".to_string(),
2899            cli_ord_id: Some("execution-evt".to_string()),
2900            order_type: KrakenFuturesOrderType::Limit,
2901            symbol: "PI_XBTUSD".to_string(),
2902            side: KrakenOrderSide::Buy,
2903            quantity: dec!(200),
2904            filled: dec!(50),
2905            limit_price: Some(dec!(35000)),
2906            stop_price: None,
2907            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2908            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2909            reduce_only: false,
2910            time_in_force: TimeInForce::Gtc,
2911            post_only: false,
2912        };
2913        let instrument = create_mock_perp();
2914        let account_id = AccountId::new("KRAKEN-001");
2915
2916        let report = parse_futures_order_event_status_report(
2917            &event,
2918            Some(KrakenFuturesOrderEventType::Execution),
2919            &instrument,
2920            account_id,
2921            TS,
2922        )
2923        .unwrap();
2924
2925        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
2926    }
2927
2928    #[rstest]
2929    fn test_parse_fill_report() {
2930        let json = load_test_json("http_trades_history.json");
2931        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
2932        let result = wrapper.get("result").unwrap();
2933        let trades_map = result.get("trades").unwrap();
2934        let trades: IndexMap<String, SpotTrade> =
2935            serde_json::from_value(trades_map.clone()).unwrap();
2936
2937        let account_id = AccountId::new("KRAKEN-001");
2938        let instrument_id = InstrumentId::new(Symbol::new("BTC/USDT"), *KRAKEN_VENUE);
2939        let instrument = InstrumentAny::CurrencyPair(
2940            CurrencyPair::builder()
2941                .instrument_id(instrument_id)
2942                .raw_symbol(Symbol::new("XBTUSDT"))
2943                .base_currency(Currency::BTC())
2944                .quote_currency(Currency::USDT())
2945                .price_precision(2)
2946                .size_precision(8)
2947                .price_increment(Price::from("0.01"))
2948                .size_increment(Quantity::from("0.00000001"))
2949                .ts_event(TS)
2950                .ts_init(TS)
2951                .build()
2952                .unwrap(),
2953        );
2954
2955        let (trade_id, trade) = trades.iter().next().unwrap();
2956
2957        let report = parse_fill_report(trade_id, trade, &instrument, account_id, TS).unwrap();
2958
2959        assert_eq!(report.account_id, account_id);
2960        assert_eq!(report.instrument_id, instrument_id);
2961        assert_eq!(report.trade_id.to_string(), *trade_id);
2962        assert_eq!(report.last_qty, Quantity::from("0.50000000"));
2963        assert_eq!(report.last_px, Price::from("29500.50"));
2964        assert_eq!(report.commission.as_decimal(), dec!(23.60));
2965    }
2966
2967    #[rstest]
2968    #[case("XXBT", "BTC")]
2969    #[case("XBT", "BTC")]
2970    #[case("XXDG", "DOGE")]
2971    #[case("XDG", "DOGE")]
2972    #[case("XETH", "ETH")]
2973    #[case("ZUSD", "USD")]
2974    #[case("ZEUR", "EUR")]
2975    #[case("KFEE", "FEE")]
2976    #[case("BTC", "BTC")]
2977    #[case("ETH", "ETH")]
2978    #[case("USDT", "USDT")]
2979    #[case("SOL", "SOL")]
2980    // Codes that legitimately begin with X or Z must survive: a prefix strip would corrupt them.
2981    #[case("XTZ", "XTZ")]
2982    #[case("XRP", "XRP")]
2983    #[case("XLM", "XLM")]
2984    #[case("XAUT", "XAUT")]
2985    #[case("XCN", "XCN")]
2986    #[case("ZRX", "ZRX")]
2987    #[case("ZEC", "ZEC")]
2988    #[case("ZK", "ZK")]
2989    fn test_normalize_currency_code(#[case] input: &str, #[case] expected: &str) {
2990        assert_eq!(normalize_currency_code(input), expected);
2991    }
2992
2993    /// Kraken Futures keys account balances by its own spelling, which is not upper case.
2994    #[rstest]
2995    #[case("xbt", "BTC")]
2996    #[case("XBT", "BTC")]
2997    #[case("xxbt", "BTC")]
2998    #[case("zeur", "EUR")]
2999    #[case("usd", "USD")]
3000    #[case("xtz", "XTZ")]
3001    #[case("flr", "FLR")]
3002    fn test_normalize_asset_key_is_case_tolerant(#[case] input: &str, #[case] expected: &str) {
3003        assert_eq!(normalize_asset_key(input), expected);
3004    }
3005
3006    #[rstest]
3007    #[case("XBT/EUR", "BTC/EUR")]
3008    #[case("XBT/USD", "BTC/USD")]
3009    #[case("XBT/USDT", "BTC/USDT")]
3010    #[case("ETH/USD", "ETH/USD")]
3011    #[case("ETH/XBT", "ETH/BTC")]
3012    #[case("SOL/XBT", "SOL/BTC")]
3013    #[case("SOL/USD", "SOL/USD")]
3014    #[case("BTC/USD", "BTC/USD")]
3015    #[case("ETH/BTC", "ETH/BTC")]
3016    #[case("XDG/USD", "DOGE/USD")]
3017    #[case("XDG/EUR", "DOGE/EUR")]
3018    #[case("XDG/BTC", "DOGE/BTC")]
3019    #[case("XDG/XBT", "DOGE/BTC")]
3020    fn test_normalize_spot_symbol(#[case] input: &str, #[case] expected: &str) {
3021        assert_eq!(normalize_spot_symbol(input), expected);
3022    }
3023
3024    #[rstest]
3025    #[case("A", "A")] // 1 char, minimum
3026    #[case("O2026022700232", "O2026022700232")] // 14 chars, typical short
3027    #[case("ABCDEFGHIJKLMNOPQR", "ABCDEFGHIJKLMNOPQR")] // 18 chars, at limit
3028    fn test_truncate_cl_ord_id_short_passthrough(#[case] input: &str, #[case] expected: &str) {
3029        let id = ClientOrderId::new(input);
3030        assert_eq!(truncate_cl_ord_id(&id), expected);
3031    }
3032
3033    #[rstest]
3034    #[case("6d47a5f0-6fd4-4b84-b56e-c23f0f689c20")] // lowercase hex
3035    #[case("6D47A5F0-6FD4-4B84-B56E-C23F0F689C20")] // uppercase hex
3036    #[case("00000000-0000-0000-0000-000000000000")] // nil UUID
3037    #[case("ffffffff-ffff-ffff-ffff-ffffffffffff")] // max UUID
3038    fn test_truncate_cl_ord_id_uuid_hyphenated_passthrough(#[case] input: &str) {
3039        let id = ClientOrderId::new(input);
3040        assert_eq!(truncate_cl_ord_id(&id), input);
3041    }
3042
3043    #[rstest]
3044    #[case("6d47a5f06fd44b84b56ec23f0f689c20")] // lowercase
3045    #[case("6D47A5F06FD44B84B56EC23F0F689C20")] // uppercase
3046    #[case("00000000000000000000000000000000")] // all zeros
3047    #[case("aAbBcCdDeEfF00112233445566778899")] // mixed case
3048    fn test_truncate_cl_ord_id_uuid_compact_passthrough(#[case] input: &str) {
3049        let id = ClientOrderId::new(input);
3050        assert_eq!(truncate_cl_ord_id(&id), input);
3051    }
3052
3053    #[rstest]
3054    #[case("O2026022700232100400", "O26022700232100400")] // 20 chars → O + last 17
3055    #[case("O202602270023210040011", "O02270023210040011")] // 22 chars, typical sequential
3056    #[case("O20260227002321004001100", "O27002321004001100")] // 24 chars
3057    fn test_truncate_cl_ord_id_sequential_truncated(#[case] input: &str, #[case] expected: &str) {
3058        let id = ClientOrderId::new(input);
3059        let result = truncate_cl_ord_id(&id);
3060        assert_eq!(result, expected);
3061        assert_eq!(result.len(), 18);
3062        assert!(result.starts_with('O'));
3063    }
3064
3065    #[rstest]
3066    fn test_truncate_cl_ord_id_32_chars_non_hex_truncated() {
3067        let input = "0123456789abcdef0123456789abcdeg";
3068        let id = ClientOrderId::new(input);
3069        let result = truncate_cl_ord_id(&id);
3070        assert_eq!(result.len(), 18);
3071        assert!(result.starts_with('O'));
3072        assert_eq!(result, "Of0123456789abcdeg");
3073    }
3074
3075    #[rstest]
3076    fn test_truncate_cl_ord_id_36_chars_wrong_hyphens_truncated() {
3077        let input = "6d47a5f0-6fd4-4b84-b56ec23f0f689c200";
3078        let id = ClientOrderId::new(input);
3079        let result = truncate_cl_ord_id(&id);
3080        assert_eq!(result.len(), 18);
3081        assert!(result.starts_with('O'));
3082    }
3083
3084    /// The wire price scale is recorded only when `pair_decimals` is finer than the tick
3085    /// precision: an equal or coarser scale leaves the key absent.
3086    #[rstest]
3087    fn test_pair_info_records_pair_decimals_only_when_finer_than_the_tick() {
3088        let json = load_test_json("http_asset_pairs_tokenized.json");
3089        let response: KrakenResponse<AssetPairsResponse> = serde_json::from_str(&json).unwrap();
3090        let pairs = response.result.unwrap();
3091        let (pair_name, definition) = pairs.iter().next().unwrap();
3092
3093        let same = parse_tokenized_instrument(pair_name, definition, TS, TS).unwrap();
3094        assert!(
3095            same.info()
3096                .is_none_or(|info| !info.contains_key(KRAKEN_PAIR_DECIMALS_KEY)),
3097            "a scale equal to the tick precision is not recorded"
3098        );
3099
3100        let mut coarser = definition.clone();
3101        coarser.pair_decimals = same.price_precision() - 1;
3102        let tokenized = parse_tokenized_instrument(pair_name, &coarser, TS, TS).unwrap();
3103        let spot = parse_spot_instrument(pair_name, &coarser, TS, TS).unwrap();
3104        for instrument in [tokenized, spot] {
3105            assert!(
3106                instrument
3107                    .info()
3108                    .is_none_or(|info| !info.contains_key(KRAKEN_PAIR_DECIMALS_KEY)),
3109                "a scale coarser than the tick precision is not recorded"
3110            );
3111        }
3112
3113        let mut finer = definition.clone();
3114        finer.pair_decimals = same.price_precision() + 1;
3115        let tokenized = parse_tokenized_instrument(pair_name, &finer, TS, TS).unwrap();
3116        let spot = parse_spot_instrument(pair_name, &finer, TS, TS).unwrap();
3117        for instrument in [tokenized, spot] {
3118            let recorded = instrument
3119                .info()
3120                .and_then(|info| info.get(KRAKEN_PAIR_DECIMALS_KEY))
3121                .and_then(serde_json::Value::as_u64);
3122            assert_eq!(recorded, Some(u64::from(finer.pair_decimals)));
3123        }
3124    }
3125
3126    #[rstest]
3127    fn test_parse_tokenized_instrument() {
3128        let json = load_test_json("http_asset_pairs_tokenized.json");
3129        let response: KrakenResponse<AssetPairsResponse> = serde_json::from_str(&json).unwrap();
3130        let pairs = response.result.unwrap();
3131
3132        let (pair_name, definition) = pairs.iter().next().unwrap();
3133
3134        let instrument = parse_tokenized_instrument(pair_name, definition, TS, TS).unwrap();
3135
3136        match instrument {
3137            InstrumentAny::TokenizedAsset(ta) => {
3138                assert_eq!(ta.id.symbol.as_str(), "AAPLx/USD");
3139                assert_eq!(ta.id.venue.as_str(), "KRAKEN");
3140                assert_eq!(ta.raw_symbol.as_str(), "AAPLxUSD");
3141                assert_eq!(ta.asset_class, AssetClass::Equity);
3142                assert_eq!(ta.base_currency.code, "AAPLx");
3143                assert_eq!(ta.quote_currency.code, "USD");
3144                assert_eq!(ta.price_precision, 2);
3145                assert_eq!(ta.size_precision, 8);
3146                assert_eq!(ta.price_increment.as_decimal(), dec!(0.01));
3147                assert_eq!(ta.size_increment.as_decimal(), dec!(0.00000001));
3148                assert!(ta.min_quantity.is_some());
3149            }
3150            _ => panic!("Expected TokenizedAsset, received {instrument:?}"),
3151        }
3152
3153        // A key spelled differently from the altname, at a wire scale finer than the tick: the
3154        // info carries the scale and nothing else.
3155        let mut finer = definition.clone();
3156        finer.pair_decimals = 3;
3157        let instrument = parse_tokenized_instrument("XAAPLxZUSD", &finer, TS, TS).unwrap();
3158        let info = instrument.info().expect("the wire scale is recorded");
3159        assert_eq!(
3160            info.get(KRAKEN_PAIR_DECIMALS_KEY)
3161                .and_then(serde_json::Value::as_u64),
3162            Some(3)
3163        );
3164        assert!(
3165            !info.contains_key(KRAKEN_ALTNAME_KEY),
3166            "a tokenized pair carries no altname alias"
3167        );
3168    }
3169
3170    #[rstest]
3171    fn test_parse_fill_report_tokenized_asset() {
3172        let json = load_test_json("http_trades_history.json");
3173        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
3174        let result = wrapper.get("result").unwrap();
3175        let trades_map = result.get("trades").unwrap();
3176        let trades: IndexMap<String, SpotTrade> =
3177            serde_json::from_value(trades_map.clone()).unwrap();
3178
3179        let account_id = AccountId::new("KRAKEN-001");
3180        let instrument_id = InstrumentId::new(Symbol::new("AAPLx/USD"), *KRAKEN_VENUE);
3181        let instrument = InstrumentAny::TokenizedAsset(
3182            TokenizedAsset::builder()
3183                .instrument_id(instrument_id)
3184                .raw_symbol(Symbol::new("AAPLxUSD"))
3185                .asset_class(AssetClass::Equity)
3186                .base_currency(Currency::get_or_create_crypto("AAPLx"))
3187                .quote_currency(Currency::USD())
3188                .price_precision(2)
3189                .size_precision(8)
3190                .price_increment(Price::from("0.01"))
3191                .size_increment(Quantity::from("0.00000001"))
3192                .ts_event(TS)
3193                .ts_init(TS)
3194                .build()
3195                .unwrap(),
3196        );
3197
3198        let (trade_id, trade) = trades.iter().next().unwrap();
3199
3200        let report = parse_fill_report(trade_id, trade, &instrument, account_id, TS).unwrap();
3201
3202        assert_eq!(report.account_id, account_id);
3203        assert_eq!(report.instrument_id, instrument_id);
3204        assert_eq!(report.trade_id.to_string(), *trade_id);
3205        assert_eq!(report.last_qty, Quantity::from("0.50000000"));
3206        assert_eq!(report.last_px, Price::from("29500.50"));
3207        assert_eq!(report.commission.currency, Currency::USD());
3208    }
3209
3210    #[rstest]
3211    fn test_truncate_cl_ord_id_19_chars_truncated() {
3212        let input = "O202602270023210040";
3213        assert_eq!(input.len(), 19);
3214        let id = ClientOrderId::new(input);
3215        let result = truncate_cl_ord_id(&id);
3216        assert_eq!(result.len(), 18);
3217        assert_eq!(result, "O02602270023210040");
3218    }
3219
3220    #[rstest]
3221    fn test_truncate_cl_ord_id_preserves_tail() {
3222        let input = "O20260227002321004001100";
3223        let id = ClientOrderId::new(input);
3224        let result = truncate_cl_ord_id(&id);
3225        assert_eq!(&result[1..], &input[input.len() - 17..]);
3226    }
3227}