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, KrakenOrderType, KrakenPositionSide, KrakenSpotTrigger,
46            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.
753pub fn parse_order_status_report(
754    order_id: &str,
755    order: &SpotOrder,
756    instrument: &InstrumentAny,
757    account_id: AccountId,
758    ts_init: UnixNanos,
759) -> anyhow::Result<OrderStatusReport> {
760    let instrument_id = instrument.id();
761    let venue_order_id = parse_venue_order_id(order_id, "spot order")?;
762
763    let order_side = OrderSide::from(order.descr.order_side).into();
764    let order_type = order.descr.ordertype.into();
765    let order_status = order.status.into();
766
767    // Kraken returns expiretm=0 for GTC orders, so check for actual expiration value
768    let has_expiration = order.expiretm.is_some_and(|t| t > 0.0);
769    let time_in_force = if has_expiration {
770        TimeInForce::Gtd
771    } else if order.oflags.contains("ioc") {
772        TimeInForce::Ioc
773    } else {
774        TimeInForce::Gtc
775    };
776
777    let quantity =
778        parse_quantity_with_precision(&order.vol, instrument.size_precision(), "order.vol")?;
779
780    let filled_qty = parse_quantity_with_precision(
781        &order.vol_exec,
782        instrument.size_precision(),
783        "order.vol_exec",
784    )?;
785
786    let ts_accepted = parse_millis_timestamp(order.opentm, "order.opentm")?;
787
788    let ts_last = order
789        .closetm
790        .map(|t| parse_millis_timestamp(t, "order.closetm"))
791        .transpose()?
792        .unwrap_or(ts_accepted);
793
794    // The row's top-level `price` is the average fill price, which `avg_px` carries, so the
795    // order's prices come from the fields that hold them
796    let price_precision = instrument.price_precision();
797    let row_price =
798        |value: &str, field: &str| parse_spot_order_price(order_id, value, price_precision, field);
799    let price = match order.descr.ordertype {
800        KrakenOrderType::Limit => row_price(&order.descr.price, "descr.price")?,
801        KrakenOrderType::StopLossLimit | KrakenOrderType::TakeProfitLimit => {
802            row_price(&order.descr.price2, "descr.price2")?
803        }
804        // A trailing-stop-limit's `descr.price2` holds the offset AddOrder took until `misc` marks
805        // the order `stopped` and the limit after, while its `limitprice` holds the peak price in
806        // both states
807        KrakenOrderType::TrailingStopLimit
808            if order.misc.split(',').any(|info| info == "stopped") =>
809        {
810            row_price(&order.descr.price2, "descr.price2")?
811        }
812        KrakenOrderType::Market
813        | KrakenOrderType::SettlePosition
814        | KrakenOrderType::StopLoss
815        | KrakenOrderType::TakeProfit
816        | KrakenOrderType::TrailingStop
817        | KrakenOrderType::TrailingStopLimit => None,
818    };
819
820    let stop_price = order
821        .stopprice
822        .as_deref()
823        .map(|value| row_price(value, "stopprice"))
824        .transpose()?
825        .flatten();
826
827    // AddOrder takes a non-trailing conditional order's trigger as its `price`, which the
828    // description holds, so it stands in for a zero `stopprice`
829    let trigger_price = match order.descr.ordertype {
830        KrakenOrderType::StopLoss
831        | KrakenOrderType::TakeProfit
832        | KrakenOrderType::StopLossLimit
833        | KrakenOrderType::TakeProfitLimit => match stop_price {
834            Some(price) => Some(price),
835            None => row_price(&order.descr.price, "descr.price")?,
836        },
837        KrakenOrderType::Market
838        | KrakenOrderType::Limit
839        | KrakenOrderType::SettlePosition
840        | KrakenOrderType::TrailingStop
841        | KrakenOrderType::TrailingStopLimit => stop_price,
842    };
843
844    let expire_time = if has_expiration {
845        order
846            .expiretm
847            .map(|t| parse_millis_timestamp(t, "order.expiretm"))
848            .transpose()?
849    } else {
850        None
851    };
852
853    let trigger_type = parse_trigger_type(order_type, order.trigger);
854
855    Ok(OrderStatusReport {
856        account_id,
857        instrument_id,
858        client_order_id: None,
859        venue_order_id,
860        order_side,
861        order_type,
862        time_in_force,
863        order_status,
864        quantity,
865        filled_qty,
866        report_id: UUID4::new(),
867        ts_accepted,
868        ts_last,
869        ts_init,
870        order_list_id: None,
871        venue_position_id: None,
872        linked_order_ids: None,
873        parent_order_id: None,
874        contingency_type: None,
875        expire_time,
876        price,
877        activation_price: None,
878        trigger_price,
879        trigger_type,
880        limit_offset: None,
881        trailing_offset: None,
882        trailing_offset_type: None,
883        display_qty: None,
884        avg_px: compute_avg_px(order),
885        post_only: order.oflags.contains("post"),
886        reduce_only: false,
887        cancel_reason: order.reason.clone(),
888        ts_triggered: None,
889    })
890}
891
892/// Parses a price field of a spot order row, an empty or zero value stating no price.
893///
894/// AddOrder also takes a price relative to the market, as an expression with a `+`, `-` or `#`
895/// prefix or a `%` suffix. Such a value is not a price, so it reads as none, with a warning,
896/// rather than failing the read.
897fn parse_spot_order_price(
898    order_id: &str,
899    value: &str,
900    precision: u8,
901    field: &str,
902) -> anyhow::Result<Option<Price>> {
903    if value.is_empty() {
904        return Ok(None);
905    }
906
907    if value.starts_with(['+', '-', '#']) || value.ends_with('%') {
908        log::warn!("Spot order {order_id} {field}='{value}' is a relative price, reporting none");
909        return Ok(None);
910    }
911
912    let price = parse_price_with_precision(value, precision, field)?;
913    Ok((!price.is_zero()).then_some(price))
914}
915
916/// Computes the average price for a Kraken spot order.
917///
918/// Prefers the direct `avg_price` field if available, otherwise calculates from `cost / vol_exec`.
919fn compute_avg_px(order: &SpotOrder) -> Option<Decimal> {
920    if let Some(ref avg) = order.avg_price
921        && let Ok(v) = parse_decimal(avg)
922        && v > dec!(0)
923    {
924        return Some(v);
925    }
926
927    let cost = parse_decimal(&order.cost);
928    let vol_exec = parse_decimal(&order.vol_exec);
929    match (&cost, &vol_exec) {
930        (Ok(c), Ok(v)) if *v > dec!(0) => Some(*c / *v),
931        _ => {
932            if let Ok(v) = &vol_exec
933                && *v > dec!(0)
934            {
935                log::warn!("Cannot compute avg_px: cost={cost:?}, vol_exec={vol_exec:?}");
936            }
937            None
938        }
939    }
940}
941
942/// Parses a Kraken spot trade into a Nautilus FillReport.
943///
944/// # Errors
945///
946/// Returns an error if:
947/// - Order ID, quantities, or prices cannot be parsed.
948pub fn parse_fill_report(
949    trade_id: &str,
950    trade: &SpotTrade,
951    instrument: &InstrumentAny,
952    account_id: AccountId,
953    ts_init: UnixNanos,
954) -> anyhow::Result<FillReport> {
955    let instrument_id = instrument.id();
956    let venue_order_id = parse_venue_order_id(&trade.ordertxid, "spot trade")?;
957    let trade_id_obj = TradeId::new(trade_id);
958
959    let order_side = trade.trade_type.into();
960
961    let last_qty =
962        parse_quantity_with_precision(&trade.vol, instrument.size_precision(), "trade.vol")?;
963
964    let last_px =
965        parse_price_with_precision(&trade.price, instrument.price_precision(), "trade.price")?;
966
967    let fee_decimal = parse_decimal(&trade.fee)?;
968    let quote_currency = match instrument {
969        InstrumentAny::CurrencyPair(pair) => pair.quote_currency,
970        InstrumentAny::CryptoPerpetual(perp) => perp.quote_currency,
971        InstrumentAny::TokenizedAsset(ta) => ta.quote_currency,
972        _ => anyhow::bail!("Unsupported instrument type for fill report"),
973    };
974
975    let commission = Money::from_decimal(fee_decimal, quote_currency)?;
976
977    let liquidity_side = match trade.maker {
978        Some(true) => LiquiditySide::Maker,
979        Some(false) => LiquiditySide::Taker,
980        None => LiquiditySide::NoLiquiditySide,
981    };
982
983    let ts_event = parse_millis_timestamp(trade.time, "trade.time")?;
984
985    Ok(FillReport {
986        account_id,
987        instrument_id,
988        venue_order_id,
989        trade_id: trade_id_obj,
990        order_side,
991        last_qty,
992        last_px,
993        commission,
994        liquidity_side,
995        avg_px: None,
996        report_id: UUID4::new(),
997        ts_event,
998        ts_init,
999        client_order_id: None,
1000        venue_position_id: None,
1001    })
1002}
1003
1004/// Returns the time in force and post-only flag for a Kraken futures order type: `ioc` is `IOC`,
1005/// `post` is post-only `GTC`, and any other type defaults to `GTC` and not post-only.
1006pub(crate) fn parse_futures_order_type_time_in_force(
1007    order_type: KrakenFuturesOrderType,
1008) -> (TimeInForce, bool) {
1009    match order_type {
1010        KrakenFuturesOrderType::Ioc => (TimeInForce::Ioc, false),
1011        KrakenFuturesOrderType::Post => (TimeInForce::Gtc, true),
1012        _ => (TimeInForce::Gtc, false),
1013    }
1014}
1015
1016/// Parses a Kraken futures open order into a Nautilus OrderStatusReport.
1017///
1018/// # Errors
1019///
1020/// Returns an error if order ID, quantities, or prices cannot be parsed.
1021pub fn parse_futures_order_status_report(
1022    order: &FuturesOpenOrder,
1023    instrument: &InstrumentAny,
1024    account_id: AccountId,
1025    fallback_quantity: Option<Decimal>,
1026    ts_init: UnixNanos,
1027) -> anyhow::Result<OrderStatusReport> {
1028    let instrument_id = instrument.id();
1029    let venue_order_id = parse_venue_order_id(&order.order_id, "futures open order")?;
1030
1031    let order_side = OrderSide::from(order.side).into();
1032    let order_type: OrderType = order.order_type.into();
1033    let order_type = if order_type == OrderType::MarketIfTouched && order.limit_price.is_some() {
1034        OrderType::LimitIfTouched
1035    } else {
1036        order_type
1037    };
1038    let order_status = order.status.into();
1039    let (time_in_force, post_only) = parse_futures_order_type_time_in_force(order.order_type);
1040
1041    let quantity_value = order
1042        .unfilled_size
1043        .map(|unfilled_size| unfilled_size + order.filled_size)
1044        .or(fallback_quantity)
1045        .context("missing unfilled size and fallback quantity")?;
1046    let quantity = Quantity::from_decimal_dp(quantity_value, instrument.size_precision())?;
1047
1048    let filled_qty = Quantity::from_decimal_dp(order.filled_size, instrument.size_precision())?;
1049
1050    let ts_accepted = parse_rfc3339_timestamp(&order.received_time, "order.received_time")?;
1051    let ts_last = parse_rfc3339_timestamp(&order.last_update_time, "order.last_update_time")?;
1052
1053    let price = order
1054        .limit_price
1055        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1056        .transpose()?;
1057
1058    let trigger_price = order
1059        .stop_price
1060        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1061        .transpose()?;
1062
1063    let trigger_type = parse_futures_trigger_type(order_type, order.trigger_signal);
1064
1065    Ok(OrderStatusReport {
1066        account_id,
1067        instrument_id,
1068        client_order_id: echoed_client_order_id(order.client_order_id()),
1069        venue_order_id,
1070        order_side,
1071        order_type,
1072        time_in_force,
1073        order_status,
1074        quantity,
1075        filled_qty,
1076        report_id: UUID4::new(),
1077        ts_accepted,
1078        ts_last,
1079        ts_init,
1080        order_list_id: None,
1081        venue_position_id: None,
1082        linked_order_ids: None,
1083        parent_order_id: None,
1084        contingency_type: None,
1085        expire_time: None,
1086        price,
1087        activation_price: None,
1088        trigger_price,
1089        trigger_type,
1090        limit_offset: None,
1091        trailing_offset: None,
1092        trailing_offset_type: None,
1093        display_qty: None,
1094        avg_px: None,
1095        post_only,
1096        reduce_only: order.reduce_only.unwrap_or(false),
1097        cancel_reason: None,
1098        ts_triggered: None,
1099    })
1100}
1101
1102/// Parses a Kraken futures order event (historical order) into a Nautilus OrderStatusReport.
1103///
1104/// # Errors
1105///
1106/// Returns an error if order ID, quantities, or prices cannot be parsed.
1107pub fn parse_futures_order_event_status_report(
1108    event: &FuturesOrderEvent,
1109    event_type: Option<KrakenFuturesOrderEventType>,
1110    instrument: &InstrumentAny,
1111    account_id: AccountId,
1112    ts_init: UnixNanos,
1113) -> anyhow::Result<OrderStatusReport> {
1114    let instrument_id = instrument.id();
1115    let venue_order_id = parse_venue_order_id(&event.order_id, "futures order event")?;
1116
1117    let order_side = OrderSide::from(event.side).into();
1118    let order_type: OrderType = event.order_type.into();
1119    let order_type = if order_type == OrderType::MarketIfTouched && event.limit_price.is_some() {
1120        OrderType::LimitIfTouched
1121    } else {
1122        order_type
1123    };
1124
1125    let order_status = parse_futures_order_event_status(event_type, event.filled, event.quantity);
1126
1127    let quantity = Quantity::from_decimal_dp(event.quantity, instrument.size_precision())?;
1128    let filled_qty = Quantity::from_decimal_dp(event.filled, instrument.size_precision())?;
1129
1130    let ts_accepted = parse_rfc3339_timestamp(&event.timestamp, "event.timestamp")?;
1131    let ts_last =
1132        parse_rfc3339_timestamp(&event.last_update_timestamp, "event.last_update_timestamp")?;
1133
1134    let price = event
1135        .limit_price
1136        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1137        .transpose()?;
1138
1139    let trigger_price = event
1140        .stop_price
1141        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1142        .transpose()?;
1143
1144    let trigger_type = parse_futures_trigger_type(order_type, None);
1145
1146    Ok(OrderStatusReport {
1147        account_id,
1148        instrument_id,
1149        client_order_id: echoed_client_order_id(event.cli_ord_id.as_deref()),
1150        venue_order_id,
1151        order_side,
1152        order_type,
1153        time_in_force: event.time_in_force,
1154        order_status,
1155        quantity,
1156        filled_qty,
1157        report_id: UUID4::new(),
1158        ts_accepted,
1159        ts_last,
1160        ts_init,
1161        order_list_id: None,
1162        venue_position_id: None,
1163        linked_order_ids: None,
1164        parent_order_id: None,
1165        contingency_type: None,
1166        expire_time: None,
1167        price,
1168        activation_price: None,
1169        trigger_price,
1170        trigger_type,
1171        limit_offset: None,
1172        trailing_offset: None,
1173        trailing_offset_type: None,
1174        display_qty: None,
1175        avg_px: None,
1176        post_only: event.post_only,
1177        reduce_only: event.reduce_only,
1178        cancel_reason: None,
1179        ts_triggered: None,
1180    })
1181}
1182
1183/// The client order ID a futures response echoes, if it carries a valid one. An empty or invalid
1184/// echo, which another tool on the account may have sent, names no order rather than failing the
1185/// read.
1186fn echoed_client_order_id(echoed: Option<&str>) -> Option<ClientOrderId> {
1187    echoed
1188        .filter(|id| !id.is_empty())
1189        .and_then(|id| ClientOrderId::new_checked(id).ok())
1190}
1191
1192/// Parses a Kraken futures `/orders/status` entry into a Nautilus
1193/// OrderStatusReport.
1194///
1195/// The endpoint reports orders which are open or were filled/cancelled in the
1196/// last 5 seconds, so the entry's cumulative `filled` is authoritative for
1197/// reconciliation even when the order is absent from the open-orders snapshot.
1198///
1199/// # Errors
1200///
1201/// Returns an error if order ID, quantities, prices, or timestamps cannot be
1202/// parsed.
1203pub fn parse_futures_order_status_details_report(
1204    details: &FuturesOrderStatusDetails,
1205    instrument: &InstrumentAny,
1206    account_id: AccountId,
1207    ts_init: UnixNanos,
1208) -> anyhow::Result<OrderStatusReport> {
1209    let venue_order_id = parse_venue_order_id(&details.order.order_id, "futures order status")?;
1210
1211    let order_side = OrderSide::from(details.order.side).into();
1212
1213    let order_type = if details.order.limit_price.is_some() {
1214        OrderType::Limit
1215    } else {
1216        OrderType::Market
1217    };
1218
1219    let filled = details.order.filled.unwrap_or(Decimal::ZERO);
1220
1221    let order_status = match details.status {
1222        KrakenFuturesOrderLifecycleStatus::EnteredBook
1223        | KrakenFuturesOrderLifecycleStatus::TriggerPlaced => {
1224            if filled > Decimal::ZERO {
1225                OrderStatus::PartiallyFilled
1226            } else {
1227                OrderStatus::Accepted
1228            }
1229        }
1230        KrakenFuturesOrderLifecycleStatus::FullyExecuted => OrderStatus::Filled,
1231        KrakenFuturesOrderLifecycleStatus::Rejected
1232        | KrakenFuturesOrderLifecycleStatus::TriggerActivationFailure => OrderStatus::Rejected,
1233        KrakenFuturesOrderLifecycleStatus::Cancelled => OrderStatus::Canceled,
1234    };
1235
1236    let quantity_value = details
1237        .order
1238        .quantity
1239        .context("order status details missing quantity")?;
1240    let quantity = Quantity::from_decimal_dp(quantity_value, instrument.size_precision())?;
1241    let filled_qty = Quantity::from_decimal_dp(filled, instrument.size_precision())?;
1242
1243    let ts_accepted = parse_rfc3339_timestamp(&details.order.timestamp, "order.timestamp")?;
1244    let ts_last = parse_rfc3339_timestamp(
1245        &details.order.last_update_timestamp,
1246        "order.last_update_timestamp",
1247    )?;
1248
1249    let price = details
1250        .order
1251        .limit_price
1252        .map(|p| Price::from_decimal_dp(p, instrument.price_precision()))
1253        .transpose()?;
1254
1255    let cancel_reason = match details.status {
1256        KrakenFuturesOrderLifecycleStatus::Cancelled
1257        | KrakenFuturesOrderLifecycleStatus::Rejected
1258        | KrakenFuturesOrderLifecycleStatus::TriggerActivationFailure => {
1259            details.update_reason.clone()
1260        }
1261        _ => None,
1262    };
1263
1264    Ok(OrderStatusReport {
1265        account_id,
1266        instrument_id: instrument.id(),
1267        client_order_id: echoed_client_order_id(details.order.cli_ord_id.as_deref()),
1268        venue_order_id,
1269        order_side,
1270        order_type,
1271        time_in_force: TimeInForce::Gtc,
1272        order_status,
1273        quantity,
1274        filled_qty,
1275        report_id: UUID4::new(),
1276        ts_accepted,
1277        ts_last,
1278        ts_init,
1279        order_list_id: None,
1280        venue_position_id: None,
1281        linked_order_ids: None,
1282        parent_order_id: None,
1283        contingency_type: None,
1284        expire_time: None,
1285        price,
1286        activation_price: None,
1287        trigger_price: None,
1288        trigger_type: None,
1289        limit_offset: None,
1290        trailing_offset: None,
1291        trailing_offset_type: None,
1292        display_qty: None,
1293        avg_px: None,
1294        post_only: false,
1295        reduce_only: details.order.reduce_only,
1296        cancel_reason,
1297        ts_triggered: None,
1298    })
1299}
1300
1301fn parse_futures_order_event_status(
1302    event_type: Option<KrakenFuturesOrderEventType>,
1303    filled: Decimal,
1304    quantity: Decimal,
1305) -> OrderStatus {
1306    match event_type {
1307        Some(KrakenFuturesOrderEventType::Cancel) => OrderStatus::Canceled,
1308        Some(KrakenFuturesOrderEventType::Reject) => OrderStatus::Rejected,
1309        Some(KrakenFuturesOrderEventType::Expire) => OrderStatus::Expired,
1310        Some(
1311            KrakenFuturesOrderEventType::Fill
1312            | KrakenFuturesOrderEventType::Execution
1313            | KrakenFuturesOrderEventType::Place
1314            | KrakenFuturesOrderEventType::Edit,
1315        ) => {
1316            if filled >= quantity {
1317                OrderStatus::Filled
1318            } else if filled > Decimal::ZERO {
1319                OrderStatus::PartiallyFilled
1320            } else {
1321                OrderStatus::Accepted
1322            }
1323        }
1324        _ => {
1325            if filled >= quantity {
1326                OrderStatus::Filled
1327            } else if filled > Decimal::ZERO {
1328                OrderStatus::PartiallyFilled
1329            } else {
1330                OrderStatus::Canceled
1331            }
1332        }
1333    }
1334}
1335
1336/// Parses a Kraken futures fill into a Nautilus FillReport.
1337///
1338/// # Errors
1339///
1340/// Returns an error if order ID, quantities, or prices cannot be parsed.
1341pub fn parse_futures_fill_report(
1342    fill: &FuturesFill,
1343    instrument: &InstrumentAny,
1344    account_id: AccountId,
1345    ts_init: UnixNanos,
1346) -> anyhow::Result<FillReport> {
1347    let instrument_id = instrument.id();
1348    let venue_order_id = parse_venue_order_id(&fill.order_id, "futures fill")?;
1349    let trade_id = TradeId::new(&fill.fill_id);
1350
1351    let order_side = fill.side.into();
1352
1353    let last_qty = Quantity::from_decimal_dp(fill.size, instrument.size_precision())?;
1354    let last_px = Price::from_decimal_dp(fill.price, instrument.price_precision())?;
1355
1356    let quote_currency = match instrument {
1357        InstrumentAny::CryptoPerpetual(perp) => perp.quote_currency,
1358        InstrumentAny::CryptoFuture(future) => future.quote_currency,
1359        _ => anyhow::bail!("Unsupported instrument type for futures fill report"),
1360    };
1361
1362    // The venue reports the fee currency, which on an inverse contract is not the quote.
1363    let commission_currency = fill
1364        .fee_currency
1365        .as_deref()
1366        .map_or(quote_currency, |reported| {
1367            fee_currency(reported, instrument)
1368        });
1369    let commission =
1370        Money::from_decimal(fill.fee_paid.unwrap_or(Decimal::ZERO), commission_currency)?;
1371
1372    let liquidity_side = fill.fill_type.into();
1373
1374    let ts_event = parse_rfc3339_timestamp(&fill.fill_time, "fill.fill_time")?;
1375
1376    Ok(FillReport {
1377        account_id,
1378        instrument_id,
1379        venue_order_id,
1380        trade_id,
1381        order_side,
1382        last_qty,
1383        last_px,
1384        commission,
1385        liquidity_side,
1386        avg_px: None,
1387        report_id: UUID4::new(),
1388        ts_event,
1389        ts_init,
1390        client_order_id: echoed_client_order_id(fill.client_order_id()),
1391        venue_position_id: None,
1392    })
1393}
1394
1395/// Parses a Kraken futures position into a Nautilus PositionStatusReport.
1396///
1397/// # Errors
1398///
1399/// Returns an error if position quantities or prices cannot be parsed.
1400pub fn parse_futures_position_status_report(
1401    position: &FuturesPosition,
1402    instrument: &InstrumentAny,
1403    account_id: AccountId,
1404    ts_init: UnixNanos,
1405) -> anyhow::Result<PositionStatusReport> {
1406    let instrument_id = instrument.id();
1407
1408    let position_side = match position.side {
1409        KrakenPositionSide::Long => PositionSide::Long,
1410        KrakenPositionSide::Short => PositionSide::Short,
1411    };
1412
1413    let quantity = Quantity::from_decimal_dp(position.size, instrument.size_precision())?;
1414    let signed_decimal_qty = match position_side {
1415        PositionSide::Long => position.size,
1416        PositionSide::Short => -position.size,
1417        PositionSide::Flat => dec!(0),
1418    };
1419
1420    let avg_px_open = Some(position.price);
1421
1422    Ok(PositionStatusReport {
1423        account_id,
1424        instrument_id,
1425        position_side,
1426        quantity,
1427        signed_decimal_qty,
1428        report_id: UUID4::new(),
1429        ts_last: ts_init,
1430        ts_init,
1431        venue_position_id: None,
1432        avg_px_open,
1433        avg_px_open_reconciliation: AvgPxReconciliation::default(),
1434        avg_px_open_precision: None,
1435        liquidation_price: None,
1436    })
1437}
1438
1439/// Converts a Nautilus BarType to Kraken Spot API interval (in minutes).
1440///
1441/// # Errors
1442///
1443/// Returns an error if:
1444/// - Bar aggregation type is not supported (only Minute, Hour, Day are valid).
1445/// - Bar step is not supported for the aggregation type.
1446pub fn bar_type_to_spot_interval(bar_type: BarType) -> anyhow::Result<u32> {
1447    let step = bar_type.spec().step.get() as u32;
1448    let base_interval = match bar_type.spec().aggregation {
1449        BarAggregation::Minute => 1,
1450        BarAggregation::Hour => 60,
1451        BarAggregation::Day => 1440,
1452        other => {
1453            anyhow::bail!("Unsupported bar aggregation for Kraken Spot: {other:?}");
1454        }
1455    };
1456    Ok(base_interval * step)
1457}
1458
1459/// Converts a Nautilus BarType to Kraken Futures API resolution string.
1460///
1461/// Supported resolutions: 1m, 5m, 15m, 1h, 4h, 12h, 1d, 1w
1462///
1463/// # Errors
1464///
1465/// Returns an error if:
1466/// - Bar aggregation type is not supported.
1467/// - Bar step is not supported for the aggregation type.
1468pub fn bar_type_to_futures_resolution(bar_type: BarType) -> anyhow::Result<&'static str> {
1469    let step = bar_type.spec().step.get() as u32;
1470    match bar_type.spec().aggregation {
1471        BarAggregation::Minute => match step {
1472            1 => Ok("1m"),
1473            5 => Ok("5m"),
1474            15 => Ok("15m"),
1475            _ => anyhow::bail!("Unsupported minute step for Kraken Futures: {step}"),
1476        },
1477        BarAggregation::Hour => match step {
1478            1 => Ok("1h"),
1479            4 => Ok("4h"),
1480            12 => Ok("12h"),
1481            _ => anyhow::bail!("Unsupported hour step for Kraken Futures: {step}"),
1482        },
1483        BarAggregation::Day => {
1484            if step == 1 {
1485                Ok("1d")
1486            } else {
1487                anyhow::bail!("Unsupported day step for Kraken Futures: {step}")
1488            }
1489        }
1490        BarAggregation::Week => {
1491            if step == 1 {
1492                Ok("1w")
1493            } else {
1494                anyhow::bail!("Unsupported week step for Kraken Futures: {step}")
1495            }
1496        }
1497        other => {
1498            anyhow::bail!("Unsupported bar aggregation for Kraken Futures: {other:?}");
1499        }
1500    }
1501}
1502
1503/// Truncates a `ClientOrderId` for Kraken's `cl_ord_id` field.
1504///
1505/// Kraken accepts three formats:
1506/// - Long UUID (36 chars with hyphens): passed through
1507/// - Short UUID (32 hex chars): passed through
1508/// - Free text: max 18 chars
1509///
1510/// Sequential NautilusTrader IDs (e.g. `O202602270023210040011`) exceed the
1511/// 18-char free-text limit. These are truncated to 'O' + last 17 chars,
1512/// preserving the counter portion for maximum entropy.
1513pub fn truncate_cl_ord_id(client_order_id: &ClientOrderId) -> String {
1514    let id = client_order_id.as_str();
1515
1516    if id.len() <= 18 {
1517        return id.to_string();
1518    }
1519
1520    if id.len() == 36 && id.bytes().filter(|b| *b == b'-').count() == 4 {
1521        return id.to_string();
1522    }
1523
1524    if id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit()) {
1525        return id.to_string();
1526    }
1527
1528    format!("O{}", &id[id.len() - 17..])
1529}
1530
1531#[cfg(test)]
1532mod tests {
1533    use indexmap::IndexMap;
1534    use nautilus_model::{
1535        data::BarSpecification,
1536        enums::{AggregationSource, BarAggregation, OrderSide, OrderStatus, PriceType},
1537        instruments::crypto_perpetual::CryptoPerpetual,
1538    };
1539    use rstest::rstest;
1540
1541    use super::*;
1542    use crate::{
1543        common::enums::{KrakenFuturesOrderEventType, KrakenFuturesOrderStatus, KrakenOrderSide},
1544        http::{
1545            futures::models::{
1546                FuturesFillsResponse, FuturesOpenOrder, FuturesOpenOrdersResponse,
1547                FuturesOrderEvent, FuturesOrdersStatusResponse,
1548            },
1549            models::{
1550                AssetPairsResponse, KrakenResponse, SpotClosedOrdersResult, SpotOpenOrdersResult,
1551            },
1552        },
1553    };
1554
1555    const TS: UnixNanos = UnixNanos::new(1_700_000_000_000_000_000);
1556
1557    fn load_test_json(filename: &str) -> String {
1558        let path = format!("test_data/{filename}");
1559        std::fs::read_to_string(&path)
1560            .unwrap_or_else(|e| panic!("Failed to load test data from {path}: {e}"))
1561    }
1562
1563    /// A futures response can echo a client order ID another tool on the account sent, so an empty
1564    /// or otherwise invalid one names no order rather than failing the parse.
1565    #[rstest]
1566    #[case::valid(Some("O-1"), Some("O-1"))]
1567    #[case::absent(None, None)]
1568    #[case::empty(Some(""), None)]
1569    #[case::whitespace(Some(" "), None)]
1570    #[case::non_ascii(Some("ordre-\u{e9}"), None)]
1571    fn test_echoed_client_order_id(#[case] echoed: Option<&str>, #[case] expected: Option<&str>) {
1572        assert_eq!(
1573            echoed_client_order_id(echoed),
1574            expected.map(ClientOrderId::from)
1575        );
1576    }
1577
1578    #[rstest]
1579    fn test_parse_decimal() {
1580        assert_eq!(parse_decimal("123.45").unwrap(), dec!(123.45));
1581        assert_eq!(parse_decimal("0").unwrap(), dec!(0));
1582        assert_eq!(parse_decimal("").unwrap(), dec!(0));
1583    }
1584
1585    #[rstest]
1586    fn test_parse_decimal_opt() {
1587        assert_eq!(
1588            parse_decimal_opt(Some("123.45")).unwrap(),
1589            Some(dec!(123.45))
1590        );
1591        assert_eq!(parse_decimal_opt(Some("0")).unwrap(), None);
1592        assert_eq!(parse_decimal_opt(Some("")).unwrap(), None);
1593        assert_eq!(parse_decimal_opt(None).unwrap(), None);
1594    }
1595
1596    #[rstest]
1597    fn test_parse_spot_instrument() {
1598        let json = load_test_json("http_asset_pairs.json");
1599        let response: KrakenResponse<AssetPairsResponse> = serde_json::from_str(&json).unwrap();
1600        let pairs = response.result.unwrap();
1601
1602        let (pair_name, definition) = pairs.iter().next().unwrap();
1603
1604        let instrument = parse_spot_instrument(pair_name, definition, TS, TS).unwrap();
1605
1606        match instrument {
1607            InstrumentAny::CurrencyPair(pair) => {
1608                assert_eq!(pair.id.venue.as_str(), "KRAKEN");
1609                assert_eq!(pair.base_currency.code, "BTC");
1610                assert_eq!(pair.quote_currency.code, "USDT");
1611                assert_eq!(pair.price_increment.as_decimal(), dec!(0.1));
1612                assert_eq!(pair.size_increment.as_decimal(), dec!(0.00000001));
1613                assert!(pair.min_quantity.is_some());
1614                assert_eq!(pair.margin_init, dec!(0));
1615                assert_eq!(pair.margin_maint, dec!(0));
1616            }
1617            _ => panic!("Expected CurrencyPair"),
1618        }
1619    }
1620
1621    #[rstest]
1622    fn test_parse_futures_instrument_inverse() {
1623        let json = load_test_json("http_futures_instruments.json");
1624        let response: crate::http::models::FuturesInstrumentsResponse =
1625            serde_json::from_str(&json).unwrap();
1626
1627        let fut_instrument = &response.instruments[0];
1628
1629        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1630
1631        match instrument {
1632            InstrumentAny::CryptoPerpetual(perp) => {
1633                assert_eq!(perp.id.venue.as_str(), "KRAKEN");
1634                assert_eq!(perp.id.symbol.as_str(), "PI_XBTUSD");
1635                assert_eq!(perp.raw_symbol.as_str(), "PI_XBTUSD");
1636                assert_eq!(perp.base_currency.code, "BTC");
1637                assert_eq!(perp.quote_currency.code, "USD");
1638                assert_eq!(perp.settlement_currency.code, "BTC");
1639                assert!(perp.is_inverse);
1640                assert_eq!(perp.price_increment.as_decimal(), dec!(0.5));
1641                assert_eq!(perp.size_increment.as_decimal(), dec!(1));
1642                assert_eq!(perp.size_precision(), 0);
1643                assert_eq!(perp.margin_init, dec!(0.02));
1644                assert_eq!(perp.margin_maint, dec!(0.01));
1645            }
1646            _ => panic!("Expected CryptoPerpetual"),
1647        }
1648    }
1649
1650    #[rstest]
1651    fn test_parse_futures_instrument_flexible() {
1652        let json = load_test_json("http_futures_instruments.json");
1653        let response: crate::http::models::FuturesInstrumentsResponse =
1654            serde_json::from_str(&json).unwrap();
1655
1656        let fut_instrument = &response.instruments[1];
1657
1658        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1659
1660        match instrument {
1661            InstrumentAny::CryptoPerpetual(perp) => {
1662                assert_eq!(perp.id.venue.as_str(), "KRAKEN");
1663                assert_eq!(perp.id.symbol.as_str(), "PF_ETHUSD");
1664                assert_eq!(perp.raw_symbol.as_str(), "PF_ETHUSD");
1665                assert_eq!(perp.base_currency.code, "ETH");
1666                assert_eq!(perp.quote_currency.code, "USD");
1667                assert_eq!(perp.settlement_currency.code, "USD");
1668                assert!(!perp.is_inverse);
1669                assert_eq!(perp.price_increment.as_decimal(), dec!(0.1));
1670                assert_eq!(perp.size_increment.as_decimal(), dec!(0.001));
1671                assert_eq!(perp.size_precision(), 3);
1672                assert_eq!(perp.margin_init, dec!(0.02));
1673                assert_eq!(perp.margin_maint, dec!(0.01));
1674            }
1675            _ => panic!("Expected CryptoPerpetual"),
1676        }
1677    }
1678
1679    #[rstest]
1680    fn test_parse_futures_instrument_accepts_max_precision() {
1681        let json = load_test_json("http_futures_instruments.json");
1682        let response: crate::http::models::FuturesInstrumentsResponse =
1683            serde_json::from_str(&json).unwrap();
1684        let mut fut_instrument = response.instruments[1].clone();
1685        let tick_size = Decimal::try_new(1, u32::from(FIXED_PRECISION)).unwrap();
1686        fut_instrument.tick_size = tick_size;
1687
1688        let instrument = parse_futures_instrument(&fut_instrument, TS, TS).unwrap();
1689
1690        match instrument {
1691            InstrumentAny::CryptoPerpetual(perp) => {
1692                assert_eq!(perp.price_precision(), FIXED_PRECISION);
1693                assert_eq!(perp.price_increment.as_decimal(), tick_size);
1694            }
1695            _ => panic!("Expected CryptoPerpetual"),
1696        }
1697    }
1698
1699    #[cfg(feature = "high-precision")]
1700    #[rstest]
1701    fn test_parse_futures_instrument_negative_precision() {
1702        let json = load_test_json("http_futures_instruments.json");
1703        let response: crate::http::models::FuturesInstrumentsResponse =
1704            serde_json::from_str(&json).unwrap();
1705
1706        // PF_PEPEUSD has contractValueTradePrecision: -3 (trades in multiples of 1000)
1707        let fut_instrument = &response.instruments[2];
1708
1709        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1710
1711        match instrument {
1712            InstrumentAny::CryptoPerpetual(perp) => {
1713                assert_eq!(perp.id.symbol.as_str(), "PF_PEPEUSD");
1714                assert_eq!(perp.base_currency.code, "PEPE");
1715                assert!(!perp.is_inverse);
1716                assert_eq!(perp.size_increment.as_decimal(), dec!(1000));
1717                assert_eq!(perp.size_precision(), 0);
1718            }
1719            _ => panic!("Expected CryptoPerpetual"),
1720        }
1721    }
1722
1723    #[cfg(feature = "high-precision")]
1724    #[rstest]
1725    fn test_parse_futures_instrument_rejects_precision_above_high_max() {
1726        let json = load_test_json("http_futures_instruments.json");
1727        let response: crate::http::models::FuturesInstrumentsResponse =
1728            serde_json::from_str(&json).unwrap();
1729        let mut fut_instrument = response.instruments[1].clone();
1730        fut_instrument.tick_size = dec!(0.00000000000000001);
1731
1732        let error = parse_futures_instrument(&fut_instrument, TS, TS).unwrap_err();
1733
1734        assert_eq!(
1735            error.to_string(),
1736            "Cannot parse Kraken Futures instrument 'PF_ETHUSD': tick_size \
1737             0.00000000000000001 requires precision 17, but this build supports at most 16"
1738        );
1739    }
1740
1741    #[cfg(not(feature = "high-precision"))]
1742    #[rstest]
1743    fn test_parse_futures_instrument_rejects_unsupported_precision() {
1744        let json = load_test_json("http_futures_instruments.json");
1745        let response: crate::http::models::FuturesInstrumentsResponse =
1746            serde_json::from_str(&json).unwrap();
1747
1748        let tick_error = parse_futures_instrument(&response.instruments[2], TS, TS).unwrap_err();
1749
1750        let mut trade_precision_instrument = response.instruments[1].clone();
1751        trade_precision_instrument.contract_value_trade_precision = 256;
1752        let trade_precision_error =
1753            parse_futures_instrument(&trade_precision_instrument, TS, TS).unwrap_err();
1754
1755        let mut contract_size_instrument = response.instruments[1].clone();
1756        contract_size_instrument.contract_size = dec!(0.0000000001);
1757        let contract_size_error =
1758            parse_futures_instrument(&contract_size_instrument, TS, TS).unwrap_err();
1759
1760        assert_eq!(
1761            tick_error.to_string(),
1762            "Cannot parse Kraken Futures instrument 'PF_PEPEUSD': tick_size 0.0000000001 requires \
1763             precision 10, but this build supports at most 9; enable the 'high-precision' Cargo \
1764             feature and rebuild"
1765        );
1766        assert_eq!(
1767            trade_precision_error.to_string(),
1768            "Cannot parse Kraken Futures instrument 'PF_ETHUSD': contract_value_trade_precision 256 \
1769             requires precision 256, but this build supports at most 9; enable the 'high-precision' \
1770             Cargo feature and rebuild"
1771        );
1772        assert_eq!(
1773            contract_size_error.to_string(),
1774            "Cannot parse Kraken Futures instrument 'PF_ETHUSD': contract_size 0.0000000001 requires \
1775             precision 10, but this build supports at most 9; enable the 'high-precision' Cargo \
1776             feature and rebuild"
1777        );
1778    }
1779
1780    #[rstest]
1781    fn test_parse_futures_instrument_tokenized_underlying() {
1782        let json = load_test_json("http_futures_instruments.json");
1783        let response: crate::http::models::FuturesInstrumentsResponse =
1784            serde_json::from_str(&json).unwrap();
1785
1786        let fut_instrument = &response.instruments[3];
1787
1788        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1789
1790        match instrument {
1791            InstrumentAny::CryptoPerpetual(perp) => {
1792                assert_eq!(perp.id.symbol.as_str(), "PF_AAPLxUSD");
1793                assert_eq!(perp.raw_symbol.as_str(), "PF_AAPLxUSD");
1794                assert_eq!(perp.base_currency.code, "AAPLx");
1795                assert_eq!(perp.quote_currency.code, "USD");
1796                assert_eq!(perp.settlement_currency.code, "USD");
1797                assert!(!perp.is_inverse);
1798                assert_eq!(perp.price_increment.as_decimal(), dec!(0.01));
1799                assert_eq!(perp.size_increment.as_decimal(), dec!(0.01));
1800                assert_eq!(perp.size_precision(), 2);
1801                assert_eq!(perp.margin_init, dec!(0.2));
1802                assert_eq!(perp.margin_maint, dec!(0.1));
1803            }
1804            _ => panic!("Expected CryptoPerpetual"),
1805        }
1806    }
1807
1808    #[rstest]
1809    fn test_parse_futures_instrument_without_fee_schedule_uid() {
1810        let json = load_test_json("http_futures_instrument_no_fee_schedule.json");
1811        let response: crate::http::models::FuturesInstrumentsResponse =
1812            serde_json::from_str(&json).unwrap();
1813
1814        let fut_instrument = &response.instruments[0];
1815        assert!(fut_instrument.fee_schedule_uid.is_none());
1816
1817        let instrument = parse_futures_instrument(fut_instrument, TS, TS).unwrap();
1818        match instrument {
1819            InstrumentAny::CryptoPerpetual(perp) => {
1820                assert_eq!(perp.id.symbol.as_str(), "PF_ETHUSD");
1821            }
1822            _ => panic!("Expected CryptoPerpetual"),
1823        }
1824    }
1825
1826    #[rstest]
1827    fn test_parse_trade_tick_from_array() {
1828        let json = load_test_json("http_trades.json");
1829        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
1830        let result = wrapper.get("result").unwrap();
1831        let trades_map = result.as_object().unwrap();
1832
1833        // Get first pair's trades
1834        let (_pair, trades_value) = trades_map.iter().find(|(k, _)| *k != "last").unwrap();
1835        let trades = trades_value.as_array().unwrap();
1836        let trade_array = trades[0].as_array().unwrap();
1837
1838        // Create a mock instrument for testing
1839        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
1840        let instrument = InstrumentAny::CurrencyPair(
1841            CurrencyPair::builder()
1842                .instrument_id(instrument_id)
1843                .raw_symbol(Symbol::new("XBTUSDT"))
1844                .base_currency(Currency::BTC())
1845                .quote_currency(Currency::USDT())
1846                .price_precision(1)
1847                .size_precision(8)
1848                .price_increment(Price::from("0.1"))
1849                .size_increment(Quantity::from("0.00000001"))
1850                .ts_event(TS)
1851                .ts_init(TS)
1852                .build()
1853                .unwrap(),
1854        );
1855
1856        let trade_tick = parse_trade_tick_from_array(trade_array, &instrument, TS).unwrap();
1857
1858        assert_eq!(trade_tick.instrument_id, instrument_id);
1859        assert_eq!(trade_tick.price, Price::from("105433.60000"));
1860        assert_eq!(trade_tick.size, Quantity::from("0.00027625"));
1861    }
1862
1863    #[rstest]
1864    fn test_parse_bar() {
1865        let json = load_test_json("http_ohlc.json");
1866        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
1867        let result = wrapper.get("result").unwrap();
1868        let ohlc_map = result.as_object().unwrap();
1869
1870        // Get first pair's OHLC data
1871        let (_pair, ohlc_value) = ohlc_map.iter().find(|(k, _)| *k != "last").unwrap();
1872        let ohlcs = ohlc_value.as_array().unwrap();
1873
1874        // Parse first OHLC array into OhlcData
1875        let ohlc_array = ohlcs[0].as_array().unwrap();
1876        let ohlc = OhlcData {
1877            time: ohlc_array[0].as_i64().unwrap(),
1878            open: ohlc_array[1].as_str().unwrap().to_string(),
1879            high: ohlc_array[2].as_str().unwrap().to_string(),
1880            low: ohlc_array[3].as_str().unwrap().to_string(),
1881            close: ohlc_array[4].as_str().unwrap().to_string(),
1882            vwap: ohlc_array[5].as_str().unwrap().to_string(),
1883            volume: ohlc_array[6].as_str().unwrap().to_string(),
1884            count: ohlc_array[7].as_i64().unwrap(),
1885        };
1886
1887        // Create a mock instrument
1888        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
1889        let instrument = InstrumentAny::CurrencyPair(
1890            CurrencyPair::builder()
1891                .instrument_id(instrument_id)
1892                .raw_symbol(Symbol::new("XBTUSDT"))
1893                .base_currency(Currency::BTC())
1894                .quote_currency(Currency::USDT())
1895                .price_precision(1)
1896                .size_precision(8)
1897                .price_increment(Price::from("0.1"))
1898                .size_increment(Quantity::from("0.00000001"))
1899                .ts_event(TS)
1900                .ts_init(TS)
1901                .build()
1902                .unwrap(),
1903        );
1904
1905        let bar_type = BarType::new(
1906            instrument_id,
1907            BarSpecification::new(1, BarAggregation::Minute, PriceType::Last),
1908            AggregationSource::External,
1909        );
1910
1911        let bar = parse_bar(&ohlc, &instrument, bar_type, TS).unwrap();
1912
1913        assert_eq!(bar.bar_type, bar_type);
1914        assert_eq!(bar.open, Price::from("106038.2"));
1915        assert_eq!(bar.high, Price::from("106038.2"));
1916        assert_eq!(bar.low, Price::from("106038.2"));
1917        assert_eq!(bar.close, Price::from("106038.2"));
1918        assert_eq!(bar.volume, Quantity::from("0.00000000"));
1919    }
1920
1921    #[rstest]
1922    fn test_parse_millis_timestamp() {
1923        let timestamp = 1762795433.9717445;
1924        let result = parse_millis_timestamp(timestamp, "test").unwrap();
1925        assert!(result.as_u64() > 0);
1926    }
1927
1928    #[rstest]
1929    #[case(1, BarAggregation::Minute, 1)]
1930    #[case(5, BarAggregation::Minute, 5)]
1931    #[case(15, BarAggregation::Minute, 15)]
1932    #[case(1, BarAggregation::Hour, 60)]
1933    #[case(4, BarAggregation::Hour, 240)]
1934    #[case(1, BarAggregation::Day, 1440)]
1935    fn test_bar_type_to_spot_interval(
1936        #[case] step: usize,
1937        #[case] aggregation: BarAggregation,
1938        #[case] expected: u32,
1939    ) {
1940        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
1941        let bar_type = BarType::new(
1942            instrument_id,
1943            BarSpecification::new(step, aggregation, PriceType::Last),
1944            AggregationSource::External,
1945        );
1946
1947        let result = bar_type_to_spot_interval(bar_type).unwrap();
1948        assert_eq!(result, expected);
1949    }
1950
1951    #[rstest]
1952    fn test_bar_type_to_spot_interval_unsupported() {
1953        let instrument_id = InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE);
1954        let bar_type = BarType::new(
1955            instrument_id,
1956            BarSpecification::new(1, BarAggregation::Second, PriceType::Last),
1957            AggregationSource::External,
1958        );
1959
1960        let result = bar_type_to_spot_interval(bar_type);
1961        assert!(result.is_err());
1962        assert!(result.unwrap_err().to_string().contains("Unsupported"));
1963    }
1964
1965    #[rstest]
1966    #[case(1, BarAggregation::Minute, "1m")]
1967    #[case(5, BarAggregation::Minute, "5m")]
1968    #[case(15, BarAggregation::Minute, "15m")]
1969    #[case(1, BarAggregation::Hour, "1h")]
1970    #[case(4, BarAggregation::Hour, "4h")]
1971    #[case(12, BarAggregation::Hour, "12h")]
1972    #[case(1, BarAggregation::Day, "1d")]
1973    #[case(1, BarAggregation::Week, "1w")]
1974    fn test_bar_type_to_futures_resolution(
1975        #[case] step: usize,
1976        #[case] aggregation: BarAggregation,
1977        #[case] expected: &str,
1978    ) {
1979        let instrument_id = InstrumentId::new(Symbol::new("PI_XBTUSD"), *KRAKEN_VENUE);
1980        let bar_type = BarType::new(
1981            instrument_id,
1982            BarSpecification::new(step, aggregation, PriceType::Last),
1983            AggregationSource::External,
1984        );
1985
1986        let result = bar_type_to_futures_resolution(bar_type).unwrap();
1987        assert_eq!(result, expected);
1988    }
1989
1990    #[rstest]
1991    #[case(30, BarAggregation::Minute)] // Unsupported minute step
1992    #[case(2, BarAggregation::Hour)] // Unsupported hour step
1993    #[case(2, BarAggregation::Day)] // Unsupported day step
1994    #[case(1, BarAggregation::Second)] // Unsupported aggregation
1995    fn test_bar_type_to_futures_resolution_unsupported(
1996        #[case] step: usize,
1997        #[case] aggregation: BarAggregation,
1998    ) {
1999        let instrument_id = InstrumentId::new(Symbol::new("PI_XBTUSD"), *KRAKEN_VENUE);
2000        let bar_type = BarType::new(
2001            instrument_id,
2002            BarSpecification::new(step, aggregation, PriceType::Last),
2003            AggregationSource::External,
2004        );
2005
2006        let result = bar_type_to_futures_resolution(bar_type);
2007        assert!(result.is_err());
2008        assert!(result.unwrap_err().to_string().contains("Unsupported"));
2009    }
2010
2011    #[rstest]
2012    fn test_parse_order_status_report() {
2013        let json = load_test_json("http_open_orders.json");
2014        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
2015        let result = wrapper.get("result").unwrap();
2016        let open_map = result.get("open").unwrap();
2017        let orders: IndexMap<String, SpotOrder> = serde_json::from_value(open_map.clone()).unwrap();
2018
2019        let account_id = AccountId::new("KRAKEN-001");
2020        let instrument_id = InstrumentId::new(Symbol::new("BTC/USDT"), *KRAKEN_VENUE);
2021        let instrument = InstrumentAny::CurrencyPair(
2022            CurrencyPair::builder()
2023                .instrument_id(instrument_id)
2024                .raw_symbol(Symbol::new("XBTUSDT"))
2025                .base_currency(Currency::BTC())
2026                .quote_currency(Currency::USDT())
2027                .price_precision(2)
2028                .size_precision(8)
2029                .price_increment(Price::from("0.01"))
2030                .size_increment(Quantity::from("0.00000001"))
2031                .ts_event(TS)
2032                .ts_init(TS)
2033                .build()
2034                .unwrap(),
2035        );
2036
2037        let (order_id, order) = orders.iter().next().unwrap();
2038
2039        let report =
2040            parse_order_status_report(order_id, order, &instrument, account_id, TS).unwrap();
2041
2042        assert_eq!(report.account_id, account_id);
2043        assert_eq!(report.instrument_id, instrument_id);
2044        assert_eq!(report.venue_order_id.as_str(), order_id);
2045        assert_eq!(report.order_status, OrderStatus::Accepted);
2046        assert_eq!(report.quantity, Quantity::from("0.50000000"));
2047    }
2048
2049    /// An order ID with the price, trigger price and average fill price its report carries.
2050    type ExpectedPrices<'a> = (&'a str, Option<&'a str>, Option<&'a str>, Option<Decimal>);
2051
2052    /// A spot report carries the order's own prices, never the row's top-level `price`, which is
2053    /// the average fill price. The limit comes from `descr.price` for a limit order and from
2054    /// `descr.price2` for a stop-loss-limit or take-profit-limit order, or a trailing-stop-limit
2055    /// order once `misc` marks it `stopped`; a trailing-stop-limit's `limitprice`, the peak price,
2056    /// never stands in. The trigger comes from `stopprice`, which a non-trailing order fills only
2057    /// once triggered, so `descr.price` stands in before. Each row is a Kraken response listed in
2058    /// `test_data/README.md`.
2059    #[rstest]
2060    #[case::untriggered_open_orders(
2061        "http_open_orders_conditional.json",
2062        usdc_eur_instrument(),
2063        &[
2064            ("OCAP01-STOPL-000001", None, Some("1.3403"), None),
2065            ("OCAP02-STOPL-000002", None, Some("1.3402"), None),
2066            ("OCAP03-TAKEP-000003", None, Some("0.4467"), None),
2067            ("OCAP04-STLMT-000004", Some("1.3403"), Some("1.3403"), None),
2068            ("OCAP05-TPLMT-000005", Some("0.4467"), Some("0.4467"), None),
2069            ("OCAP06-TRAIL-000006", None, Some("1.3402"), None),
2070            ("OCAP07-TRLMT-000007", None, Some("1.3402"), None),
2071            ("OCAP08-LIMIT-000008", Some("0.4467"), None, None),
2072        ]
2073    )]
2074    #[case::untriggered_canceled_orders_one_amended(
2075        "http_closed_orders_conditional_canceled.json",
2076        usdc_eur_instrument(),
2077        &[
2078            ("OCAP01-STOPL-000001", None, Some("1.4296"), None),
2079            ("OCAP02-STOPL-000002", None, Some("1.3402"), None),
2080            ("OCAP03-TAKEP-000003", None, Some("0.4467"), None),
2081            ("OCAP04-STLMT-000004", Some("1.3403"), Some("1.3403"), None),
2082            ("OCAP05-TPLMT-000005", Some("0.4467"), Some("0.4467"), None),
2083            ("OCAP06-TRAIL-000006", None, Some("1.3401"), None),
2084            ("OCAP07-TRLMT-000007", None, Some("1.3401"), None),
2085            ("OCAP08-LIMIT-000008", Some("0.4467"), None, None),
2086        ]
2087    )]
2088    #[case::canceled_orders_three_triggered(
2089        "http_closed_orders_conditional_triggered.json",
2090        usdc_eur_instrument(),
2091        &[
2092            ("OCAP09-STLMT-000009", Some("0.4464"), Some("1.3394"), None),
2093            ("OCAP10-TPLMT-000010", Some("0.4455"), Some("0.4465"), None),
2094            ("OCAP11-STLMT-000011", Some("0.4464"), Some("0.8929"), None),
2095            ("OCAP12-TPLMT-000012", Some("0.4464"), Some("0.8929"), None),
2096            ("OCAP13-TRLMT-000013", Some("0.4465"), Some("0.8930"), None),
2097        ]
2098    )]
2099    #[case::documented_open_limit_orders(
2100        "http_open_orders_doc_example.json",
2101        xbt_usd_instrument(),
2102        &[
2103            ("OQCLML-BW3P3-BUCMWZ", Some("30010.0"), None, Some(dec!(11253.7) / dec!(0.375))),
2104            ("OB5VMB-B4U2U-DK2WRW", Some("14500.0"), None, None),
2105        ]
2106    )]
2107    #[case::documented_filled_market_order(
2108        "http_query_orders_doc_example.json",
2109        xbt_usd_instrument(),
2110        &[("OMMDB2-FSB6Z-7W3HPO", None, None, Some(dec!(30000)))]
2111    )]
2112    fn test_parse_order_status_report_prices_the_order_from_its_own_fields(
2113        #[case] filename: &str,
2114        #[case] instrument: InstrumentAny,
2115        #[case] expected: &[ExpectedPrices],
2116    ) {
2117        let rows = spot_order_rows(filename);
2118
2119        for &(order_id, expected_price, expected_trigger_price, expected_avg_px) in expected {
2120            let report = parse_order_status_report(
2121                order_id,
2122                &rows[order_id],
2123                &instrument,
2124                AccountId::new("KRAKEN-001"),
2125                TS,
2126            )
2127            .unwrap();
2128
2129            assert_eq!(report.price, expected_price.map(Price::from), "{order_id}");
2130            assert_eq!(
2131                report.trigger_price,
2132                expected_trigger_price.map(Price::from),
2133                "{order_id}"
2134            );
2135            assert_eq!(report.avg_px, expected_avg_px, "{order_id}");
2136        }
2137    }
2138
2139    /// A description price that is neither a price nor a relative expression fails the row. The
2140    /// input is synthetic: a captured limit row with its `descr.price` replaced.
2141    #[rstest]
2142    fn test_parse_order_status_report_fails_on_a_malformed_order_price() {
2143        let order_id = "OCAP08-LIMIT-000008";
2144        let mut order = spot_order_rows("http_open_orders_conditional.json")
2145            .swap_remove(order_id)
2146            .unwrap();
2147        order.descr.price = "abc".to_string();
2148
2149        let result = parse_order_status_report(
2150            order_id,
2151            &order,
2152            &usdc_eur_instrument(),
2153            AccountId::new("KRAKEN-001"),
2154            TS,
2155        );
2156
2157        assert!(result.is_err(), "{result:?}");
2158    }
2159
2160    /// An empty price or a relative expression reads as none rather than failing the row. The
2161    /// inputs are synthetic: a captured stop-loss row with its `stopprice` replaced, so
2162    /// `descr.price` stands in.
2163    #[rstest]
2164    #[case::empty("")]
2165    #[case::relative("+1.5%")]
2166    fn test_parse_order_status_report_reads_an_unpriced_stop_price_as_none(
2167        #[case] stop_price: &str,
2168    ) {
2169        let order_id = "OCAP02-STOPL-000002";
2170        let mut order = spot_order_rows("http_open_orders_conditional.json")
2171            .swap_remove(order_id)
2172            .unwrap();
2173        order.stopprice = Some(stop_price.to_string());
2174
2175        let report = parse_order_status_report(
2176            order_id,
2177            &order,
2178            &usdc_eur_instrument(),
2179            AccountId::new("KRAKEN-001"),
2180            TS,
2181        )
2182        .unwrap();
2183
2184        assert_eq!(report.trigger_price, Some(Price::from("1.3402")));
2185    }
2186
2187    /// An untriggered trailing-stop-limit carries no price whatever its `descr.price2` holds, so an
2188    /// unsigned offset, the form Nautilus submits, never reads as its limit. The input is
2189    /// synthetic: a captured untriggered row with its offset written unsigned.
2190    #[rstest]
2191    fn test_parse_order_status_report_prices_no_untriggered_trailing_stop_limit() {
2192        let order_id = "OCAP07-TRLMT-000007";
2193        let mut order = spot_order_rows("http_open_orders_conditional.json")
2194            .swap_remove(order_id)
2195            .unwrap();
2196        order.descr.price2 = "1.0000".to_string();
2197
2198        let report = parse_order_status_report(
2199            order_id,
2200            &order,
2201            &usdc_eur_instrument(),
2202            AccountId::new("KRAKEN-001"),
2203            TS,
2204        )
2205        .unwrap();
2206
2207        assert_eq!(report.price, None);
2208        assert_eq!(report.trigger_price, Some(Price::from("1.3402")));
2209    }
2210
2211    /// The rows of a spot OpenOrders, ClosedOrders or QueryOrders response in `test_data`.
2212    fn spot_order_rows(filename: &str) -> IndexMap<String, SpotOrder> {
2213        let json = load_test_json(filename);
2214        if filename.starts_with("http_open_orders") {
2215            let response: KrakenResponse<SpotOpenOrdersResult> =
2216                serde_json::from_str(&json).unwrap();
2217            response.result.unwrap().open
2218        } else if filename.starts_with("http_closed_orders") {
2219            let response: KrakenResponse<SpotClosedOrdersResult> =
2220                serde_json::from_str(&json).unwrap();
2221            response.result.unwrap().closed
2222        } else {
2223            let response: KrakenResponse<IndexMap<String, SpotOrder>> =
2224                serde_json::from_str(&json).unwrap();
2225            response.result.unwrap()
2226        }
2227    }
2228
2229    fn usdc_eur_instrument() -> InstrumentAny {
2230        InstrumentAny::CurrencyPair(
2231            CurrencyPair::builder()
2232                .instrument_id(InstrumentId::new(Symbol::new("USDC/EUR"), *KRAKEN_VENUE))
2233                .raw_symbol(Symbol::new("USDCEUR"))
2234                .base_currency(Currency::USDC())
2235                .quote_currency(Currency::EUR())
2236                .price_precision(4)
2237                .size_precision(8)
2238                .price_increment(Price::from("0.0001"))
2239                .size_increment(Quantity::from("0.00000001"))
2240                .ts_event(TS)
2241                .ts_init(TS)
2242                .build()
2243                .unwrap(),
2244        )
2245    }
2246
2247    fn xbt_usd_instrument() -> InstrumentAny {
2248        InstrumentAny::CurrencyPair(
2249            CurrencyPair::builder()
2250                .instrument_id(InstrumentId::new(Symbol::new("BTC/USD"), *KRAKEN_VENUE))
2251                .raw_symbol(Symbol::new("XBTUSD"))
2252                .base_currency(Currency::BTC())
2253                .quote_currency(Currency::USD())
2254                .price_precision(1)
2255                .size_precision(8)
2256                .price_increment(Price::from("0.1"))
2257                .size_increment(Quantity::from("0.00000001"))
2258                .ts_event(TS)
2259                .ts_init(TS)
2260                .build()
2261                .unwrap(),
2262        )
2263    }
2264
2265    fn create_mock_perp() -> InstrumentAny {
2266        let instrument_id = InstrumentId::new(Symbol::new("PI_XBTUSD"), *KRAKEN_VENUE);
2267        InstrumentAny::CryptoPerpetual(
2268            CryptoPerpetual::builder()
2269                .instrument_id(instrument_id)
2270                .raw_symbol(Symbol::new("PI_XBTUSD"))
2271                .base_currency(Currency::BTC())
2272                .quote_currency(Currency::USD())
2273                .settlement_currency(Currency::USD())
2274                .is_inverse(false)
2275                .price_precision(1)
2276                .size_precision(0)
2277                .price_increment(Price::from("0.5"))
2278                .size_increment(Quantity::from("1"))
2279                .ts_event(TS)
2280                .ts_init(TS)
2281                .build()
2282                .unwrap(),
2283        )
2284    }
2285
2286    #[rstest]
2287    fn test_parse_futures_assignee_fill_report() {
2288        let json = load_test_json("http_futures_fills.json");
2289        let response: FuturesFillsResponse = serde_json::from_str(&json).unwrap();
2290        let fill = &response.fills[2];
2291        let instrument = create_mock_perp();
2292        let account_id = AccountId::new("KRAKEN-001");
2293
2294        let report = parse_futures_fill_report(fill, &instrument, account_id, TS).unwrap();
2295
2296        assert_eq!(report.account_id, account_id);
2297        assert_eq!(report.instrument_id, instrument.id());
2298        assert_eq!(
2299            report.venue_order_id,
2300            VenueOrderId::new("f8a7b6c5-d4e3-2f1a-0b9c-8d7e6f5a4b3c")
2301        );
2302        assert_eq!(
2303            report.trade_id,
2304            TradeId::new("d3f4e5a6-b7c8-9d0e-1f2a-3b4c5d6e7f8a")
2305        );
2306        assert_eq!(report.order_side, OrderSide::Sell);
2307        assert_eq!(report.last_qty, Quantity::from("2500"));
2308        assert_eq!(report.last_px, Price::from("28050.0"));
2309        assert_eq!(report.commission, Money::zero(Currency::USD()));
2310        assert_eq!(report.liquidity_side, LiquiditySide::NoLiquiditySide);
2311        assert_eq!(report.avg_px, None);
2312        assert_eq!(
2313            report.ts_event,
2314            "2023-04-07T15:55:20.123Z".parse::<UnixNanos>().unwrap()
2315        );
2316        assert_eq!(report.ts_init, TS);
2317        assert_eq!(report.client_order_id, None);
2318        assert_eq!(report.venue_position_id, None);
2319    }
2320
2321    #[rstest]
2322    fn test_parse_venue_order_id_returns_a_valid_id() {
2323        assert_eq!(
2324            parse_venue_order_id("OABCDE-12345-FGHIJ", "spot order").unwrap(),
2325            VenueOrderId::new("OABCDE-12345-FGHIJ")
2326        );
2327    }
2328
2329    /// An order ID the model cannot hold is an error, whichever way it is invalid: the panicking
2330    /// constructor would abort a release build. The error names the payload the caller gives.
2331    #[rstest]
2332    #[case::empty("")]
2333    #[case::whitespace("   ")]
2334    #[case::non_ascii("\u{e9}")]
2335    fn test_parse_venue_order_id_fails_on_an_invalid_id(#[case] order_id: &str) {
2336        let fill_id = "F-1";
2337
2338        let error =
2339            parse_venue_order_id(order_id, format_args!("futures fill {fill_id}")).unwrap_err();
2340
2341        assert_eq!(
2342            error.to_string(),
2343            format!("Invalid order_id '{order_id}' in Kraken futures fill F-1")
2344        );
2345    }
2346
2347    #[rstest]
2348    fn test_parse_order_status_report_fails_on_an_invalid_order_id() {
2349        let order = spot_order_rows("http_open_orders_conditional.json")
2350            .swap_remove("OCAP08-LIMIT-000008")
2351            .unwrap();
2352
2353        let error = parse_order_status_report(
2354            "",
2355            &order,
2356            &usdc_eur_instrument(),
2357            AccountId::new("KRAKEN-001"),
2358            TS,
2359        )
2360        .unwrap_err();
2361
2362        assert_eq!(
2363            error.to_string(),
2364            "Invalid order_id '' in Kraken spot order"
2365        );
2366    }
2367
2368    #[rstest]
2369    fn test_parse_fill_report_fails_on_an_invalid_order_id() {
2370        let json = load_test_json("http_trades_history.json");
2371        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
2372        let mut trades: IndexMap<String, SpotTrade> =
2373            serde_json::from_value(wrapper["result"]["trades"].clone()).unwrap();
2374        let (trade_id, trade) = trades.first_mut().unwrap();
2375        trade.ordertxid = String::new();
2376
2377        let error = parse_fill_report(
2378            trade_id,
2379            trade,
2380            &usdc_eur_instrument(),
2381            AccountId::new("KRAKEN-001"),
2382            TS,
2383        )
2384        .unwrap_err();
2385
2386        assert_eq!(
2387            error.to_string(),
2388            "Invalid order_id '' in Kraken spot trade"
2389        );
2390    }
2391
2392    #[rstest]
2393    fn test_parse_futures_order_status_report_fails_on_an_invalid_order_id() {
2394        let json = load_test_json("http_futures_open_orders.json");
2395        let mut response: FuturesOpenOrdersResponse = serde_json::from_str(&json).unwrap();
2396        let mut order = response.open_orders.swap_remove(0);
2397        order.order_id = String::new();
2398
2399        let error = parse_futures_order_status_report(
2400            &order,
2401            &create_mock_perp(),
2402            AccountId::new("KRAKEN-001"),
2403            None,
2404            TS,
2405        )
2406        .unwrap_err();
2407
2408        assert_eq!(
2409            error.to_string(),
2410            "Invalid order_id '' in Kraken futures open order"
2411        );
2412    }
2413
2414    /// The history decoder validates its uid; the post-submit send events reach this parser with
2415    /// an ID nothing has checked.
2416    #[rstest]
2417    fn test_parse_futures_order_event_status_report_fails_on_an_invalid_order_id() {
2418        let event = FuturesOrderEvent {
2419            order_id: String::new(),
2420            cli_ord_id: None,
2421            order_type: KrakenFuturesOrderType::Limit,
2422            symbol: "PI_XBTUSD".to_string(),
2423            side: KrakenOrderSide::Sell,
2424            quantity: dec!(200),
2425            filled: Decimal::ZERO,
2426            limit_price: Some(dec!(39500)),
2427            stop_price: None,
2428            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2429            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2430            reduce_only: false,
2431            time_in_force: TimeInForce::Gtc,
2432            post_only: false,
2433        };
2434
2435        let error = parse_futures_order_event_status_report(
2436            &event,
2437            None,
2438            &create_mock_perp(),
2439            AccountId::new("KRAKEN-001"),
2440            TS,
2441        )
2442        .unwrap_err();
2443
2444        assert_eq!(
2445            error.to_string(),
2446            "Invalid order_id '' in Kraken futures order event"
2447        );
2448    }
2449
2450    #[rstest]
2451    fn test_parse_futures_order_status_details_report_fails_on_an_invalid_order_id() {
2452        let json = load_test_json("http_futures_orders_status.json");
2453        let mut response: FuturesOrdersStatusResponse = serde_json::from_str(&json).unwrap();
2454        let mut details = response.orders.swap_remove(0);
2455        details.order.order_id = String::new();
2456
2457        let error = parse_futures_order_status_details_report(
2458            &details,
2459            &create_mock_perp(),
2460            AccountId::new("KRAKEN-001"),
2461            TS,
2462        )
2463        .unwrap_err();
2464
2465        assert_eq!(
2466            error.to_string(),
2467            "Invalid order_id '' in Kraken futures order status"
2468        );
2469    }
2470
2471    #[rstest]
2472    fn test_parse_futures_fill_report_fails_on_an_invalid_order_id() {
2473        let json = load_test_json("http_futures_fills.json");
2474        let mut response: FuturesFillsResponse = serde_json::from_str(&json).unwrap();
2475        let mut fill = response.fills.swap_remove(0);
2476        fill.order_id = String::new();
2477
2478        let error =
2479            parse_futures_fill_report(&fill, &create_mock_perp(), AccountId::new("KRAKEN-001"), TS)
2480                .unwrap_err();
2481
2482        assert_eq!(
2483            error.to_string(),
2484            "Invalid order_id '' in Kraken futures fill"
2485        );
2486    }
2487
2488    #[rstest]
2489    fn test_parse_futures_order_status_report_market_if_touched() {
2490        let order = FuturesOpenOrder {
2491            order_id: "tp-001".to_string(),
2492            symbol: "PI_XBTUSD".to_string(),
2493            side: KrakenOrderSide::Buy,
2494            order_type: KrakenFuturesOrderType::TakeProfit,
2495            limit_price: None,
2496            stop_price: Some(dec!(36000)),
2497            unfilled_size: Some(dec!(500)),
2498            received_time: "2023-11-14T22:13:20.000Z".to_string(),
2499            status: KrakenFuturesOrderStatus::PartiallyFilled,
2500            filled_size: dec!(25),
2501            reduce_only: Some(true),
2502            last_update_time: "2023-11-14T22:13:20.000Z".to_string(),
2503            trigger_signal: None,
2504            cli_ord_id: Some("my-tp-1".to_string()),
2505            cli_ord_id_snake_case: None,
2506        };
2507        let instrument = create_mock_perp();
2508        let account_id = AccountId::new("KRAKEN-001");
2509
2510        let report =
2511            parse_futures_order_status_report(&order, &instrument, account_id, None, TS).unwrap();
2512
2513        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2514        assert_eq!(report.quantity.as_decimal(), dec!(525));
2515        assert_eq!(report.filled_qty.as_decimal(), dec!(25));
2516        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(36000));
2517        assert!(report.price.is_none());
2518        assert!(report.reduce_only);
2519        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
2520    }
2521
2522    /// The `ioc` and `post` types reach the report as `IOC` and post-only `GTC`, and any other type
2523    /// stays `GTC` and not post-only.
2524    #[rstest]
2525    #[case::limit(KrakenFuturesOrderType::Limit, TimeInForce::Gtc, false)]
2526    #[case::ioc(KrakenFuturesOrderType::Ioc, TimeInForce::Ioc, false)]
2527    #[case::post(KrakenFuturesOrderType::Post, TimeInForce::Gtc, true)]
2528    #[case::stop(KrakenFuturesOrderType::StopLower, TimeInForce::Gtc, false)]
2529    #[case::take_profit(KrakenFuturesOrderType::TakeProfit, TimeInForce::Gtc, false)]
2530    fn test_parse_futures_order_status_report_time_in_force(
2531        #[case] order_type: KrakenFuturesOrderType,
2532        #[case] time_in_force: TimeInForce,
2533        #[case] post_only: bool,
2534    ) {
2535        let order = FuturesOpenOrder {
2536            order_id: "tif-001".to_string(),
2537            symbol: "PI_XBTUSD".to_string(),
2538            side: KrakenOrderSide::Buy,
2539            order_type,
2540            limit_price: Some(dec!(36000)),
2541            stop_price: None,
2542            unfilled_size: Some(dec!(500)),
2543            received_time: "2023-11-14T22:13:20.000Z".to_string(),
2544            status: KrakenFuturesOrderStatus::Untouched,
2545            filled_size: Decimal::ZERO,
2546            reduce_only: Some(false),
2547            last_update_time: "2023-11-14T22:13:20.000Z".to_string(),
2548            trigger_signal: None,
2549            cli_ord_id: None,
2550            cli_ord_id_snake_case: None,
2551        };
2552
2553        let report = parse_futures_order_status_report(
2554            &order,
2555            &create_mock_perp(),
2556            AccountId::new("KRAKEN-001"),
2557            None,
2558            TS,
2559        )
2560        .unwrap();
2561
2562        assert_eq!(report.time_in_force, time_in_force);
2563        assert_eq!(report.post_only, post_only);
2564    }
2565
2566    #[rstest]
2567    fn test_parse_futures_order_status_report_limit_if_touched() {
2568        let order = FuturesOpenOrder {
2569            order_id: "tpl-001".to_string(),
2570            symbol: "PI_XBTUSD".to_string(),
2571            side: KrakenOrderSide::Sell,
2572            order_type: KrakenFuturesOrderType::TakeProfit,
2573            limit_price: Some(dec!(35500)),
2574            stop_price: Some(dec!(36000)),
2575            unfilled_size: Some(dec!(500)),
2576            received_time: "2023-11-14T22:13:20.000Z".to_string(),
2577            status: KrakenFuturesOrderStatus::Untouched,
2578            filled_size: dec!(0),
2579            reduce_only: None,
2580            last_update_time: "2023-11-14T22:13:20.000Z".to_string(),
2581            trigger_signal: None,
2582            cli_ord_id: Some("my-tpl-1".to_string()),
2583            cli_ord_id_snake_case: None,
2584        };
2585        let instrument = create_mock_perp();
2586        let account_id = AccountId::new("KRAKEN-001");
2587
2588        let report =
2589            parse_futures_order_status_report(&order, &instrument, account_id, None, TS).unwrap();
2590
2591        assert_eq!(report.order_type, OrderType::LimitIfTouched);
2592        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(36000));
2593        assert_eq!(report.price.unwrap().as_decimal(), dec!(35500));
2594        assert_eq!(report.order_side, OrderSide::Sell.into());
2595        assert!(!report.reduce_only);
2596    }
2597
2598    #[rstest]
2599    fn test_parse_futures_order_event_market_if_touched() {
2600        let event = FuturesOrderEvent {
2601            order_id: "tp-evt-001".to_string(),
2602            cli_ord_id: None,
2603            order_type: KrakenFuturesOrderType::TakeProfit,
2604            symbol: "PI_XBTUSD".to_string(),
2605            side: KrakenOrderSide::Buy,
2606            quantity: dec!(100),
2607            filled: dec!(100),
2608            limit_price: None,
2609            stop_price: Some(dec!(40000)),
2610            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2611            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2612            reduce_only: false,
2613            time_in_force: TimeInForce::Gtc,
2614            post_only: false,
2615        };
2616        let instrument = create_mock_perp();
2617        let account_id = AccountId::new("KRAKEN-001");
2618
2619        let report = parse_futures_order_event_status_report(
2620            &event,
2621            Some(KrakenFuturesOrderEventType::Fill),
2622            &instrument,
2623            account_id,
2624            TS,
2625        )
2626        .unwrap();
2627
2628        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2629        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(40000));
2630        assert!(report.price.is_none());
2631        assert_eq!(report.order_status, OrderStatus::Filled);
2632    }
2633
2634    #[rstest]
2635    fn test_parse_futures_order_event_limit_if_touched() {
2636        let event = FuturesOrderEvent {
2637            order_id: "tpl-evt-001".to_string(),
2638            cli_ord_id: Some("my-tpl-evt".to_string()),
2639            order_type: KrakenFuturesOrderType::TakeProfit,
2640            symbol: "PI_XBTUSD".to_string(),
2641            side: KrakenOrderSide::Sell,
2642            quantity: dec!(200),
2643            filled: Decimal::ZERO,
2644            limit_price: Some(dec!(39500)),
2645            stop_price: Some(dec!(40000)),
2646            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2647            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2648            reduce_only: true,
2649            time_in_force: TimeInForce::Gtc,
2650            post_only: false,
2651        };
2652        let instrument = create_mock_perp();
2653        let account_id = AccountId::new("KRAKEN-001");
2654
2655        let report = parse_futures_order_event_status_report(
2656            &event,
2657            Some(KrakenFuturesOrderEventType::Place),
2658            &instrument,
2659            account_id,
2660            TS,
2661        )
2662        .unwrap();
2663
2664        assert_eq!(report.order_type, OrderType::LimitIfTouched);
2665        assert_eq!(report.trigger_price.unwrap().as_decimal(), dec!(40000));
2666        assert_eq!(report.price.unwrap().as_decimal(), dec!(39500));
2667        assert_eq!(report.order_side, OrderSide::Sell.into());
2668        assert_eq!(report.order_status, OrderStatus::Accepted);
2669        assert!(report.reduce_only);
2670    }
2671
2672    #[rstest]
2673    fn test_parse_futures_order_event_cancel_status() {
2674        let event = FuturesOrderEvent {
2675            order_id: "cancel-evt-001".to_string(),
2676            cli_ord_id: Some("cancel-evt".to_string()),
2677            order_type: KrakenFuturesOrderType::Stop,
2678            symbol: "PI_XBTUSD".to_string(),
2679            side: KrakenOrderSide::Sell,
2680            quantity: dec!(200),
2681            filled: Decimal::ZERO,
2682            limit_price: None,
2683            stop_price: Some(dec!(39000)),
2684            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2685            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2686            reduce_only: true,
2687            time_in_force: TimeInForce::Gtc,
2688            post_only: false,
2689        };
2690        let instrument = create_mock_perp();
2691        let account_id = AccountId::new("KRAKEN-001");
2692
2693        let report = parse_futures_order_event_status_report(
2694            &event,
2695            Some(KrakenFuturesOrderEventType::Cancel),
2696            &instrument,
2697            account_id,
2698            TS,
2699        )
2700        .unwrap();
2701
2702        assert_eq!(report.order_status, OrderStatus::Canceled);
2703        assert!(report.reduce_only);
2704    }
2705
2706    #[rstest]
2707    fn test_parse_futures_order_event_reject_status() {
2708        let event = FuturesOrderEvent {
2709            order_id: "reject-evt-001".to_string(),
2710            cli_ord_id: Some("reject-evt".to_string()),
2711            order_type: KrakenFuturesOrderType::Limit,
2712            symbol: "PI_XBTUSD".to_string(),
2713            side: KrakenOrderSide::Buy,
2714            quantity: dec!(200),
2715            filled: Decimal::ZERO,
2716            limit_price: Some(dec!(35000)),
2717            stop_price: None,
2718            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2719            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2720            reduce_only: false,
2721            time_in_force: TimeInForce::Gtc,
2722            post_only: false,
2723        };
2724        let instrument = create_mock_perp();
2725        let account_id = AccountId::new("KRAKEN-001");
2726
2727        let report = parse_futures_order_event_status_report(
2728            &event,
2729            Some(KrakenFuturesOrderEventType::Reject),
2730            &instrument,
2731            account_id,
2732            TS,
2733        )
2734        .unwrap();
2735
2736        assert_eq!(report.order_status, OrderStatus::Rejected);
2737    }
2738
2739    #[rstest]
2740    fn test_parse_futures_order_event_expire_status() {
2741        let event = FuturesOrderEvent {
2742            order_id: "expire-evt-001".to_string(),
2743            cli_ord_id: Some("expire-evt".to_string()),
2744            order_type: KrakenFuturesOrderType::Limit,
2745            symbol: "PI_XBTUSD".to_string(),
2746            side: KrakenOrderSide::Buy,
2747            quantity: dec!(200),
2748            filled: Decimal::ZERO,
2749            limit_price: Some(dec!(35000)),
2750            stop_price: None,
2751            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2752            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2753            reduce_only: false,
2754            time_in_force: TimeInForce::Gtc,
2755            post_only: false,
2756        };
2757        let instrument = create_mock_perp();
2758        let account_id = AccountId::new("KRAKEN-001");
2759
2760        let report = parse_futures_order_event_status_report(
2761            &event,
2762            Some(KrakenFuturesOrderEventType::Expire),
2763            &instrument,
2764            account_id,
2765            TS,
2766        )
2767        .unwrap();
2768
2769        assert_eq!(report.order_status, OrderStatus::Expired);
2770    }
2771
2772    #[rstest]
2773    fn test_parse_futures_order_event_execution_status() {
2774        let event = FuturesOrderEvent {
2775            order_id: "execution-evt-001".to_string(),
2776            cli_ord_id: Some("execution-evt".to_string()),
2777            order_type: KrakenFuturesOrderType::Limit,
2778            symbol: "PI_XBTUSD".to_string(),
2779            side: KrakenOrderSide::Buy,
2780            quantity: dec!(200),
2781            filled: dec!(50),
2782            limit_price: Some(dec!(35000)),
2783            stop_price: None,
2784            timestamp: "2023-11-14T22:13:20.000Z".to_string(),
2785            last_update_timestamp: "2023-11-14T22:13:21.000Z".to_string(),
2786            reduce_only: false,
2787            time_in_force: TimeInForce::Gtc,
2788            post_only: false,
2789        };
2790        let instrument = create_mock_perp();
2791        let account_id = AccountId::new("KRAKEN-001");
2792
2793        let report = parse_futures_order_event_status_report(
2794            &event,
2795            Some(KrakenFuturesOrderEventType::Execution),
2796            &instrument,
2797            account_id,
2798            TS,
2799        )
2800        .unwrap();
2801
2802        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
2803    }
2804
2805    #[rstest]
2806    fn test_parse_fill_report() {
2807        let json = load_test_json("http_trades_history.json");
2808        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
2809        let result = wrapper.get("result").unwrap();
2810        let trades_map = result.get("trades").unwrap();
2811        let trades: IndexMap<String, SpotTrade> =
2812            serde_json::from_value(trades_map.clone()).unwrap();
2813
2814        let account_id = AccountId::new("KRAKEN-001");
2815        let instrument_id = InstrumentId::new(Symbol::new("BTC/USDT"), *KRAKEN_VENUE);
2816        let instrument = InstrumentAny::CurrencyPair(
2817            CurrencyPair::builder()
2818                .instrument_id(instrument_id)
2819                .raw_symbol(Symbol::new("XBTUSDT"))
2820                .base_currency(Currency::BTC())
2821                .quote_currency(Currency::USDT())
2822                .price_precision(2)
2823                .size_precision(8)
2824                .price_increment(Price::from("0.01"))
2825                .size_increment(Quantity::from("0.00000001"))
2826                .ts_event(TS)
2827                .ts_init(TS)
2828                .build()
2829                .unwrap(),
2830        );
2831
2832        let (trade_id, trade) = trades.iter().next().unwrap();
2833
2834        let report = parse_fill_report(trade_id, trade, &instrument, account_id, TS).unwrap();
2835
2836        assert_eq!(report.account_id, account_id);
2837        assert_eq!(report.instrument_id, instrument_id);
2838        assert_eq!(report.trade_id.to_string(), *trade_id);
2839        assert_eq!(report.last_qty, Quantity::from("0.50000000"));
2840        assert_eq!(report.last_px, Price::from("29500.50"));
2841        assert_eq!(report.commission.as_decimal(), dec!(23.60));
2842    }
2843
2844    #[rstest]
2845    #[case("XXBT", "BTC")]
2846    #[case("XBT", "BTC")]
2847    #[case("XXDG", "DOGE")]
2848    #[case("XDG", "DOGE")]
2849    #[case("XETH", "ETH")]
2850    #[case("ZUSD", "USD")]
2851    #[case("ZEUR", "EUR")]
2852    #[case("KFEE", "FEE")]
2853    #[case("BTC", "BTC")]
2854    #[case("ETH", "ETH")]
2855    #[case("USDT", "USDT")]
2856    #[case("SOL", "SOL")]
2857    // Codes that legitimately begin with X or Z must survive: a prefix strip would corrupt them.
2858    #[case("XTZ", "XTZ")]
2859    #[case("XRP", "XRP")]
2860    #[case("XLM", "XLM")]
2861    #[case("XAUT", "XAUT")]
2862    #[case("XCN", "XCN")]
2863    #[case("ZRX", "ZRX")]
2864    #[case("ZEC", "ZEC")]
2865    #[case("ZK", "ZK")]
2866    fn test_normalize_currency_code(#[case] input: &str, #[case] expected: &str) {
2867        assert_eq!(normalize_currency_code(input), expected);
2868    }
2869
2870    /// Kraken Futures keys account balances by its own spelling, which is not upper case.
2871    #[rstest]
2872    #[case("xbt", "BTC")]
2873    #[case("XBT", "BTC")]
2874    #[case("xxbt", "BTC")]
2875    #[case("zeur", "EUR")]
2876    #[case("usd", "USD")]
2877    #[case("xtz", "XTZ")]
2878    #[case("flr", "FLR")]
2879    fn test_normalize_asset_key_is_case_tolerant(#[case] input: &str, #[case] expected: &str) {
2880        assert_eq!(normalize_asset_key(input), expected);
2881    }
2882
2883    #[rstest]
2884    #[case("XBT/EUR", "BTC/EUR")]
2885    #[case("XBT/USD", "BTC/USD")]
2886    #[case("XBT/USDT", "BTC/USDT")]
2887    #[case("ETH/USD", "ETH/USD")]
2888    #[case("ETH/XBT", "ETH/BTC")]
2889    #[case("SOL/XBT", "SOL/BTC")]
2890    #[case("SOL/USD", "SOL/USD")]
2891    #[case("BTC/USD", "BTC/USD")]
2892    #[case("ETH/BTC", "ETH/BTC")]
2893    #[case("XDG/USD", "DOGE/USD")]
2894    #[case("XDG/EUR", "DOGE/EUR")]
2895    #[case("XDG/BTC", "DOGE/BTC")]
2896    #[case("XDG/XBT", "DOGE/BTC")]
2897    fn test_normalize_spot_symbol(#[case] input: &str, #[case] expected: &str) {
2898        assert_eq!(normalize_spot_symbol(input), expected);
2899    }
2900
2901    #[rstest]
2902    #[case("A", "A")] // 1 char, minimum
2903    #[case("O2026022700232", "O2026022700232")] // 14 chars, typical short
2904    #[case("ABCDEFGHIJKLMNOPQR", "ABCDEFGHIJKLMNOPQR")] // 18 chars, at limit
2905    fn test_truncate_cl_ord_id_short_passthrough(#[case] input: &str, #[case] expected: &str) {
2906        let id = ClientOrderId::new(input);
2907        assert_eq!(truncate_cl_ord_id(&id), expected);
2908    }
2909
2910    #[rstest]
2911    #[case("6d47a5f0-6fd4-4b84-b56e-c23f0f689c20")] // lowercase hex
2912    #[case("6D47A5F0-6FD4-4B84-B56E-C23F0F689C20")] // uppercase hex
2913    #[case("00000000-0000-0000-0000-000000000000")] // nil UUID
2914    #[case("ffffffff-ffff-ffff-ffff-ffffffffffff")] // max UUID
2915    fn test_truncate_cl_ord_id_uuid_hyphenated_passthrough(#[case] input: &str) {
2916        let id = ClientOrderId::new(input);
2917        assert_eq!(truncate_cl_ord_id(&id), input);
2918    }
2919
2920    #[rstest]
2921    #[case("6d47a5f06fd44b84b56ec23f0f689c20")] // lowercase
2922    #[case("6D47A5F06FD44B84B56EC23F0F689C20")] // uppercase
2923    #[case("00000000000000000000000000000000")] // all zeros
2924    #[case("aAbBcCdDeEfF00112233445566778899")] // mixed case
2925    fn test_truncate_cl_ord_id_uuid_compact_passthrough(#[case] input: &str) {
2926        let id = ClientOrderId::new(input);
2927        assert_eq!(truncate_cl_ord_id(&id), input);
2928    }
2929
2930    #[rstest]
2931    #[case("O2026022700232100400", "O26022700232100400")] // 20 chars → O + last 17
2932    #[case("O202602270023210040011", "O02270023210040011")] // 22 chars, typical sequential
2933    #[case("O20260227002321004001100", "O27002321004001100")] // 24 chars
2934    fn test_truncate_cl_ord_id_sequential_truncated(#[case] input: &str, #[case] expected: &str) {
2935        let id = ClientOrderId::new(input);
2936        let result = truncate_cl_ord_id(&id);
2937        assert_eq!(result, expected);
2938        assert_eq!(result.len(), 18);
2939        assert!(result.starts_with('O'));
2940    }
2941
2942    #[rstest]
2943    fn test_truncate_cl_ord_id_32_chars_non_hex_truncated() {
2944        let input = "0123456789abcdef0123456789abcdeg";
2945        let id = ClientOrderId::new(input);
2946        let result = truncate_cl_ord_id(&id);
2947        assert_eq!(result.len(), 18);
2948        assert!(result.starts_with('O'));
2949        assert_eq!(result, "Of0123456789abcdeg");
2950    }
2951
2952    #[rstest]
2953    fn test_truncate_cl_ord_id_36_chars_wrong_hyphens_truncated() {
2954        let input = "6d47a5f0-6fd4-4b84-b56ec23f0f689c200";
2955        let id = ClientOrderId::new(input);
2956        let result = truncate_cl_ord_id(&id);
2957        assert_eq!(result.len(), 18);
2958        assert!(result.starts_with('O'));
2959    }
2960
2961    /// The wire price scale is recorded only when `pair_decimals` is finer than the tick
2962    /// precision: an equal or coarser scale leaves the key absent.
2963    #[rstest]
2964    fn test_pair_info_records_pair_decimals_only_when_finer_than_the_tick() {
2965        let json = load_test_json("http_asset_pairs_tokenized.json");
2966        let response: KrakenResponse<AssetPairsResponse> = serde_json::from_str(&json).unwrap();
2967        let pairs = response.result.unwrap();
2968        let (pair_name, definition) = pairs.iter().next().unwrap();
2969
2970        let same = parse_tokenized_instrument(pair_name, definition, TS, TS).unwrap();
2971        assert!(
2972            same.info()
2973                .is_none_or(|info| !info.contains_key(KRAKEN_PAIR_DECIMALS_KEY)),
2974            "a scale equal to the tick precision is not recorded"
2975        );
2976
2977        let mut coarser = definition.clone();
2978        coarser.pair_decimals = same.price_precision() - 1;
2979        let tokenized = parse_tokenized_instrument(pair_name, &coarser, TS, TS).unwrap();
2980        let spot = parse_spot_instrument(pair_name, &coarser, TS, TS).unwrap();
2981        for instrument in [tokenized, spot] {
2982            assert!(
2983                instrument
2984                    .info()
2985                    .is_none_or(|info| !info.contains_key(KRAKEN_PAIR_DECIMALS_KEY)),
2986                "a scale coarser than the tick precision is not recorded"
2987            );
2988        }
2989
2990        let mut finer = definition.clone();
2991        finer.pair_decimals = same.price_precision() + 1;
2992        let tokenized = parse_tokenized_instrument(pair_name, &finer, TS, TS).unwrap();
2993        let spot = parse_spot_instrument(pair_name, &finer, TS, TS).unwrap();
2994        for instrument in [tokenized, spot] {
2995            let recorded = instrument
2996                .info()
2997                .and_then(|info| info.get(KRAKEN_PAIR_DECIMALS_KEY))
2998                .and_then(serde_json::Value::as_u64);
2999            assert_eq!(recorded, Some(u64::from(finer.pair_decimals)));
3000        }
3001    }
3002
3003    #[rstest]
3004    fn test_parse_tokenized_instrument() {
3005        let json = load_test_json("http_asset_pairs_tokenized.json");
3006        let response: KrakenResponse<AssetPairsResponse> = serde_json::from_str(&json).unwrap();
3007        let pairs = response.result.unwrap();
3008
3009        let (pair_name, definition) = pairs.iter().next().unwrap();
3010
3011        let instrument = parse_tokenized_instrument(pair_name, definition, TS, TS).unwrap();
3012
3013        match instrument {
3014            InstrumentAny::TokenizedAsset(ta) => {
3015                assert_eq!(ta.id.symbol.as_str(), "AAPLx/USD");
3016                assert_eq!(ta.id.venue.as_str(), "KRAKEN");
3017                assert_eq!(ta.raw_symbol.as_str(), "AAPLxUSD");
3018                assert_eq!(ta.asset_class, AssetClass::Equity);
3019                assert_eq!(ta.base_currency.code, "AAPLx");
3020                assert_eq!(ta.quote_currency.code, "USD");
3021                assert_eq!(ta.price_precision, 2);
3022                assert_eq!(ta.size_precision, 8);
3023                assert_eq!(ta.price_increment.as_decimal(), dec!(0.01));
3024                assert_eq!(ta.size_increment.as_decimal(), dec!(0.00000001));
3025                assert!(ta.min_quantity.is_some());
3026            }
3027            _ => panic!("Expected TokenizedAsset, received {instrument:?}"),
3028        }
3029
3030        // A key spelled differently from the altname, at a wire scale finer than the tick: the
3031        // info carries the scale and nothing else.
3032        let mut finer = definition.clone();
3033        finer.pair_decimals = 3;
3034        let instrument = parse_tokenized_instrument("XAAPLxZUSD", &finer, TS, TS).unwrap();
3035        let info = instrument.info().expect("the wire scale is recorded");
3036        assert_eq!(
3037            info.get(KRAKEN_PAIR_DECIMALS_KEY)
3038                .and_then(serde_json::Value::as_u64),
3039            Some(3)
3040        );
3041        assert!(
3042            !info.contains_key(KRAKEN_ALTNAME_KEY),
3043            "a tokenized pair carries no altname alias"
3044        );
3045    }
3046
3047    #[rstest]
3048    fn test_parse_fill_report_tokenized_asset() {
3049        let json = load_test_json("http_trades_history.json");
3050        let wrapper: serde_json::Value = serde_json::from_str(&json).unwrap();
3051        let result = wrapper.get("result").unwrap();
3052        let trades_map = result.get("trades").unwrap();
3053        let trades: IndexMap<String, SpotTrade> =
3054            serde_json::from_value(trades_map.clone()).unwrap();
3055
3056        let account_id = AccountId::new("KRAKEN-001");
3057        let instrument_id = InstrumentId::new(Symbol::new("AAPLx/USD"), *KRAKEN_VENUE);
3058        let instrument = InstrumentAny::TokenizedAsset(
3059            TokenizedAsset::builder()
3060                .instrument_id(instrument_id)
3061                .raw_symbol(Symbol::new("AAPLxUSD"))
3062                .asset_class(AssetClass::Equity)
3063                .base_currency(Currency::get_or_create_crypto("AAPLx"))
3064                .quote_currency(Currency::USD())
3065                .price_precision(2)
3066                .size_precision(8)
3067                .price_increment(Price::from("0.01"))
3068                .size_increment(Quantity::from("0.00000001"))
3069                .ts_event(TS)
3070                .ts_init(TS)
3071                .build()
3072                .unwrap(),
3073        );
3074
3075        let (trade_id, trade) = trades.iter().next().unwrap();
3076
3077        let report = parse_fill_report(trade_id, trade, &instrument, account_id, TS).unwrap();
3078
3079        assert_eq!(report.account_id, account_id);
3080        assert_eq!(report.instrument_id, instrument_id);
3081        assert_eq!(report.trade_id.to_string(), *trade_id);
3082        assert_eq!(report.last_qty, Quantity::from("0.50000000"));
3083        assert_eq!(report.last_px, Price::from("29500.50"));
3084        assert_eq!(report.commission.currency, Currency::USD());
3085    }
3086
3087    #[rstest]
3088    fn test_truncate_cl_ord_id_19_chars_truncated() {
3089        let input = "O202602270023210040";
3090        assert_eq!(input.len(), 19);
3091        let id = ClientOrderId::new(input);
3092        let result = truncate_cl_ord_id(&id);
3093        assert_eq!(result.len(), 18);
3094        assert_eq!(result, "O02602270023210040");
3095    }
3096
3097    #[rstest]
3098    fn test_truncate_cl_ord_id_preserves_tail() {
3099        let input = "O20260227002321004001100";
3100        let id = ClientOrderId::new(input);
3101        let result = truncate_cl_ord_id(&id);
3102        assert_eq!(&result[1..], &input[input.len() - 17..]);
3103    }
3104}