Skip to main content

nautilus_coinbase/http/
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//! Parsing functions for converting Coinbase API responses to Nautilus domain types.
17
18use std::str::FromStr;
19
20use anyhow::Context;
21use jiff::Timestamp;
22use nautilus_core::{UUID4, UnixNanos};
23use nautilus_model::{
24    data::{Bar, BarType, BookOrder, OrderBookDelta, OrderBookDeltas, TradeTick},
25    enums::{
26        AccountType, AggressorSide, BookAction, LiquiditySide, OrderSide, OrderStatus, OrderType,
27        PositionSide, RecordFlag, TimeInForce, TriggerType,
28    },
29    events::AccountState,
30    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, TradeId, VenueOrderId},
31    instruments::{CryptoFuture, CryptoPerpetual, CurrencyPair, Instrument, InstrumentAny},
32    reports::{FillReport, OrderStatusReport, PositionStatusReport},
33    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
34};
35use rust_decimal::Decimal;
36
37use crate::{
38    common::{
39        consts::{
40            COINBASE_VENUE, ORDER_CONFIG_BASE_SIZE, ORDER_CONFIG_END_TIME,
41            ORDER_CONFIG_LIMIT_PRICE, ORDER_CONFIG_POST_ONLY, ORDER_CONFIG_STOP_PRICE,
42        },
43        enums::{
44            CoinbaseContractExpiryType, CoinbaseFcmPositionSide, CoinbaseLiquidityIndicator,
45            CoinbaseOrderSide, CoinbaseOrderStatus, CoinbaseOrderType, CoinbaseProductType,
46            CoinbaseTimeInForce,
47        },
48    },
49    http::models::{
50        Account, BookLevel, Candle, CfmBalanceSummary, CfmPosition, Fill, Order, PriceBook,
51        Product, Trade,
52    },
53    websocket::messages::WsFcmBalanceSummary,
54};
55
56/// Parses an RFC 3339 timestamp string to `UnixNanos`.
57pub fn parse_rfc3339_timestamp(timestamp: &str) -> anyhow::Result<UnixNanos> {
58    let dt = timestamp
59        .parse::<Timestamp>()
60        .context(format!("Failed to parse timestamp '{timestamp}'"))?;
61    let nanos = u64::try_from(dt.as_nanosecond())
62        .context(format!("Timestamp out of range: '{timestamp}'"))?;
63    Ok(UnixNanos::from(nanos))
64}
65
66/// Parses a Unix epoch seconds string to `UnixNanos`.
67pub fn parse_epoch_secs_timestamp(epoch_secs: &str) -> anyhow::Result<UnixNanos> {
68    let secs: u64 = epoch_secs
69        .parse()
70        .context(format!("Failed to parse epoch seconds '{epoch_secs}'"))?;
71    Ok(UnixNanos::from(secs * 1_000_000_000))
72}
73
74/// Parses a price string with the given precision.
75pub fn parse_price(value: &str, precision: u8) -> anyhow::Result<Price> {
76    let decimal = Decimal::from_str(value).context(format!("Failed to parse price '{value}'"))?;
77    Price::from_decimal_dp(decimal, precision).context(format!(
78        "Failed to create Price from '{value}' with precision {precision}"
79    ))
80}
81
82/// Parses a quantity string with the given precision.
83pub fn parse_quantity(value: &str, precision: u8) -> anyhow::Result<Quantity> {
84    let decimal =
85        Decimal::from_str(value).context(format!("Failed to parse quantity '{value}'"))?;
86    Quantity::from_decimal_dp(decimal, precision).context(format!(
87        "Failed to create Quantity from '{value}' with precision {precision}"
88    ))
89}
90
91/// Derives precision (number of decimal places) from an increment string.
92///
93/// For example, `"0.01"` returns 2, `"0.00000001"` returns 8, `"1"` returns 0.
94pub fn precision_from_increment(increment: &str) -> u8 {
95    match increment.find('.') {
96        Some(pos) => {
97            let decimals = &increment[pos + 1..];
98            let trimmed_len = decimals.trim_end_matches('0').len();
99            let min = usize::from(!decimals.chars().all(|c| c == '0'));
100            trimmed_len.max(min) as u8
101        }
102        None => 0,
103    }
104}
105
106/// Converts a Coinbase market trade side to a Nautilus aggressor side.
107///
108/// Coinbase reports the maker side on public market trades, so the aggressor is the
109/// opposite side.
110pub fn coinbase_side_to_aggressor(side: &CoinbaseOrderSide) -> AggressorSide {
111    match side {
112        CoinbaseOrderSide::Buy => AggressorSide::Sell,
113        CoinbaseOrderSide::Sell => AggressorSide::Buy,
114        CoinbaseOrderSide::Unknown => AggressorSide::NoAggressor,
115    }
116}
117
118/// Parses an optional quantity from a string, returning `None` for empty,
119/// zero, or values that exceed Nautilus's `QUANTITY_RAW_MAX`.
120fn parse_optional_quantity(value: &str) -> Option<Quantity> {
121    if value.is_empty() || value == "0" {
122        None
123    } else {
124        Quantity::from_str(value).ok()
125    }
126}
127
128/// Derives the base currency from the product, falling back to the first word
129/// in `display_name` when `base_currency_id` is empty (Coinbase futures).
130fn derive_base_currency(product: &Product) -> Currency {
131    if product.base_currency_id.is_empty() {
132        let base_str = product
133            .display_name
134            .split_whitespace()
135            .next()
136            .unwrap_or("UNKNOWN");
137        Currency::get_or_create_crypto(base_str)
138    } else {
139        Currency::get_or_create_crypto(product.base_currency_id)
140    }
141}
142
143/// Extracts the contract size as a multiplier from future product details.
144fn contract_size_multiplier(product: &Product) -> Option<Quantity> {
145    product.future_product_details.as_ref().and_then(|d| {
146        if d.contract_size.is_empty() || d.contract_size == "0" {
147            None
148        } else {
149            Some(Quantity::from(d.contract_size.as_str()))
150        }
151    })
152}
153
154/// Parses a Coinbase spot product into a `CurrencyPair`.
155///
156/// # Panics
157///
158/// Panics if the constructed instrument fails validation.
159pub fn parse_spot_instrument(
160    product: &Product,
161    ts_init: UnixNanos,
162) -> anyhow::Result<InstrumentAny> {
163    let instrument_id = InstrumentId::new(Symbol::new(product.product_id), *COINBASE_VENUE);
164    let raw_symbol = Symbol::new(product.product_id);
165
166    let base_currency = Currency::get_or_create_crypto(product.base_currency_id);
167    let quote_currency = Currency::get_or_create_crypto(product.quote_currency_id);
168
169    let price_precision = precision_from_increment(&product.price_increment);
170    let size_precision = precision_from_increment(&product.base_increment);
171
172    let price_increment = parse_price(&product.price_increment, price_precision)?;
173    let size_increment = parse_quantity(&product.base_increment, size_precision)?;
174
175    let min_quantity = parse_optional_quantity(&product.base_min_size);
176    let max_quantity = parse_optional_quantity(&product.base_max_size);
177
178    let instrument = CurrencyPair::builder()
179        .instrument_id(instrument_id)
180        .raw_symbol(raw_symbol)
181        .base_currency(base_currency)
182        .quote_currency(quote_currency)
183        .price_precision(price_precision)
184        .size_precision(size_precision)
185        .price_increment(price_increment)
186        .size_increment(size_increment)
187        .maybe_max_quantity(max_quantity)
188        .maybe_min_quantity(min_quantity)
189        // maker_fee (loaded separately via transaction_summary)
190        .ts_event(ts_init)
191        .ts_init(ts_init)
192        .build()
193        .unwrap();
194
195    Ok(InstrumentAny::CurrencyPair(instrument))
196}
197
198/// Parses a Coinbase perpetual futures product into a `CryptoPerpetual`.
199///
200/// # Panics
201///
202/// Panics if the constructed instrument fails validation.
203pub fn parse_perpetual_instrument(
204    product: &Product,
205    ts_init: UnixNanos,
206) -> anyhow::Result<InstrumentAny> {
207    let instrument_id = InstrumentId::new(Symbol::new(product.product_id), *COINBASE_VENUE);
208    let raw_symbol = Symbol::new(product.product_id);
209
210    let base_currency = derive_base_currency(product);
211    let quote_currency = Currency::get_or_create_crypto(product.quote_currency_id);
212    let settlement_currency = quote_currency;
213
214    let price_precision = precision_from_increment(&product.price_increment);
215    let size_precision = precision_from_increment(&product.base_increment);
216
217    let price_increment = parse_price(&product.price_increment, price_precision)?;
218    let size_increment = parse_quantity(&product.base_increment, size_precision)?;
219
220    let min_quantity = parse_optional_quantity(&product.base_min_size);
221    let max_quantity = parse_optional_quantity(&product.base_max_size);
222
223    let multiplier = contract_size_multiplier(product);
224
225    let instrument = CryptoPerpetual::builder()
226        .instrument_id(instrument_id)
227        .raw_symbol(raw_symbol)
228        .base_currency(base_currency)
229        .quote_currency(quote_currency)
230        .settlement_currency(settlement_currency)
231        .is_inverse(false)
232        .price_precision(price_precision)
233        .size_precision(size_precision)
234        .price_increment(price_increment)
235        .size_increment(size_increment)
236        .maybe_multiplier(multiplier)
237        .maybe_max_quantity(max_quantity)
238        .maybe_min_quantity(min_quantity)
239        .ts_event(ts_init)
240        .ts_init(ts_init)
241        .build()
242        .unwrap();
243
244    Ok(InstrumentAny::CryptoPerpetual(instrument))
245}
246
247/// Parses a Coinbase dated future into a `CryptoFuture`.
248///
249/// # Panics
250///
251/// Panics if the constructed instrument fails validation.
252pub fn parse_future_instrument(
253    product: &Product,
254    ts_init: UnixNanos,
255) -> anyhow::Result<InstrumentAny> {
256    let instrument_id = InstrumentId::new(Symbol::new(product.product_id), *COINBASE_VENUE);
257    let raw_symbol = Symbol::new(product.product_id);
258
259    let underlying = derive_base_currency(product);
260    let quote_currency = Currency::get_or_create_crypto(product.quote_currency_id);
261    let settlement_currency = quote_currency;
262
263    let price_precision = precision_from_increment(&product.price_increment);
264    let size_precision = precision_from_increment(&product.base_increment);
265
266    let price_increment = parse_price(&product.price_increment, price_precision)?;
267    let size_increment = parse_quantity(&product.base_increment, size_precision)?;
268
269    let min_quantity = parse_optional_quantity(&product.base_min_size);
270    let max_quantity = parse_optional_quantity(&product.base_max_size);
271
272    let expiry_str = product
273        .future_product_details
274        .as_ref()
275        .map_or("", |d| d.contract_expiry.as_str());
276
277    anyhow::ensure!(
278        !expiry_str.is_empty(),
279        "Missing contract_expiry for dated future '{}'",
280        product.product_id
281    );
282
283    let expiration_ns = parse_rfc3339_timestamp(expiry_str).context(format!(
284        "Failed to parse contract_expiry for '{}'",
285        product.product_id
286    ))?;
287
288    let multiplier = contract_size_multiplier(product);
289
290    let instrument = CryptoFuture::builder()
291        .instrument_id(instrument_id)
292        .raw_symbol(raw_symbol)
293        .underlying(underlying)
294        .quote_currency(quote_currency)
295        .settlement_currency(settlement_currency)
296        .is_inverse(false)
297        .activation_ns(ts_init)
298        .expiration_ns(expiration_ns)
299        .price_precision(price_precision)
300        .size_precision(size_precision)
301        .price_increment(price_increment)
302        .size_increment(size_increment)
303        .maybe_multiplier(multiplier)
304        .maybe_max_quantity(max_quantity)
305        .maybe_min_quantity(min_quantity)
306        .ts_event(ts_init)
307        .ts_init(ts_init)
308        .build()
309        .unwrap();
310
311    Ok(InstrumentAny::CryptoFuture(instrument))
312}
313
314/// Parses a Coinbase product into the appropriate Nautilus instrument type.
315pub fn parse_instrument(product: &Product, ts_init: UnixNanos) -> anyhow::Result<InstrumentAny> {
316    match product.product_type {
317        CoinbaseProductType::Spot => parse_spot_instrument(product, ts_init),
318        CoinbaseProductType::Future => {
319            if is_perpetual_product(product) {
320                parse_perpetual_instrument(product, ts_init)
321            } else {
322                parse_future_instrument(product, ts_init)
323            }
324        }
325        CoinbaseProductType::Unknown => {
326            anyhow::bail!("Unknown product type for '{}'", product.product_id)
327        }
328    }
329}
330
331/// Determines whether a futures product is a perpetual contract.
332///
333/// Coinbase returns `contract_expiry_type: "EXPIRING"` for both perpetuals
334/// and dated futures, so the `CoinbaseContractExpiryType::Perpetual` variant
335/// alone is not sufficient. We check three signals in order:
336///
337/// 1. `contract_expiry_type == Perpetual` (forward compat if Coinbase fixes the API)
338/// 2. Non-empty `funding_rate` in `future_product_details` (structural signal:
339///    only perpetuals have ongoing funding)
340/// 3. `display_name` contains "PERP" or "Perpetual" (heuristic fallback)
341pub(crate) fn is_perpetual_product(product: &Product) -> bool {
342    if let Some(details) = &product.future_product_details {
343        if details.contract_expiry_type == CoinbaseContractExpiryType::Perpetual {
344            return true;
345        }
346
347        if !details.funding_rate.is_empty() {
348            return true;
349        }
350    }
351    product.display_name.contains("PERP") || product.display_name.contains("Perpetual")
352}
353
354/// Parses a Coinbase trade into a `TradeTick`.
355pub fn parse_trade_tick(
356    trade: &Trade,
357    instrument_id: InstrumentId,
358    price_precision: u8,
359    size_precision: u8,
360    ts_init: UnixNanos,
361) -> anyhow::Result<TradeTick> {
362    let price = parse_price(&trade.price, price_precision)?;
363    let size = parse_quantity(&trade.size, size_precision)?;
364    let aggressor_side = coinbase_side_to_aggressor(&trade.side);
365    let trade_id = TradeId::new(&trade.trade_id);
366    let ts_event = parse_rfc3339_timestamp(&trade.time)?;
367
368    TradeTick::new_checked(
369        instrument_id,
370        price,
371        size,
372        aggressor_side,
373        trade_id,
374        ts_event,
375        ts_init,
376    )
377}
378
379/// Parses a Coinbase candle into a `Bar`.
380pub fn parse_bar(
381    candle: &Candle,
382    bar_type: BarType,
383    price_precision: u8,
384    size_precision: u8,
385    ts_init: UnixNanos,
386) -> anyhow::Result<Bar> {
387    let open = parse_price(&candle.open, price_precision)?;
388    let high = parse_price(&candle.high, price_precision)?;
389    let low = parse_price(&candle.low, price_precision)?;
390    let close = parse_price(&candle.close, price_precision)?;
391    let volume = parse_quantity(&candle.volume, size_precision)?;
392
393    // Coinbase candle "start" is epoch seconds for the candle open time
394    let ts_event = parse_epoch_secs_timestamp(&candle.start)?;
395
396    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
397}
398
399/// Parses a Coinbase order book snapshot into `OrderBookDeltas`.
400pub fn parse_product_book_snapshot(
401    book: &PriceBook,
402    instrument_id: InstrumentId,
403    price_precision: u8,
404    size_precision: u8,
405    ts_init: UnixNanos,
406) -> anyhow::Result<OrderBookDeltas> {
407    let ts_event = parse_rfc3339_timestamp(&book.time)?;
408    let total_levels = book.bids.len() + book.asks.len();
409    let mut deltas = Vec::with_capacity(total_levels + 1);
410
411    let mut clear = OrderBookDelta::clear(instrument_id, 0, ts_event, ts_init);
412    clear.flags |= RecordFlag::F_SNAPSHOT as u8;
413
414    if total_levels == 0 {
415        clear.flags |= RecordFlag::F_LAST as u8;
416    }
417    deltas.push(clear);
418
419    let mut processed = 0usize;
420
421    for level in &book.bids {
422        processed += 1;
423        let delta = parse_book_delta(
424            level,
425            OrderSide::Buy,
426            instrument_id,
427            price_precision,
428            size_precision,
429            processed == total_levels,
430            ts_event,
431            ts_init,
432        )?;
433        deltas.push(delta);
434    }
435
436    for level in &book.asks {
437        processed += 1;
438        let delta = parse_book_delta(
439            level,
440            OrderSide::Sell,
441            instrument_id,
442            price_precision,
443            size_precision,
444            processed == total_levels,
445            ts_event,
446            ts_init,
447        )?;
448        deltas.push(delta);
449    }
450
451    OrderBookDeltas::new_checked(instrument_id, deltas)
452}
453
454#[expect(clippy::too_many_arguments)]
455fn parse_book_delta(
456    level: &BookLevel,
457    side: OrderSide,
458    instrument_id: InstrumentId,
459    price_precision: u8,
460    size_precision: u8,
461    is_last: bool,
462    ts_event: UnixNanos,
463    ts_init: UnixNanos,
464) -> anyhow::Result<OrderBookDelta> {
465    let price = parse_price(&level.price, price_precision)?;
466    let size = parse_quantity(&level.size, size_precision)?;
467
468    let mut flags = RecordFlag::F_MBP as u8 | RecordFlag::F_SNAPSHOT as u8;
469
470    if is_last {
471        flags |= RecordFlag::F_LAST as u8;
472    }
473
474    let order = BookOrder::new(side, price, size, 0);
475    OrderBookDelta::new_checked(
476        instrument_id,
477        BookAction::Add,
478        order,
479        flags,
480        0,
481        ts_event,
482        ts_init,
483    )
484}
485
486/// Converts a Coinbase order side to the Nautilus [`Option<OrderSide>`].
487pub fn parse_order_side_optional(side: &CoinbaseOrderSide) -> Option<OrderSide> {
488    match side {
489        CoinbaseOrderSide::Buy => Some(OrderSide::Buy),
490        CoinbaseOrderSide::Sell => Some(OrderSide::Sell),
491        CoinbaseOrderSide::Unknown => None,
492    }
493}
494
495/// Converts a Coinbase order side to a Nautilus [`OrderSide`].
496///
497/// # Errors
498///
499/// Returns an error if Coinbase supplies an unknown side.
500pub fn parse_order_side(side: &CoinbaseOrderSide) -> anyhow::Result<OrderSide> {
501    match side {
502        CoinbaseOrderSide::Buy => Ok(OrderSide::Buy),
503        CoinbaseOrderSide::Sell => Ok(OrderSide::Sell),
504        CoinbaseOrderSide::Unknown => anyhow::bail!("Coinbase fill has unknown order side"),
505    }
506}
507
508/// Converts a Coinbase order status to the Nautilus [`OrderStatus`].
509///
510/// `Pending` and `Queued` are transient pre-`Open` states the venue passes
511/// through after acknowledging the order. They are mapped to `Accepted`
512/// (rather than `Submitted`) so user-channel updates that race the REST
513/// `OrderAccepted` event do not appear as a backwards transition to the
514/// reconciler. `Open` also maps to `Accepted` because Nautilus differentiates
515/// the initial accept event from later partial-fill states; callers should
516/// promote the status to `PartiallyFilled` / `Filled` based on `filled_qty`.
517pub fn parse_order_status(status: CoinbaseOrderStatus) -> OrderStatus {
518    match status {
519        CoinbaseOrderStatus::Pending | CoinbaseOrderStatus::Queued | CoinbaseOrderStatus::Open => {
520            OrderStatus::Accepted
521        }
522        CoinbaseOrderStatus::Filled => OrderStatus::Filled,
523        CoinbaseOrderStatus::Cancelled => OrderStatus::Canceled,
524        CoinbaseOrderStatus::CancelQueued => OrderStatus::PendingCancel,
525        CoinbaseOrderStatus::EditQueued => OrderStatus::PendingUpdate,
526        CoinbaseOrderStatus::Expired => OrderStatus::Expired,
527        CoinbaseOrderStatus::Failed => OrderStatus::Rejected,
528        CoinbaseOrderStatus::Unknown => OrderStatus::Rejected,
529    }
530}
531
532/// Converts a Coinbase time-in-force to the Nautilus [`TimeInForce`].
533pub fn parse_time_in_force(tif: Option<CoinbaseTimeInForce>) -> TimeInForce {
534    match tif {
535        Some(CoinbaseTimeInForce::GoodUntilCancelled) => TimeInForce::Gtc,
536        Some(CoinbaseTimeInForce::GoodUntilDateTime) => TimeInForce::Gtd,
537        Some(CoinbaseTimeInForce::ImmediateOrCancel) => TimeInForce::Ioc,
538        Some(CoinbaseTimeInForce::FillOrKill) => TimeInForce::Fok,
539        Some(CoinbaseTimeInForce::Unknown) | None => TimeInForce::Gtc,
540    }
541}
542
543/// Converts a Coinbase liquidity indicator to the Nautilus [`LiquiditySide`].
544pub fn parse_liquidity_side(indicator: &CoinbaseLiquidityIndicator) -> LiquiditySide {
545    match indicator {
546        CoinbaseLiquidityIndicator::Maker => LiquiditySide::Maker,
547        CoinbaseLiquidityIndicator::Taker => LiquiditySide::Taker,
548        CoinbaseLiquidityIndicator::Unknown => LiquiditySide::NoLiquiditySide,
549    }
550}
551
552/// Converts a Coinbase order type to the Nautilus [`OrderType`].
553///
554/// Coinbase uses `BRACKET` on history endpoints for multi-leg orders. Nautilus
555/// has no bracket order type, so the parser falls back to [`OrderType::Limit`].
556pub fn parse_order_type(order_type: CoinbaseOrderType) -> OrderType {
557    match order_type {
558        CoinbaseOrderType::Market => OrderType::Market,
559        CoinbaseOrderType::Limit => OrderType::Limit,
560        CoinbaseOrderType::Stop => OrderType::StopMarket,
561        CoinbaseOrderType::StopLimit => OrderType::StopLimit,
562        CoinbaseOrderType::Liquidation => OrderType::Market,
563        CoinbaseOrderType::Bracket
564        | CoinbaseOrderType::Twap
565        | CoinbaseOrderType::RollOpen
566        | CoinbaseOrderType::RollClose
567        | CoinbaseOrderType::Scaled
568        | CoinbaseOrderType::Unknown => OrderType::Limit,
569    }
570}
571
572/// Parses a Coinbase [`Order`] into an [`OrderStatusReport`].
573///
574/// Uses the given instrument's price and size precision to build quantities
575/// and prices, and derives the limit price from the order configuration when
576/// present. Timestamps default to `ts_init` when Coinbase omits them.
577///
578/// # Errors
579///
580/// Returns an error if any numeric field cannot be parsed against the instrument precision.
581pub fn parse_order_status_report(
582    order: &Order,
583    instrument: &InstrumentAny,
584    account_id: AccountId,
585    ts_init: UnixNanos,
586) -> anyhow::Result<OrderStatusReport> {
587    let instrument_id = instrument.id();
588    let price_precision = instrument.price_precision();
589    let size_precision = instrument.size_precision();
590
591    let order_side = parse_order_side_optional(&order.side);
592    let order_type = parse_order_type(order.order_type);
593    let time_in_force = parse_time_in_force(order.time_in_force);
594    let mut order_status = parse_order_status(order.status);
595
596    let venue_order_id = VenueOrderId::new(&order.order_id);
597    let client_order_id = if order.client_order_id.is_empty() {
598        None
599    } else {
600        Some(ClientOrderId::new(&order.client_order_id))
601    };
602
603    let filled_qty = if order.filled_size.is_empty() {
604        Quantity::zero(size_precision)
605    } else {
606        parse_quantity(&order.filled_size, size_precision).context("failed to parse filled_size")?
607    };
608
609    // API has no separate ADL flag, so liquidation and ADL share this branch
610    if order.order_type == CoinbaseOrderType::Liquidation || order.is_liquidation {
611        let order_side = order_side.as_ref().map_or("NO_ORDER_SIDE", AsRef::as_ref);
612        log::warn!(
613            "Forced-close (liquidation/ADL) order: {instrument_id} venue_order_id={venue_order_id} side={order_side} filled={filled_qty}",
614        );
615    }
616
617    // Derive the ordered quantity from the order_configuration. For quote-sized
618    // market orders the base quantity is not reported pre-fill; fall back to
619    // filled_qty when the order is terminal.
620    let quantity = base_quantity_from_configuration(order, size_precision).unwrap_or(filled_qty);
621
622    // Promote Accepted to PartiallyFilled when some fill has landed but the
623    // order is still open, matching Nautilus' lifecycle.
624    if order_status == OrderStatus::Accepted && filled_qty.is_positive() && filled_qty < quantity {
625        order_status = OrderStatus::PartiallyFilled;
626    }
627
628    let ts_accepted = if order.created_time.is_empty() {
629        ts_init
630    } else {
631        parse_rfc3339_timestamp(&order.created_time).unwrap_or(ts_init)
632    };
633    let ts_last = order
634        .last_fill_time
635        .as_deref()
636        .filter(|s| !s.is_empty())
637        .and_then(|s| parse_rfc3339_timestamp(s).ok())
638        .unwrap_or(ts_accepted);
639
640    let mut report = OrderStatusReport::new(
641        account_id,
642        instrument_id,
643        client_order_id,
644        venue_order_id,
645        order_side,
646        order_type,
647        time_in_force,
648        order_status,
649        quantity,
650        filled_qty,
651        ts_accepted,
652        ts_last,
653        ts_init,
654        None,
655    );
656
657    if let Some(price) = limit_price_from_configuration(order, price_precision) {
658        report = report.with_price(price);
659    }
660
661    if let Some(trigger_price) = stop_price_from_configuration(order, price_precision) {
662        report = report
663            .with_trigger_price(trigger_price)
664            .with_trigger_type(TriggerType::LastPrice);
665    }
666
667    if !order.average_filled_price.is_empty()
668        && let Ok(avg_decimal) = Decimal::from_str(&order.average_filled_price)
669        && avg_decimal.is_sign_positive()
670        && !avg_decimal.is_zero()
671    {
672        report = report.with_avg_px(avg_decimal);
673    }
674
675    if post_only_from_configuration(order) {
676        report = report.with_post_only(true);
677    }
678
679    if let Some(expire_time) = end_time_from_configuration(order) {
680        report = report.with_expire_time(expire_time);
681    }
682
683    Ok(report)
684}
685
686/// Parses a Coinbase [`Fill`] into a [`FillReport`].
687///
688/// Commission currency defaults to the instrument's quote currency, as reported for spot products.
689/// Quote-sized fills are converted to base quantity using the fill price. Commissions are positive
690/// when paid.
691///
692/// # Errors
693///
694/// Returns an error if the order side or trade time is invalid, if the price, size, or commission
695/// cannot be parsed or converted, or if a quote-sized fill has a non-positive price.
696pub fn parse_fill_report(
697    fill: &Fill,
698    instrument: &InstrumentAny,
699    account_id: AccountId,
700    ts_init: UnixNanos,
701) -> anyhow::Result<FillReport> {
702    let instrument_id = instrument.id();
703    let price_precision = instrument.price_precision();
704    let size_precision = instrument.size_precision();
705
706    let venue_order_id = VenueOrderId::new(&fill.order_id);
707    let trade_id = TradeId::new(&fill.trade_id);
708    let order_side = parse_order_side(&fill.side)?;
709    let last_px = parse_price(&fill.price, price_precision)?;
710    let last_qty = if fill.size_in_quote {
711        let size = Decimal::from_str(&fill.size).context("failed to parse quote fill size")?;
712        let price = Decimal::from_str(&fill.price).context("failed to parse quote fill price")?;
713        anyhow::ensure!(price > Decimal::ZERO, "quote fill price must be positive");
714        let quantity = size
715            .checked_div(price)
716            .context("failed to convert quote fill size to base quantity")?;
717        Quantity::from_decimal_dp(quantity, size_precision)?
718    } else {
719        parse_quantity(&fill.size, size_precision)?
720    };
721
722    let commission_currency = instrument.quote_currency();
723    let commission = Money::from_decimal(fill.commission, commission_currency)
724        .context("failed to build commission Money")?;
725
726    let liquidity_side = parse_liquidity_side(&fill.liquidity_indicator);
727    let ts_event = parse_rfc3339_timestamp(&fill.trade_time)?;
728
729    Ok(FillReport::new(
730        account_id,
731        instrument_id,
732        venue_order_id,
733        trade_id,
734        order_side,
735        last_qty,
736        last_px,
737        commission,
738        liquidity_side,
739        None, // client_order_id not carried on Coinbase fill records
740        None, // venue_position_id not provided
741        ts_event,
742        ts_init,
743        None,
744    ))
745}
746
747/// Parses a list of Coinbase [`Account`] entries into a Nautilus [`AccountState`].
748///
749/// Builds one [`AccountBalance`] per currency where
750/// `total = available_balance + hold`, `free = available_balance`, and
751/// `locked = hold`. Accounts with invalid balances are skipped with a debug
752/// log. Always emits at least one balance so the resulting
753/// [`AccountState`] is valid.
754///
755/// # Errors
756///
757/// Returns an error if building a balance fails after all accounts have been exhausted (i.e. every
758/// entry was malformed).
759pub fn parse_account_state(
760    accounts: &[Account],
761    account_id: AccountId,
762    is_reported: bool,
763    ts_event: UnixNanos,
764    ts_init: UnixNanos,
765) -> anyhow::Result<AccountState> {
766    // Coinbase returns one row per wallet, so the same currency may appear
767    // multiple times (per retail portfolio or sub-account). Aggregate by
768    // currency before emitting balances: Nautilus stores balances keyed by
769    // `Currency`, so emitting duplicates would drop funds via last-write-wins.
770    let mut aggregated: ahash::AHashMap<Currency, (Money, Money)> = ahash::AHashMap::new();
771
772    for account in accounts {
773        let currency_code = account.currency.trim();
774        if currency_code.is_empty() {
775            log::debug!(
776                "Skipping account with empty currency code: uuid={}",
777                account.uuid
778            );
779            continue;
780        }
781
782        let currency =
783            Currency::get_or_create_crypto_with_context(currency_code, Some("coinbase account"));
784
785        let Some(free) = parse_money_field(
786            account.available_balance.value,
787            "available_balance",
788            currency,
789        ) else {
790            continue;
791        };
792
793        let locked = match account.hold.as_ref() {
794            Some(hold) => {
795                parse_money_field(hold.value, "hold", currency).unwrap_or(Money::zero(currency))
796            }
797            None => Money::zero(currency),
798        };
799
800        aggregated
801            .entry(currency)
802            .and_modify(|(acc_free, acc_locked)| {
803                *acc_free = *acc_free + free;
804                *acc_locked = *acc_locked + locked;
805            })
806            .or_insert((free, locked));
807    }
808
809    let mut balances: Vec<AccountBalance> = aggregated
810        .into_iter()
811        .map(|(currency, (free, locked))| {
812            let total = free + locked;
813            AccountBalance::from_total_and_locked(total.as_decimal(), locked.as_decimal(), currency)
814                .map_err(anyhow::Error::from)
815        })
816        .collect::<anyhow::Result<Vec<_>>>()?;
817
818    if balances.is_empty() {
819        let fallback_currency = Currency::USD();
820        let zero = Money::zero(fallback_currency);
821        balances.push(AccountBalance::new(zero, zero, zero));
822    }
823
824    Ok(AccountState::new(
825        account_id,
826        AccountType::Cash,
827        balances,
828        Vec::new(),
829        is_reported,
830        UUID4::new(),
831        ts_event,
832        ts_init,
833        None,
834    ))
835}
836
837fn parse_money_field(value: Decimal, field: &str, currency: Currency) -> Option<Money> {
838    match Money::from_decimal(value, currency) {
839        Ok(money) => Some(money),
840        Err(e) => {
841            log::debug!(
842                "Skipping {field}='{value}' for currency {}: {e}",
843                currency.code
844            );
845            None
846        }
847    }
848}
849
850// Coinbase reports the CFM buffer as a percentage of `liquidation_threshold`
851// (e.g. "100" = 1x cushion). Warn at <20% so operators can react before the
852// liquidation engine (or, on perps, the deleveraging waterfall) fires.
853const CFM_LIQUIDATION_BUFFER_WARN_PCT: Decimal = Decimal::from_parts(20, 0, 0, false, 0);
854
855fn liquidation_buffer_in_warn_band(buffer_percentage: Decimal) -> bool {
856    buffer_percentage < CFM_LIQUIDATION_BUFFER_WARN_PCT
857}
858
859fn warn_if_liquidation_buffer_low(account_id: AccountId, buffer_percentage: Decimal) {
860    if liquidation_buffer_in_warn_band(buffer_percentage) {
861        log::warn!(
862            "Elevated CFM liquidation risk: {account_id} liquidation_buffer_percentage={buffer_percentage}% (warn threshold {CFM_LIQUIDATION_BUFFER_WARN_PCT}%)",
863        );
864    }
865}
866
867/// Parses a CFM balance summary into a single consolidated [`MarginBalance`].
868///
869/// Coinbase reports two windows (intraday and overnight) with identical
870/// currency, but `MarginAccount::split_event_margins` keys account-level
871/// margins by currency only, so emitting both would have one overwrite the
872/// other. Selecting per-field maxima could synthesize a pair that matches
873/// neither window, so we pick the whole window with the larger
874/// `initial_margin` (ties broken by `maintenance_margin`) and emit its pair
875/// verbatim; the stricter capital requirement governs risk.
876///
877/// # Errors
878///
879/// Returns an error if any balance cannot be built as [`Money`].
880pub fn parse_cfm_margin_balances(
881    summary: &CfmBalanceSummary,
882) -> anyhow::Result<Vec<MarginBalance>> {
883    let Some(window) = [
884        summary.intraday_margin_window_measure.as_ref(),
885        summary.overnight_margin_window_measure.as_ref(),
886    ]
887    .into_iter()
888    .flatten()
889    .max_by(|a, b| {
890        a.initial_margin
891            .value
892            .cmp(&b.initial_margin.value)
893            .then(a.maintenance_margin.value.cmp(&b.maintenance_margin.value))
894    }) else {
895        return Ok(Vec::new());
896    };
897
898    let currency = Currency::get_or_create_crypto(window.initial_margin.currency.as_str());
899    let initial = Money::from_decimal(window.initial_margin.value, currency)
900        .context("failed to build initial margin")?;
901    let maintenance = Money::from_decimal(window.maintenance_margin.value, currency)
902        .context("failed to build maintenance margin")?;
903
904    Ok(vec![MarginBalance::new(initial, maintenance, None)])
905}
906
907/// Builds a margin [`AccountState`] from the CFM balance summary and the
908/// current CBI / CFM USD balances.
909///
910/// # Errors
911///
912/// Returns an error if balances cannot be built from the summary values.
913pub fn parse_cfm_account_state(
914    summary: &CfmBalanceSummary,
915    account_id: AccountId,
916    is_reported: bool,
917    ts_event: UnixNanos,
918    ts_init: UnixNanos,
919) -> anyhow::Result<AccountState> {
920    if let Ok(buffer_pct) = Decimal::from_str(&summary.liquidation_buffer_percentage) {
921        warn_if_liquidation_buffer_low(account_id, buffer_pct);
922    }
923
924    let usd_currency = Currency::get_or_create_crypto(summary.total_usd_balance.currency.as_str());
925
926    // `total_usd_balance` is the venue's equity figure and includes collateral
927    // already consumed by open positions; using it as total (with
928    // `available_margin` as free) preserves equity so `Portfolio::equity`
929    // matches the venue. `from_total_and_free` derives locked as total - free
930    // so the `total == free + locked` invariant holds by construction.
931    let balance = AccountBalance::from_total_and_free(
932        summary.total_usd_balance.value,
933        summary.available_margin.value,
934        usd_currency,
935    )
936    .context("failed to build CFM account balance")?;
937
938    let margins = parse_cfm_margin_balances(summary)?;
939
940    Ok(AccountState::new(
941        account_id,
942        AccountType::Margin,
943        vec![balance],
944        margins,
945        is_reported,
946        UUID4::new(),
947        ts_event,
948        ts_init,
949        None,
950    ))
951}
952
953/// Builds a margin [`AccountState`] from a WebSocket-delivered FCM balance
954/// summary.
955///
956/// The WebSocket payload does not carry explicit currency codes, so the
957/// balance is reported in USD (the only CFM settlement currency).
958///
959/// # Errors
960///
961/// Returns an error if any component balance cannot be constructed.
962pub fn parse_ws_cfm_account_state(
963    summary: &WsFcmBalanceSummary,
964    account_id: AccountId,
965    ts_event: UnixNanos,
966    ts_init: UnixNanos,
967) -> anyhow::Result<AccountState> {
968    warn_if_liquidation_buffer_low(account_id, summary.liquidation_buffer_percentage);
969
970    let usd = Currency::USD();
971
972    // See `parse_cfm_account_state`: `total_usd_balance` is the venue's
973    // equity and must be kept so cached balance and `Portfolio::equity` align
974    // with the venue.
975    let balance = AccountBalance::from_total_and_free(
976        summary.total_usd_balance,
977        summary.available_margin,
978        usd,
979    )
980    .context("failed to build WS CFM account balance")?;
981
982    // Pick the window with the larger `initial_margin` (ties by maintenance)
983    // and emit its pair verbatim so the emitted MarginBalance matches a real
984    // venue window. See `parse_cfm_margin_balances` for why.
985    let window = if summary
986        .intraday_margin_window_measure
987        .initial_margin
988        .cmp(&summary.overnight_margin_window_measure.initial_margin)
989        .then(
990            summary
991                .intraday_margin_window_measure
992                .maintenance_margin
993                .cmp(&summary.overnight_margin_window_measure.maintenance_margin),
994        )
995        .is_ge()
996    {
997        &summary.intraday_margin_window_measure
998    } else {
999        &summary.overnight_margin_window_measure
1000    };
1001
1002    let initial = Money::from_decimal(window.initial_margin, usd)
1003        .context("failed to build initial margin")?;
1004    let maintenance = Money::from_decimal(window.maintenance_margin, usd)
1005        .context("failed to build maintenance margin")?;
1006
1007    Ok(AccountState::new(
1008        account_id,
1009        AccountType::Margin,
1010        vec![balance],
1011        vec![MarginBalance::new(initial, maintenance, None)],
1012        true,
1013        UUID4::new(),
1014        ts_event,
1015        ts_init,
1016        None,
1017    ))
1018}
1019
1020/// Parses a single CFM position into a Nautilus [`PositionStatusReport`].
1021///
1022/// The position's quantity is scaled by `contract_size` (expressed in the
1023/// instrument's size precision). Callers are expected to supply the
1024/// matching instrument so precision lines up with the venue's reported
1025/// number of contracts.
1026///
1027/// # Errors
1028///
1029/// Returns an error if the quantity or average entry price cannot be represented with the
1030/// instrument's precision.
1031pub fn parse_cfm_position_status_report(
1032    position: &CfmPosition,
1033    instrument: &InstrumentAny,
1034    account_id: AccountId,
1035    ts_init: UnixNanos,
1036) -> anyhow::Result<PositionStatusReport> {
1037    let instrument_id = instrument.id();
1038    let size_precision = instrument.size_precision();
1039
1040    let position_side = match position.side {
1041        CoinbaseFcmPositionSide::Long => PositionSide::Long,
1042        CoinbaseFcmPositionSide::Short => PositionSide::Short,
1043        CoinbaseFcmPositionSide::Unspecified => PositionSide::Flat,
1044    };
1045
1046    let quantity = Quantity::from_decimal_dp(position.number_of_contracts, size_precision)
1047        .context("failed to build CFM position quantity")?;
1048
1049    let avg_px_open = if position.avg_entry_price.value.is_zero() {
1050        None
1051    } else {
1052        Some(position.avg_entry_price.value)
1053    };
1054
1055    Ok(PositionStatusReport::new(
1056        account_id,
1057        instrument_id,
1058        position_side,
1059        quantity,
1060        ts_init,
1061        ts_init,
1062        None,
1063        None,
1064        avg_px_open,
1065    ))
1066}
1067
1068// Coinbase history endpoints return a wider set of configuration shapes than
1069// `OrderConfiguration` covers (bracket, TWAP, trigger variants). History
1070// `Order.order_configuration` is kept as a raw `serde_json::Value`; these
1071// accessors read the value by key so unknown shapes simply return `None`
1072// instead of failing the whole batch.
1073fn base_quantity_from_configuration(order: &Order, size_precision: u8) -> Option<Quantity> {
1074    let config = order.order_configuration.as_ref()?.as_object()?;
1075
1076    for (_key, inner) in config {
1077        let Some(inner_obj) = inner.as_object() else {
1078            continue;
1079        };
1080
1081        if let Some(size) = inner_obj
1082            .get(ORDER_CONFIG_BASE_SIZE)
1083            .and_then(|v| v.as_str())
1084            && !size.is_empty()
1085            && let Ok(qty) = parse_quantity(size, size_precision)
1086        {
1087            return Some(qty);
1088        }
1089    }
1090
1091    None
1092}
1093
1094fn limit_price_from_configuration(order: &Order, price_precision: u8) -> Option<Price> {
1095    let config = order.order_configuration.as_ref()?.as_object()?;
1096
1097    for (_key, inner) in config {
1098        let Some(inner_obj) = inner.as_object() else {
1099            continue;
1100        };
1101
1102        if let Some(price) = inner_obj
1103            .get(ORDER_CONFIG_LIMIT_PRICE)
1104            .and_then(|v| v.as_str())
1105            && !price.is_empty()
1106            && let Ok(parsed) = parse_price(price, price_precision)
1107        {
1108            return Some(parsed);
1109        }
1110    }
1111
1112    None
1113}
1114
1115fn stop_price_from_configuration(order: &Order, price_precision: u8) -> Option<Price> {
1116    let config = order.order_configuration.as_ref()?.as_object()?;
1117
1118    for (_key, inner) in config {
1119        let Some(inner_obj) = inner.as_object() else {
1120            continue;
1121        };
1122
1123        if let Some(stop) = inner_obj
1124            .get(ORDER_CONFIG_STOP_PRICE)
1125            .and_then(|v| v.as_str())
1126            && !stop.is_empty()
1127            && let Ok(parsed) = parse_price(stop, price_precision)
1128        {
1129            return Some(parsed);
1130        }
1131    }
1132
1133    None
1134}
1135
1136fn post_only_from_configuration(order: &Order) -> bool {
1137    let Some(config) = order
1138        .order_configuration
1139        .as_ref()
1140        .and_then(|v| v.as_object())
1141    else {
1142        return false;
1143    };
1144
1145    for (_key, inner) in config {
1146        if let Some(inner_obj) = inner.as_object()
1147            && let Some(post_only) = inner_obj
1148                .get(ORDER_CONFIG_POST_ONLY)
1149                .and_then(|v| v.as_bool())
1150        {
1151            return post_only;
1152        }
1153    }
1154    false
1155}
1156
1157fn end_time_from_configuration(order: &Order) -> Option<UnixNanos> {
1158    let config = order.order_configuration.as_ref()?.as_object()?;
1159
1160    for (_key, inner) in config {
1161        if let Some(inner_obj) = inner.as_object()
1162            && let Some(end_time) = inner_obj
1163                .get(ORDER_CONFIG_END_TIME)
1164                .and_then(|v| v.as_str())
1165            && !end_time.is_empty()
1166            && let Ok(ts) = parse_rfc3339_timestamp(end_time)
1167        {
1168            return Some(ts);
1169        }
1170    }
1171
1172    None
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177    use nautilus_model::{
1178        data::bar::{BarSpecification, BarType},
1179        enums::{AggregationSource, BarAggregation, PriceType},
1180        identifiers::Venue,
1181        instruments::Instrument,
1182    };
1183    use rstest::rstest;
1184    use ustr::Ustr;
1185
1186    use super::*;
1187    use crate::{
1188        common::{
1189            consts::COINBASE_VENUE,
1190            enums::{CoinbaseMarginLevel, CoinbaseMarginWindowType},
1191            testing::load_test_fixture,
1192        },
1193        http::models::{Account, Balance},
1194    };
1195
1196    fn coinbase_venue() -> Venue {
1197        *COINBASE_VENUE
1198    }
1199
1200    #[rstest]
1201    #[case("0.01", 2)]
1202    #[case("0.00000001", 8)]
1203    #[case("1", 0)]
1204    #[case("5", 0)]
1205    #[case("0.1", 1)]
1206    #[case("0.001", 3)]
1207    #[case("25.000", 0)]
1208    fn test_precision_from_increment(#[case] increment: &str, #[case] expected: u8) {
1209        assert_eq!(precision_from_increment(increment), expected);
1210    }
1211
1212    #[rstest]
1213    fn test_parse_rfc3339_timestamp() {
1214        let ts = parse_rfc3339_timestamp("2026-04-07T00:28:32.643779Z").unwrap();
1215        assert_eq!(ts.as_u64(), 1_775_521_712_643_779_000);
1216    }
1217
1218    #[rstest]
1219    #[case("")]
1220    #[case("not-a-date")]
1221    #[case("2026-13-01T00:00:00Z")]
1222    fn test_parse_rfc3339_timestamp_rejects_invalid(#[case] input: &str) {
1223        assert!(parse_rfc3339_timestamp(input).is_err());
1224    }
1225
1226    #[rstest]
1227    fn test_parse_epoch_secs_timestamp() {
1228        let ts = parse_epoch_secs_timestamp("1712192400").unwrap();
1229        assert_eq!(ts.as_u64(), 1_712_192_400_000_000_000);
1230    }
1231
1232    #[rstest]
1233    #[case("")]
1234    #[case("abc")]
1235    fn test_parse_epoch_secs_timestamp_rejects_invalid(#[case] input: &str) {
1236        assert!(parse_epoch_secs_timestamp(input).is_err());
1237    }
1238
1239    #[rstest]
1240    fn test_parse_price_valid() {
1241        let price = parse_price("68913.87", 2).unwrap();
1242        assert_eq!(price, Price::from("68913.87"));
1243    }
1244
1245    #[rstest]
1246    #[case("")]
1247    #[case("abc")]
1248    fn test_parse_price_rejects_invalid(#[case] input: &str) {
1249        assert!(parse_price(input, 2).is_err());
1250    }
1251
1252    #[rstest]
1253    fn test_parse_quantity_valid() {
1254        let qty = parse_quantity("0.00014004", 8).unwrap();
1255        assert_eq!(qty, Quantity::from("0.00014004"));
1256    }
1257
1258    #[rstest]
1259    #[case("")]
1260    #[case("abc")]
1261    fn test_parse_quantity_rejects_invalid(#[case] input: &str) {
1262        assert!(parse_quantity(input, 8).is_err());
1263    }
1264
1265    #[rstest]
1266    fn test_parse_spot_instrument() {
1267        let json = load_test_fixture("http_product.json");
1268        let product: crate::http::models::Product = serde_json::from_str(&json).unwrap();
1269        let ts = UnixNanos::default();
1270
1271        let instrument = parse_spot_instrument(&product, ts).unwrap();
1272        let pair = match &instrument {
1273            InstrumentAny::CurrencyPair(p) => p,
1274            other => panic!("Expected CurrencyPair, was{other:?}"),
1275        };
1276
1277        assert_eq!(pair.id().symbol.as_str(), "BTC-USD");
1278        assert_eq!(pair.id().venue, coinbase_venue());
1279        assert_eq!(pair.base_currency().unwrap().code, "BTC");
1280        assert_eq!(pair.quote_currency().code, "USD");
1281        assert_eq!(pair.price_precision(), 2);
1282        assert_eq!(pair.size_precision(), 8);
1283        assert_eq!(pair.price_increment(), Price::from("0.01"));
1284        assert_eq!(pair.size_increment(), Quantity::from("0.00000001"));
1285        assert_eq!(pair.min_quantity(), Some(Quantity::from("0.00000001")));
1286        assert_eq!(pair.max_quantity(), Some(Quantity::from("3400")));
1287    }
1288
1289    #[rstest]
1290    fn test_parse_spot_instrument_normalizes_padded_increments() {
1291        let json = load_test_fixture("http_product.json");
1292        let mut product: crate::http::models::Product = serde_json::from_str(&json).unwrap();
1293        product.price_increment = "25.000".to_string();
1294        product.base_increment = "1.2300".to_string();
1295
1296        let instrument = parse_spot_instrument(&product, UnixNanos::default()).unwrap();
1297        let InstrumentAny::CurrencyPair(pair) = instrument else {
1298            panic!("Expected CurrencyPair");
1299        };
1300
1301        assert_eq!(pair.price_precision(), 0);
1302        assert_eq!(pair.price_increment(), Price::from("25"));
1303        assert_eq!(pair.price_increment().precision, 0);
1304        assert_eq!(pair.size_precision(), 2);
1305        assert_eq!(pair.size_increment(), Quantity::from("1.23"));
1306        assert_eq!(pair.size_increment().precision, 2);
1307    }
1308
1309    #[rstest]
1310    fn test_parse_derivative_instruments_normalize_padded_increments() {
1311        let json = load_test_fixture("http_products_future.json");
1312        let response: crate::http::models::ProductsResponse = serde_json::from_str(&json).unwrap();
1313        let mut perp_product = response
1314            .products
1315            .iter()
1316            .find(|product| product.display_name.contains("PERP"))
1317            .unwrap()
1318            .clone();
1319        let mut future_product = response
1320            .products
1321            .iter()
1322            .find(|product| !product.display_name.contains("PERP"))
1323            .unwrap()
1324            .clone();
1325
1326        for product in [&mut perp_product, &mut future_product] {
1327            product.price_increment = "25.000".to_string();
1328            product.base_increment = "1.2300".to_string();
1329        }
1330
1331        let perp = parse_perpetual_instrument(&perp_product, UnixNanos::default()).unwrap();
1332        let future = parse_future_instrument(&future_product, UnixNanos::default()).unwrap();
1333
1334        for instrument in [&perp, &future] {
1335            assert_eq!(instrument.price_precision(), 0);
1336            assert_eq!(instrument.price_increment(), Price::from("25"));
1337            assert_eq!(instrument.price_increment().precision, 0);
1338            assert_eq!(instrument.size_precision(), 2);
1339            assert_eq!(instrument.size_increment(), Quantity::from("1.23"));
1340            assert_eq!(instrument.size_increment().precision, 2);
1341        }
1342    }
1343
1344    #[rstest]
1345    fn test_parse_spot_instruments_from_list() {
1346        let json = load_test_fixture("http_products.json");
1347        let response: crate::http::models::ProductsResponse = serde_json::from_str(&json).unwrap();
1348        let ts = UnixNanos::default();
1349
1350        let instruments: Vec<InstrumentAny> = response
1351            .products
1352            .iter()
1353            .map(|p| parse_instrument(p, ts).unwrap())
1354            .collect();
1355
1356        assert_eq!(instruments.len(), 2);
1357        for inst in &instruments {
1358            assert!(matches!(inst, InstrumentAny::CurrencyPair(_)));
1359        }
1360    }
1361
1362    #[rstest]
1363    fn test_parse_future_instruments_distinguishes_perp_and_dated() {
1364        let json = load_test_fixture("http_products_future.json");
1365        let response: crate::http::models::ProductsResponse = serde_json::from_str(&json).unwrap();
1366        let ts = UnixNanos::default();
1367
1368        let instruments: Vec<InstrumentAny> = response
1369            .products
1370            .iter()
1371            .map(|p| parse_instrument(p, ts).unwrap())
1372            .collect();
1373
1374        assert_eq!(instruments.len(), 2);
1375
1376        // First product is "BTC PERP" -> CryptoPerpetual
1377        assert!(
1378            matches!(&instruments[0], InstrumentAny::CryptoPerpetual(_)),
1379            "Expected CryptoPerpetual for BTC PERP, was{:?}",
1380            instruments[0]
1381        );
1382
1383        // Second product is "BTC 24 APR 26" -> CryptoFuture
1384        assert!(
1385            matches!(&instruments[1], InstrumentAny::CryptoFuture(_)),
1386            "Expected CryptoFuture for dated future, was{:?}",
1387            instruments[1]
1388        );
1389    }
1390
1391    #[rstest]
1392    fn test_parse_perpetual_instrument_derives_base_from_display_name() {
1393        let json = load_test_fixture("http_products_future.json");
1394        let response: crate::http::models::ProductsResponse = serde_json::from_str(&json).unwrap();
1395        let ts = UnixNanos::default();
1396
1397        // The first future product has empty base_currency_id and display_name "BTC PERP"
1398        let perp_product = response
1399            .products
1400            .iter()
1401            .find(|p| p.display_name.contains("PERP"))
1402            .expect("should have a PERP product");
1403
1404        let instrument = parse_perpetual_instrument(perp_product, ts).unwrap();
1405        let perp = match &instrument {
1406            InstrumentAny::CryptoPerpetual(p) => p,
1407            other => panic!("Expected CryptoPerpetual, was{other:?}"),
1408        };
1409
1410        assert_eq!(perp.base_currency().unwrap().code, "BTC");
1411        assert_eq!(perp.quote_currency().code, "USD");
1412    }
1413
1414    #[rstest]
1415    fn test_parse_perpetual_instrument_has_contract_size_multiplier() {
1416        let json = load_test_fixture("http_products_future.json");
1417        let response: crate::http::models::ProductsResponse = serde_json::from_str(&json).unwrap();
1418        let ts = UnixNanos::default();
1419
1420        let perp_product = response
1421            .products
1422            .iter()
1423            .find(|p| p.display_name.contains("PERP"))
1424            .expect("should have a PERP product");
1425
1426        let instrument = parse_perpetual_instrument(perp_product, ts).unwrap();
1427        let perp = match &instrument {
1428            InstrumentAny::CryptoPerpetual(p) => p,
1429            other => panic!("Expected CryptoPerpetual, was {other:?}"),
1430        };
1431
1432        assert_eq!(perp.multiplier, Quantity::from("0.01"));
1433    }
1434
1435    #[rstest]
1436    fn test_parse_future_instrument_has_expiry_and_multiplier() {
1437        let json = load_test_fixture("http_products_future.json");
1438        let response: crate::http::models::ProductsResponse = serde_json::from_str(&json).unwrap();
1439        let ts = UnixNanos::default();
1440
1441        let future_product = response
1442            .products
1443            .iter()
1444            .find(|p| !p.display_name.contains("PERP") && !p.display_name.contains("Perpetual"))
1445            .expect("should have a dated future product");
1446
1447        let instrument = parse_future_instrument(future_product, ts).unwrap();
1448        let future = match &instrument {
1449            InstrumentAny::CryptoFuture(f) => f,
1450            other => panic!("Expected CryptoFuture, was {other:?}"),
1451        };
1452
1453        // Verify contract_expiry "2026-04-24T15:00:00Z" parsed correctly
1454        let expected_expiry = parse_rfc3339_timestamp("2026-04-24T15:00:00Z").unwrap();
1455        assert_eq!(future.expiration_ns, expected_expiry);
1456        assert_eq!(future.multiplier, Quantity::from("0.01"));
1457        assert_eq!(future.base_currency().unwrap().code, "BTC");
1458        assert_eq!(future.quote_currency().code, "USD");
1459    }
1460
1461    #[rstest]
1462    fn test_parse_trade_tick() {
1463        let json = load_test_fixture("http_ticker.json");
1464        let response: crate::http::models::TickerResponse = serde_json::from_str(&json).unwrap();
1465        let instrument_id = InstrumentId::new(Symbol::new("BTC-USD"), coinbase_venue());
1466        let ts_init = UnixNanos::default();
1467
1468        let trades: Vec<TradeTick> = response
1469            .trades
1470            .iter()
1471            .map(|t| parse_trade_tick(t, instrument_id, 2, 8, ts_init).unwrap())
1472            .collect();
1473
1474        assert_eq!(trades.len(), 3);
1475
1476        // Verify exact values from first fixture trade
1477        assert_eq!(trades[0].instrument_id, instrument_id);
1478        assert_eq!(trades[0].price, Price::from("68923.67"));
1479        assert_eq!(trades[0].size, Quantity::from("0.00064000"));
1480        assert_eq!(trades[0].trade_id.as_str(), "995098663");
1481        assert!(trades[0].ts_event.as_u64() > 0);
1482    }
1483
1484    #[rstest]
1485    fn test_parse_trade_tick_aggressor_side() {
1486        let json = load_test_fixture("http_ticker.json");
1487        let response: crate::http::models::TickerResponse = serde_json::from_str(&json).unwrap();
1488        let instrument_id = InstrumentId::new(Symbol::new("BTC-USD"), coinbase_venue());
1489        let ts_init = UnixNanos::default();
1490
1491        let aggressor_sides: Vec<AggressorSide> = response
1492            .trades
1493            .iter()
1494            .map(|t| {
1495                parse_trade_tick(t, instrument_id, 2, 8, ts_init)
1496                    .unwrap()
1497                    .aggressor_side
1498            })
1499            .collect();
1500
1501        // Fixture sides are SELL, SELL, BUY (maker sides)
1502        assert_eq!(
1503            aggressor_sides,
1504            vec![AggressorSide::Buy, AggressorSide::Buy, AggressorSide::Sell],
1505        );
1506    }
1507
1508    #[rstest]
1509    fn test_parse_bar() {
1510        let json = load_test_fixture("http_candles.json");
1511        let response: crate::http::models::CandlesResponse = serde_json::from_str(&json).unwrap();
1512
1513        let instrument_id = InstrumentId::new(Symbol::new("BTC-USD"), coinbase_venue());
1514        let bar_spec = BarSpecification::new(1, BarAggregation::Hour, PriceType::Last);
1515        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::External);
1516        let ts_init = UnixNanos::default();
1517
1518        let bars: Vec<Bar> = response
1519            .candles
1520            .iter()
1521            .map(|c| parse_bar(c, bar_type, 2, 8, ts_init).unwrap())
1522            .collect();
1523
1524        assert_eq!(bars.len(), 2);
1525
1526        // Verify exact OHLCV from first fixture candle (start=1712192400)
1527        let bar = &bars[0];
1528        assert_eq!(bar.bar_type, bar_type);
1529        assert_eq!(bar.open, Price::from("66312.40"));
1530        assert_eq!(bar.high, Price::from("66331.99"));
1531        assert_eq!(bar.low, Price::from("66055.14"));
1532        assert_eq!(bar.close, Price::from("66181.60"));
1533        assert_eq!(bar.volume, Quantity::from("355.82896243"));
1534        assert_eq!(bar.ts_event.as_u64(), 1_712_192_400_000_000_000);
1535    }
1536
1537    #[rstest]
1538    fn test_parse_product_book_snapshot() {
1539        let json = load_test_fixture("http_product_book.json");
1540        let response: crate::http::models::ProductBookResponse =
1541            serde_json::from_str(&json).unwrap();
1542
1543        let instrument_id = InstrumentId::new(Symbol::new("BTC-USD"), coinbase_venue());
1544        let ts_init = UnixNanos::default();
1545
1546        let deltas =
1547            parse_product_book_snapshot(&response.pricebook, instrument_id, 2, 8, ts_init).unwrap();
1548
1549        assert_eq!(deltas.instrument_id, instrument_id);
1550        let total_levels = response.pricebook.bids.len() + response.pricebook.asks.len();
1551        assert_eq!(deltas.deltas.len(), total_levels + 1);
1552
1553        // First delta is a clear
1554        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1555
1556        // Verify first bid side and price
1557        let first_bid = &deltas.deltas[1];
1558        assert_eq!(first_bid.order.side, OrderSide::Buy.into());
1559        assert_eq!(first_bid.action, BookAction::Add);
1560        assert!(first_bid.order.price.as_f64() > 0.0);
1561
1562        // Verify first ask comes after bids
1563        let first_ask_idx = response.pricebook.bids.len() + 1;
1564        let first_ask = &deltas.deltas[first_ask_idx];
1565        assert_eq!(first_ask.order.side, OrderSide::Sell.into());
1566        assert_eq!(first_ask.action, BookAction::Add);
1567
1568        // Last delta has F_LAST flag
1569        let last = deltas.deltas.last().unwrap();
1570        assert_ne!(last.flags & RecordFlag::F_LAST as u8, 0);
1571
1572        // Every delta in a snapshot sequence carries F_SNAPSHOT.
1573        for delta in &deltas.deltas {
1574            assert_ne!(
1575                delta.flags & RecordFlag::F_SNAPSHOT as u8,
1576                0,
1577                "snapshot delta missing F_SNAPSHOT: {delta:?}",
1578            );
1579        }
1580    }
1581
1582    // Empty-book snapshots must carry F_SNAPSHOT | F_LAST on the lone Clear
1583    // delta so buffered consumers receive the clear event; without F_LAST the
1584    // DataEngine never flushes and downstream subscribers see nothing.
1585    #[rstest]
1586    fn test_parse_product_book_snapshot_empty_book_clear_carries_snapshot_and_last() {
1587        let pricebook = crate::http::models::PriceBook {
1588            product_id: Ustr::from("BTC-USD"),
1589            bids: Vec::new(),
1590            asks: Vec::new(),
1591            time: "2024-01-15T10:30:00Z".to_string(),
1592        };
1593        let instrument_id = InstrumentId::new(Symbol::new("BTC-USD"), coinbase_venue());
1594
1595        let deltas =
1596            parse_product_book_snapshot(&pricebook, instrument_id, 2, 8, UnixNanos::default())
1597                .unwrap();
1598        assert_eq!(deltas.deltas.len(), 1);
1599        let clear = &deltas.deltas[0];
1600        assert_eq!(clear.action, BookAction::Clear);
1601        assert_ne!(clear.flags & RecordFlag::F_SNAPSHOT as u8, 0);
1602        assert_ne!(clear.flags & RecordFlag::F_LAST as u8, 0);
1603    }
1604
1605    fn btc_usd_instrument() -> InstrumentAny {
1606        let json = load_test_fixture("http_product.json");
1607        let product: crate::http::models::Product = serde_json::from_str(&json).unwrap();
1608        parse_spot_instrument(&product, UnixNanos::default()).unwrap()
1609    }
1610
1611    #[rstest]
1612    fn test_parse_order_status_report_fully_filled_limit_gtc() {
1613        let json = load_test_fixture("http_order.json");
1614        let response: crate::http::models::OrderResponse = serde_json::from_str(&json).unwrap();
1615        let instrument = btc_usd_instrument();
1616        let account_id = AccountId::new("COINBASE-001");
1617        let ts_init = UnixNanos::from(1);
1618
1619        let report =
1620            parse_order_status_report(&response.order, &instrument, account_id, ts_init).unwrap();
1621
1622        assert_eq!(report.account_id, account_id);
1623        assert_eq!(report.instrument_id.symbol.as_str(), "BTC-USD");
1624        assert_eq!(report.venue_order_id.as_str(), "0000-000000-000000");
1625        assert_eq!(
1626            report.client_order_id.unwrap().as_str(),
1627            "11111-000000-000000"
1628        );
1629        assert_eq!(report.order_side, OrderSide::Buy.into());
1630        assert_eq!(report.order_type, OrderType::Limit);
1631        assert_eq!(report.time_in_force, TimeInForce::Gtc);
1632        // filled_size (0.001) == base_size (0.001), so status stays Accepted
1633        // rather than promoting to PartiallyFilled.
1634        assert_eq!(report.order_status, OrderStatus::Accepted);
1635        assert_eq!(report.quantity, Quantity::from("0.001"));
1636        assert_eq!(report.filled_qty, Quantity::from("0.001"));
1637        assert_eq!(report.price, Some(Price::from("10000.00")));
1638        assert_eq!(report.avg_px, Some(Decimal::from(50)));
1639    }
1640
1641    #[rstest]
1642    fn test_parse_order_status_report_filled_market_order() {
1643        let json = load_test_fixture("http_orders_list.json");
1644        let response: crate::http::models::OrdersListResponse =
1645            serde_json::from_str(&json).unwrap();
1646        let instrument = btc_usd_instrument();
1647        let account_id = AccountId::new("COINBASE-001");
1648        let ts_init = UnixNanos::from(1);
1649
1650        // Second order in the list is a filled MARKET order
1651        let filled_order = &response.orders[1];
1652        let report =
1653            parse_order_status_report(filled_order, &instrument, account_id, ts_init).unwrap();
1654
1655        assert_eq!(report.order_status, OrderStatus::Filled);
1656        assert_eq!(report.order_type, OrderType::Market);
1657        assert_eq!(report.order_side, OrderSide::Sell.into());
1658        assert_eq!(report.time_in_force, TimeInForce::Ioc);
1659        // Market quote-size orders fall back to filled_qty for total quantity
1660        assert_eq!(report.filled_qty, Quantity::from("0.0325"));
1661        assert_eq!(report.quantity, report.filled_qty);
1662        assert!(report.price.is_none());
1663    }
1664
1665    #[rstest]
1666    fn test_parse_fill_report_maker() {
1667        let json = load_test_fixture("http_fills.json");
1668        let response: crate::http::models::FillsResponse = serde_json::from_str(&json).unwrap();
1669        let instrument = btc_usd_instrument();
1670        let account_id = AccountId::new("COINBASE-001");
1671        let ts_init = UnixNanos::from(1);
1672
1673        let maker_fill = &response.fills[0];
1674        let report = parse_fill_report(maker_fill, &instrument, account_id, ts_init).unwrap();
1675
1676        assert_eq!(report.account_id, account_id);
1677        assert_eq!(report.trade_id.as_str(), "1111-11111-111111");
1678        assert_eq!(report.venue_order_id.as_str(), "0000-000000-000000");
1679        assert_eq!(report.order_side, OrderSide::Buy);
1680        assert_eq!(report.liquidity_side, LiquiditySide::Maker);
1681        assert_eq!(report.last_px, Price::from("45123.45"));
1682        assert_eq!(report.last_qty, Quantity::from("0.00500000"));
1683        assert_eq!(
1684            report.commission.as_decimal(),
1685            Decimal::from_str("1.14").unwrap()
1686        );
1687        assert_eq!(report.commission.currency.code, "USD");
1688    }
1689
1690    #[rstest]
1691    fn test_parse_account_state_spot_cash() {
1692        let json = load_test_fixture("http_accounts.json");
1693        let response: crate::http::models::AccountsResponse = serde_json::from_str(&json).unwrap();
1694        let account_id = AccountId::new("COINBASE-001");
1695        let ts_event = UnixNanos::from(1);
1696        let ts_init = UnixNanos::from(2);
1697
1698        let state =
1699            parse_account_state(&response.accounts, account_id, true, ts_event, ts_init).unwrap();
1700
1701        assert_eq!(state.account_id, account_id);
1702        assert_eq!(state.account_type, AccountType::Cash);
1703        assert!(state.is_reported);
1704        assert_eq!(state.margins.len(), 0);
1705        assert_eq!(state.balances.len(), 2);
1706
1707        let btc_balance = state
1708            .balances
1709            .iter()
1710            .find(|b| b.currency.code == "BTC")
1711            .expect("BTC balance present");
1712        assert_eq!(
1713            btc_balance.free.as_decimal(),
1714            Decimal::from_str("1.23456789").unwrap()
1715        );
1716        assert_eq!(
1717            btc_balance.locked.as_decimal(),
1718            Decimal::from_str("0.00500000").unwrap()
1719        );
1720        assert_eq!(
1721            btc_balance.total.as_decimal(),
1722            btc_balance.free.as_decimal() + btc_balance.locked.as_decimal()
1723        );
1724
1725        let usd_balance = state
1726            .balances
1727            .iter()
1728            .find(|b| b.currency.code == "USD")
1729            .expect("USD balance present");
1730        assert_eq!(
1731            usd_balance.free.as_decimal(),
1732            Decimal::from_str("10000.50").unwrap()
1733        );
1734        assert_eq!(
1735            usd_balance.locked.as_decimal(),
1736            Decimal::from_str("450.00").unwrap()
1737        );
1738    }
1739
1740    #[rstest]
1741    fn test_parse_account_state_aggregates_same_currency() {
1742        fn make_account(
1743            currency: &str,
1744            available: &str,
1745            hold: &str,
1746            uuid: &str,
1747            portfolio: &str,
1748        ) -> Account {
1749            Account {
1750                uuid: uuid.to_string(),
1751                name: "wallet".to_string(),
1752                currency: Ustr::from(currency),
1753                available_balance: Balance {
1754                    value: Decimal::from_str(available).unwrap(),
1755                    currency: Ustr::from(currency),
1756                },
1757                default: false,
1758                active: true,
1759                created_at: String::new(),
1760                updated_at: String::new(),
1761                deleted_at: None,
1762                account_type: crate::common::enums::CoinbaseAccountType::Fiat,
1763                ready: true,
1764                hold: Some(Balance {
1765                    value: Decimal::from_str(hold).unwrap(),
1766                    currency: Ustr::from(currency),
1767                }),
1768                retail_portfolio_id: portfolio.to_string(),
1769            }
1770        }
1771
1772        let accounts = vec![
1773            make_account("USD", "1000.00", "50.00", "uuid-1", "portfolio-a"),
1774            make_account("USD", "2500.00", "25.00", "uuid-2", "portfolio-b"),
1775            make_account("BTC", "0.5", "0.1", "uuid-3", "portfolio-a"),
1776        ];
1777
1778        let account_id = AccountId::new("COINBASE-001");
1779        let state = parse_account_state(
1780            &accounts,
1781            account_id,
1782            true,
1783            UnixNanos::from(1),
1784            UnixNanos::from(2),
1785        )
1786        .unwrap();
1787
1788        assert_eq!(state.balances.len(), 2);
1789
1790        let usd = state
1791            .balances
1792            .iter()
1793            .find(|b| b.currency.code == "USD")
1794            .expect("USD balance aggregated");
1795        assert_eq!(usd.free.as_decimal(), Decimal::from_str("3500.00").unwrap());
1796        assert_eq!(usd.locked.as_decimal(), Decimal::from_str("75.00").unwrap());
1797        assert_eq!(
1798            usd.total.as_decimal(),
1799            Decimal::from_str("3575.00").unwrap()
1800        );
1801
1802        let btc = state
1803            .balances
1804            .iter()
1805            .find(|b| b.currency.code == "BTC")
1806            .expect("BTC balance present");
1807        assert_eq!(btc.free.as_decimal(), Decimal::from_str("0.5").unwrap());
1808        assert_eq!(btc.locked.as_decimal(), Decimal::from_str("0.1").unwrap());
1809    }
1810
1811    #[rstest]
1812    fn test_parse_account_state_empty_falls_back_to_zero_usd() {
1813        let account_id = AccountId::new("COINBASE-001");
1814        let state = parse_account_state(
1815            &[],
1816            account_id,
1817            true,
1818            UnixNanos::from(1),
1819            UnixNanos::from(2),
1820        )
1821        .unwrap();
1822
1823        assert_eq!(state.balances.len(), 1);
1824        let balance = &state.balances[0];
1825        assert_eq!(balance.currency.code, "USD");
1826        assert_eq!(balance.total.as_decimal(), Decimal::ZERO);
1827    }
1828
1829    #[rstest]
1830    #[case(CoinbaseOrderType::Market, OrderType::Market)]
1831    #[case(CoinbaseOrderType::Limit, OrderType::Limit)]
1832    #[case(CoinbaseOrderType::Stop, OrderType::StopMarket)]
1833    #[case(CoinbaseOrderType::StopLimit, OrderType::StopLimit)]
1834    #[case(CoinbaseOrderType::Bracket, OrderType::Limit)]
1835    #[case(CoinbaseOrderType::Twap, OrderType::Limit)]
1836    #[case(CoinbaseOrderType::RollOpen, OrderType::Limit)]
1837    #[case(CoinbaseOrderType::RollClose, OrderType::Limit)]
1838    #[case(CoinbaseOrderType::Liquidation, OrderType::Market)]
1839    #[case(CoinbaseOrderType::Scaled, OrderType::Limit)]
1840    #[case(CoinbaseOrderType::Unknown, OrderType::Limit)]
1841    fn test_parse_order_type(#[case] input: CoinbaseOrderType, #[case] expected: OrderType) {
1842        assert_eq!(parse_order_type(input), expected);
1843    }
1844
1845    #[rstest]
1846    #[case(CoinbaseOrderStatus::Open, OrderStatus::Accepted)]
1847    #[case(CoinbaseOrderStatus::Filled, OrderStatus::Filled)]
1848    #[case(CoinbaseOrderStatus::Cancelled, OrderStatus::Canceled)]
1849    #[case(CoinbaseOrderStatus::CancelQueued, OrderStatus::PendingCancel)]
1850    #[case(CoinbaseOrderStatus::EditQueued, OrderStatus::PendingUpdate)]
1851    #[case(CoinbaseOrderStatus::Expired, OrderStatus::Expired)]
1852    #[case(CoinbaseOrderStatus::Failed, OrderStatus::Rejected)]
1853    #[case(CoinbaseOrderStatus::Pending, OrderStatus::Accepted)]
1854    #[case(CoinbaseOrderStatus::Queued, OrderStatus::Accepted)]
1855    fn test_parse_order_status(#[case] input: CoinbaseOrderStatus, #[case] expected: OrderStatus) {
1856        assert_eq!(parse_order_status(input), expected);
1857    }
1858
1859    // Builds a minimal limit-GTC order with overridable size fields so tests
1860    // can exercise partial-fill, error, and boundary paths without adding a
1861    // fixture per permutation.
1862    fn make_limit_gtc_order(
1863        base_size: &str,
1864        limit_price: &str,
1865        filled_size: &str,
1866        status: CoinbaseOrderStatus,
1867    ) -> crate::http::models::Order {
1868        crate::http::models::Order {
1869            order_id: "venue-abc".to_string(),
1870            product_id: Ustr::from("BTC-USD"),
1871            user_id: "user-1".to_string(),
1872            order_configuration: Some(serde_json::json!({
1873                "limit_limit_gtc": {
1874                    "base_size": base_size,
1875                    "limit_price": limit_price,
1876                    "post_only": false,
1877                }
1878            })),
1879            side: CoinbaseOrderSide::Buy,
1880            client_order_id: "client-abc".to_string(),
1881            status,
1882            time_in_force: Some(CoinbaseTimeInForce::GoodUntilCancelled),
1883            created_time: "2024-01-15T10:00:00Z".to_string(),
1884            completion_percentage: String::new(),
1885            filled_size: filled_size.to_string(),
1886            average_filled_price: String::new(),
1887            fee: Decimal::ZERO,
1888            number_of_fills: 0,
1889            filled_value: Decimal::ZERO,
1890            pending_cancel: false,
1891            size_in_quote: false,
1892            total_fees: Decimal::ZERO,
1893            size_inclusive_of_fees: false,
1894            total_value_after_fees: Decimal::ZERO,
1895            trigger_status: crate::common::enums::CoinbaseTriggerStatus::Unknown,
1896            order_type: CoinbaseOrderType::Limit,
1897            reject_reason: String::new(),
1898            settled: false,
1899            product_type: CoinbaseProductType::Spot,
1900            reject_message: String::new(),
1901            cancel_message: String::new(),
1902            order_placement_source:
1903                crate::common::enums::CoinbaseOrderPlacementSource::RetailAdvanced,
1904            outstanding_hold_amount: Decimal::ZERO,
1905            is_liquidation: false,
1906            last_fill_time: None,
1907            leverage: String::new(),
1908            margin_type: None,
1909            retail_portfolio_id: String::new(),
1910            originating_order_id: String::new(),
1911            attached_order_id: String::new(),
1912        }
1913    }
1914
1915    #[rstest]
1916    #[case::partially_filled("0.001", "0.0005", OrderStatus::PartiallyFilled)]
1917    #[case::fully_equals_boundary("0.001", "0.001", OrderStatus::Accepted)]
1918    #[case::zero_filled("0.001", "0", OrderStatus::Accepted)]
1919    fn test_parse_order_status_report_promotes_to_partially_filled(
1920        #[case] base_size: &str,
1921        #[case] filled_size: &str,
1922        #[case] expected_status: OrderStatus,
1923    ) {
1924        let order = make_limit_gtc_order(
1925            base_size,
1926            "50000.00",
1927            filled_size,
1928            CoinbaseOrderStatus::Open,
1929        );
1930        let instrument = btc_usd_instrument();
1931        let account_id = AccountId::new("COINBASE-001");
1932
1933        let report =
1934            parse_order_status_report(&order, &instrument, account_id, UnixNanos::from(1)).unwrap();
1935
1936        assert_eq!(report.order_status, expected_status);
1937        assert_eq!(report.quantity, Quantity::from(base_size));
1938    }
1939
1940    #[rstest]
1941    fn test_parse_order_status_report_handles_liquidation_order_type() {
1942        let mut order =
1943            make_limit_gtc_order("0.001", "50000.00", "0.001", CoinbaseOrderStatus::Filled);
1944        order.order_type = CoinbaseOrderType::Liquidation;
1945        let instrument = btc_usd_instrument();
1946
1947        let report = parse_order_status_report(
1948            &order,
1949            &instrument,
1950            AccountId::new("COINBASE-001"),
1951            UnixNanos::from(1),
1952        )
1953        .unwrap();
1954
1955        assert_eq!(report.order_type, OrderType::Market);
1956        assert_eq!(report.order_status, OrderStatus::Filled);
1957    }
1958
1959    #[rstest]
1960    fn test_parse_order_status_report_handles_is_liquidation_flag() {
1961        let mut order =
1962            make_limit_gtc_order("0.001", "50000.00", "0.001", CoinbaseOrderStatus::Filled);
1963        order.is_liquidation = true;
1964        let instrument = btc_usd_instrument();
1965
1966        let report = parse_order_status_report(
1967            &order,
1968            &instrument,
1969            AccountId::new("COINBASE-001"),
1970            UnixNanos::from(1),
1971        )
1972        .unwrap();
1973
1974        // Pin the fields the warn branch reads so a future refactor that drops
1975        // the `is_liquidation` arm cannot accept this fixture by accident.
1976        assert_eq!(report.order_status, OrderStatus::Filled);
1977        assert_eq!(report.order_side, OrderSide::Buy.into());
1978        assert_eq!(report.filled_qty, Quantity::from("0.001"));
1979        assert_eq!(report.instrument_id, instrument.id());
1980    }
1981
1982    #[rstest]
1983    fn test_parse_order_status_report_rejects_malformed_filled_size() {
1984        let mut order = make_limit_gtc_order("0.001", "50000.00", "0", CoinbaseOrderStatus::Open);
1985        order.filled_size = "not-a-number".to_string();
1986        let instrument = btc_usd_instrument();
1987
1988        let err = parse_order_status_report(
1989            &order,
1990            &instrument,
1991            AccountId::new("COINBASE-001"),
1992            UnixNanos::from(1),
1993        )
1994        .unwrap_err();
1995
1996        let chain = format!("{err:#}");
1997        assert!(
1998            chain.contains("failed to parse filled_size"),
1999            "expected failed to parse filled_size in error chain, was: {chain}"
2000        );
2001    }
2002
2003    fn make_fill(commission: &str, price: &str, size: &str, trade_time: &str) -> Fill {
2004        Fill {
2005            entry_id: "entry-1".to_string(),
2006            trade_id: "trade-1".to_string(),
2007            order_id: "venue-1".to_string(),
2008            trade_time: trade_time.to_string(),
2009            trade_type: crate::common::enums::CoinbaseFillTradeType::Fill,
2010            price: price.to_string(),
2011            size: size.to_string(),
2012            commission: Decimal::from_str(commission).unwrap(),
2013            product_id: Ustr::from("BTC-USD"),
2014            sequence_timestamp: "2024-01-15T10:30:00.000Z".to_string(),
2015            liquidity_indicator: CoinbaseLiquidityIndicator::Maker,
2016            size_in_quote: false,
2017            user_id: "user-1".to_string(),
2018            side: CoinbaseOrderSide::Buy,
2019            retail_portfolio_id: String::new(),
2020        }
2021    }
2022
2023    #[rstest]
2024    #[case(false, "0.005")]
2025    #[case(true, "225.61725")]
2026    fn test_parse_fill_report_base_and_quote_size(#[case] size_in_quote: bool, #[case] size: &str) {
2027        let mut fill = make_fill("1.14", "45123.45", size, "2024-01-15T10:30:00Z");
2028        fill.size_in_quote = size_in_quote;
2029        let instrument = btc_usd_instrument();
2030        let account_id = AccountId::new("COINBASE-001");
2031        let ts_init = UnixNanos::from(2);
2032
2033        let report = parse_fill_report(&fill, &instrument, account_id, ts_init).unwrap();
2034
2035        assert_eq!(report.account_id, account_id);
2036        assert_eq!(report.instrument_id, instrument.id());
2037        assert_eq!(report.venue_order_id, VenueOrderId::from("venue-1"));
2038        assert_eq!(report.trade_id, TradeId::from("trade-1"));
2039        assert_eq!(report.order_side, OrderSide::Buy);
2040        assert_eq!(report.last_qty, Quantity::from("0.00500000"));
2041        assert_eq!(report.last_px, Price::from("45123.45"));
2042        assert_eq!(report.commission, Money::from("1.14 USD"));
2043        assert_eq!(report.liquidity_side, LiquiditySide::Maker);
2044        assert_eq!(report.client_order_id, None);
2045        assert_eq!(report.venue_position_id, None);
2046        assert_eq!(
2047            report.ts_event,
2048            parse_rfc3339_timestamp(&fill.trade_time).unwrap()
2049        );
2050        assert_eq!(report.ts_init, ts_init);
2051    }
2052
2053    #[rstest]
2054    #[case("0")]
2055    #[case("-1")]
2056    fn test_parse_fill_report_rejects_nonpositive_quote_price(#[case] price: &str) {
2057        let mut fill = make_fill("1.14", price, "225.61725", "2024-01-15T10:30:00Z");
2058        fill.size_in_quote = true;
2059        let instrument = btc_usd_instrument();
2060
2061        let result = parse_fill_report(
2062            &fill,
2063            &instrument,
2064            AccountId::new("COINBASE-001"),
2065            UnixNanos::from(2),
2066        );
2067
2068        assert_eq!(
2069            result.unwrap_err().to_string(),
2070            "quote fill price must be positive"
2071        );
2072    }
2073
2074    #[rstest]
2075    fn test_parse_fill_report_rejects_out_of_range_commission() {
2076        let fill = make_fill(
2077            "9999999999999999999999999999",
2078            "45000.00",
2079            "0.001",
2080            "2024-01-15T10:30:00Z",
2081        );
2082        let instrument = btc_usd_instrument();
2083
2084        let err = parse_fill_report(
2085            &fill,
2086            &instrument,
2087            AccountId::new("COINBASE-001"),
2088            UnixNanos::from(1),
2089        )
2090        .unwrap_err();
2091
2092        let chain = format!("{err:#}");
2093        assert!(
2094            chain.contains("failed to build commission Money"),
2095            "expected failed to build commission Money in error chain, was: {chain}"
2096        );
2097    }
2098
2099    #[rstest]
2100    fn test_parse_fill_report_rejects_non_rfc3339_trade_time() {
2101        let fill = make_fill("0.50", "45000.00", "0.001", "not-a-timestamp");
2102        let instrument = btc_usd_instrument();
2103
2104        let result = parse_fill_report(
2105            &fill,
2106            &instrument,
2107            AccountId::new("COINBASE-001"),
2108            UnixNanos::from(1),
2109        );
2110        assert!(result.is_err(), "expected parse failure on bad trade_time");
2111    }
2112
2113    #[rstest]
2114    fn test_parse_account_state_skips_entry_with_out_of_range_money() {
2115        let valid = Account {
2116            uuid: "uuid-valid".to_string(),
2117            name: "USD Wallet".to_string(),
2118            currency: Ustr::from("USD"),
2119            available_balance: Balance {
2120                value: Decimal::from_str("1000.00").unwrap(),
2121                currency: Ustr::from("USD"),
2122            },
2123            default: false,
2124            active: true,
2125            created_at: String::new(),
2126            updated_at: String::new(),
2127            deleted_at: None,
2128            account_type: crate::common::enums::CoinbaseAccountType::Fiat,
2129            ready: true,
2130            hold: Some(Balance {
2131                value: Decimal::from_str("50.00").unwrap(),
2132                currency: Ustr::from("USD"),
2133            }),
2134            retail_portfolio_id: String::new(),
2135        };
2136
2137        let over_precision = Account {
2138            available_balance: Balance {
2139                value: Decimal::from_str("9999999999999999999999999999").unwrap(),
2140                currency: Ustr::from("USD"),
2141            },
2142            hold: Some(Balance {
2143                value: Decimal::ZERO,
2144                currency: Ustr::from("USD"),
2145            }),
2146            currency: Ustr::from("USD"),
2147            uuid: "uuid-over-precision".to_string(),
2148            ..valid.clone()
2149        };
2150
2151        let state = parse_account_state(
2152            &[over_precision, valid],
2153            AccountId::new("COINBASE-001"),
2154            true,
2155            UnixNanos::from(1),
2156            UnixNanos::from(2),
2157        )
2158        .unwrap();
2159
2160        // Out-of-range entry was skipped; only the valid USD row survives.
2161        assert_eq!(state.balances.len(), 1);
2162        assert_eq!(state.balances[0].currency.code, "USD");
2163        assert_eq!(
2164            state.balances[0].free.as_decimal(),
2165            Decimal::from_str("1000.00").unwrap()
2166        );
2167    }
2168
2169    #[rstest]
2170    fn test_parse_order_status_report_extracts_stop_limit_trigger_price() {
2171        let order = crate::http::models::Order {
2172            order_configuration: Some(serde_json::json!({
2173                "stop_limit_stop_limit_gtc": {
2174                    "base_size": "0.001",
2175                    "limit_price": "49500.00",
2176                    "stop_price": "49000.00",
2177                    "stop_direction": "STOP_DIRECTION_STOP_DOWN"
2178                }
2179            })),
2180            order_type: CoinbaseOrderType::StopLimit,
2181            ..make_limit_gtc_order("0.001", "0", "0", CoinbaseOrderStatus::Open)
2182        };
2183        let instrument = btc_usd_instrument();
2184
2185        let report = parse_order_status_report(
2186            &order,
2187            &instrument,
2188            AccountId::new("COINBASE-001"),
2189            UnixNanos::from(1),
2190        )
2191        .unwrap();
2192
2193        assert_eq!(report.order_type, OrderType::StopLimit);
2194        assert_eq!(report.price, Some(Price::from("49500.00")));
2195        assert_eq!(report.trigger_price, Some(Price::from("49000.00")));
2196        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2197    }
2198
2199    #[rstest]
2200    #[case::limit_gtc_post_only_true("limit_limit_gtc", true)]
2201    #[case::limit_gtc_post_only_false("limit_limit_gtc", false)]
2202    fn test_parse_order_status_report_propagates_post_only(
2203        #[case] config_key: &str,
2204        #[case] post_only: bool,
2205    ) {
2206        let config = serde_json::json!({
2207            config_key: {
2208                "base_size": "0.001",
2209                "limit_price": "50000.00",
2210                "post_only": post_only,
2211            }
2212        });
2213        let order = crate::http::models::Order {
2214            order_configuration: Some(config),
2215            ..make_limit_gtc_order("0.001", "50000.00", "0", CoinbaseOrderStatus::Open)
2216        };
2217
2218        let report = parse_order_status_report(
2219            &order,
2220            &btc_usd_instrument(),
2221            AccountId::new("COINBASE-001"),
2222            UnixNanos::from(1),
2223        )
2224        .unwrap();
2225
2226        assert_eq!(report.post_only, post_only);
2227    }
2228
2229    #[rstest]
2230    fn test_parse_order_with_unknown_configuration_does_not_fail() {
2231        // Coinbase history may return bracket, TWAP, or trigger configs that
2232        // the submit-side OrderConfiguration enum does not model. The raw
2233        // JSON field must tolerate these without failing deserialization.
2234        let json_str = r#"{
2235            "order": {
2236                "order_id": "venue-bracket-1",
2237                "product_id": "BTC-USD",
2238                "user_id": "user-1",
2239                "order_configuration": {
2240                    "trigger_bracket_gtd": {
2241                        "limit_price": "55000.00",
2242                        "stop_trigger_price": "45000.00",
2243                        "end_time": "2024-12-31T23:59:59Z"
2244                    }
2245                },
2246                "side": "BUY",
2247                "client_order_id": "client-bracket-1",
2248                "status": "OPEN",
2249                "time_in_force": "GOOD_UNTIL_DATE_TIME",
2250                "created_time": "2024-01-15T10:00:00Z",
2251                "completion_percentage": "0",
2252                "filled_size": "0",
2253                "average_filled_price": "0",
2254                "fee": "0",
2255                "number_of_fills": "0",
2256                "filled_value": "0",
2257                "pending_cancel": false,
2258                "size_in_quote": false,
2259                "total_fees": "0",
2260                "size_inclusive_of_fees": false,
2261                "total_value_after_fees": "0",
2262                "trigger_status": "INVALID_ORDER_TYPE",
2263                "order_type": "BRACKET",
2264                "reject_reason": "",
2265                "settled": false,
2266                "product_type": "SPOT",
2267                "reject_message": "",
2268                "cancel_message": "",
2269                "order_placement_source": "RETAIL_ADVANCED",
2270                "outstanding_hold_amount": "0",
2271                "is_liquidation": false,
2272                "last_fill_time": null,
2273                "leverage": "",
2274                "margin_type": "",
2275                "retail_portfolio_id": "",
2276                "originating_order_id": "",
2277                "attached_order_id": ""
2278            }
2279        }"#;
2280
2281        let response: crate::http::models::OrderResponse =
2282            serde_json::from_str(json_str).expect("unknown config must deserialize");
2283
2284        let report = parse_order_status_report(
2285            &response.order,
2286            &btc_usd_instrument(),
2287            AccountId::new("COINBASE-001"),
2288            UnixNanos::from(1),
2289        )
2290        .unwrap();
2291
2292        assert_eq!(report.venue_order_id.as_str(), "venue-bracket-1");
2293        // The bracket config has no `base_size`, so quantity falls back to
2294        // filled_qty (zero). The `limit_price` key still matches the
2295        // permissive walker and is extracted opportunistically; this is the
2296        // right tolerant default for unknown shapes.
2297        assert_eq!(report.filled_qty, Quantity::zero(8));
2298        assert_eq!(report.price, Some(Price::from("55000.00")));
2299    }
2300
2301    #[rstest]
2302    fn test_parse_order_status_report_gtd_carries_expire_time() {
2303        let order = crate::http::models::Order {
2304            order_configuration: Some(serde_json::json!({
2305                "limit_limit_gtd": {
2306                    "base_size": "0.001",
2307                    "limit_price": "50000.00",
2308                    "end_time": "2024-12-31T23:59:59Z",
2309                    "post_only": false
2310                }
2311            })),
2312            time_in_force: Some(CoinbaseTimeInForce::GoodUntilDateTime),
2313            order_type: CoinbaseOrderType::Limit,
2314            ..make_limit_gtc_order("0.001", "50000.00", "0", CoinbaseOrderStatus::Open)
2315        };
2316
2317        let report = parse_order_status_report(
2318            &order,
2319            &btc_usd_instrument(),
2320            AccountId::new("COINBASE-001"),
2321            UnixNanos::from(1),
2322        )
2323        .unwrap();
2324
2325        assert_eq!(report.time_in_force, TimeInForce::Gtd);
2326
2327        let expected_expire = parse_rfc3339_timestamp("2024-12-31T23:59:59Z").unwrap();
2328        assert_eq!(report.expire_time, Some(expected_expire));
2329    }
2330
2331    #[rstest]
2332    fn test_parse_optional_quantity_returns_none_on_overflow() {
2333        // Values exceeding QUANTITY_RAW_MAX must return None instead of panicking
2334        let result = parse_optional_quantity("99999999999999999999999999999999");
2335        assert!(result.is_none());
2336    }
2337
2338    // Confirms the "pick one whole window" invariant: when intraday has the
2339    // larger initial_margin but overnight has the larger maintenance_margin,
2340    // the emitted MarginBalance must match one of the venue windows verbatim
2341    // rather than mixing fields across windows.
2342    #[rstest]
2343    fn test_parse_cfm_margin_balances_picks_whole_window_not_per_field_max() {
2344        let summary = cfm_summary_with_windows(
2345            Some(cfm_window(
2346                CoinbaseMarginWindowType::Intraday,
2347                "800.00",
2348                "100.00",
2349            )),
2350            Some(cfm_window(
2351                CoinbaseMarginWindowType::Overnight,
2352                "500.00",
2353                "400.00",
2354            )),
2355        );
2356
2357        let margins = parse_cfm_margin_balances(&summary).unwrap();
2358        assert_eq!(margins.len(), 1);
2359        let m = &margins[0];
2360        // Intraday wins on initial (800 > 500); its maintenance (100) must
2361        // come along, not the overnight 400 that would dominate a per-field
2362        // max strategy.
2363        assert_eq!(m.initial.as_decimal(), Decimal::from_str("800.00").unwrap());
2364        assert_eq!(
2365            m.maintenance.as_decimal(),
2366            Decimal::from_str("100.00").unwrap()
2367        );
2368    }
2369
2370    #[rstest]
2371    fn test_parse_cfm_margin_balances_returns_empty_when_no_windows() {
2372        let summary = cfm_summary_with_windows(None, None);
2373        assert!(parse_cfm_margin_balances(&summary).unwrap().is_empty());
2374    }
2375
2376    #[rstest]
2377    fn test_parse_cfm_margin_balances_uses_sole_intraday_window_verbatim() {
2378        let summary = cfm_summary_with_windows(
2379            Some(cfm_window(
2380                CoinbaseMarginWindowType::Intraday,
2381                "250.00",
2382                "125.00",
2383            )),
2384            None,
2385        );
2386        let margins = parse_cfm_margin_balances(&summary).unwrap();
2387        assert_eq!(margins.len(), 1);
2388        assert_eq!(
2389            margins[0].initial.as_decimal(),
2390            Decimal::from_str("250.00").unwrap()
2391        );
2392        assert_eq!(
2393            margins[0].maintenance.as_decimal(),
2394            Decimal::from_str("125.00").unwrap()
2395        );
2396    }
2397
2398    #[rstest]
2399    fn test_parse_cfm_margin_balances_uses_sole_overnight_window_verbatim() {
2400        let summary = cfm_summary_with_windows(
2401            None,
2402            Some(cfm_window(
2403                CoinbaseMarginWindowType::Overnight,
2404                "900.00",
2405                "450.00",
2406            )),
2407        );
2408        let margins = parse_cfm_margin_balances(&summary).unwrap();
2409        assert_eq!(margins.len(), 1);
2410        assert_eq!(
2411            margins[0].initial.as_decimal(),
2412            Decimal::from_str("900.00").unwrap()
2413        );
2414        assert_eq!(
2415            margins[0].maintenance.as_decimal(),
2416            Decimal::from_str("450.00").unwrap()
2417        );
2418    }
2419
2420    // Mirrors `parse_cfm_margin_balances` selector tests for the WS variant
2421    // so a future drift between the two selectors is caught before it ships.
2422    #[rstest]
2423    fn test_parse_ws_cfm_account_state_picks_whole_window_not_per_field_max() {
2424        use nautilus_model::enums::AccountType;
2425
2426        use crate::websocket::messages::{WsFcmBalanceSummary, WsMarginWindowMeasure};
2427
2428        fn ws_window(
2429            kind: CoinbaseMarginWindowType,
2430            initial: &str,
2431            maintenance: &str,
2432        ) -> WsMarginWindowMeasure {
2433            WsMarginWindowMeasure {
2434                margin_window_type: kind,
2435                margin_level: CoinbaseMarginLevel::Base,
2436                initial_margin: Decimal::from_str(initial).unwrap(),
2437                maintenance_margin: Decimal::from_str(maintenance).unwrap(),
2438                liquidation_buffer_percentage: Decimal::ZERO,
2439                total_hold: Decimal::ZERO,
2440                futures_buying_power: Decimal::ZERO,
2441            }
2442        }
2443
2444        let summary = WsFcmBalanceSummary {
2445            futures_buying_power: Decimal::from_str("100.00").unwrap(),
2446            total_usd_balance: Decimal::from_str("500.00").unwrap(),
2447            cbi_usd_balance: Decimal::ZERO,
2448            cfm_usd_balance: Decimal::ZERO,
2449            total_open_orders_hold_amount: Decimal::from_str("25.00").unwrap(),
2450            unrealized_pnl: Decimal::ZERO,
2451            daily_realized_pnl: Decimal::ZERO,
2452            initial_margin: Decimal::ZERO,
2453            available_margin: Decimal::from_str("350.00").unwrap(),
2454            liquidation_threshold: Decimal::ZERO,
2455            liquidation_buffer_amount: Decimal::ZERO,
2456            liquidation_buffer_percentage: Decimal::ZERO,
2457            intraday_margin_window_measure: ws_window(
2458                CoinbaseMarginWindowType::Intraday,
2459                "800.00",
2460                "100.00",
2461            ),
2462            overnight_margin_window_measure: ws_window(
2463                CoinbaseMarginWindowType::Overnight,
2464                "500.00",
2465                "400.00",
2466            ),
2467        };
2468
2469        let state = parse_ws_cfm_account_state(
2470            &summary,
2471            AccountId::new("COINBASE-001"),
2472            UnixNanos::default(),
2473            UnixNanos::default(),
2474        )
2475        .unwrap();
2476
2477        assert_eq!(state.account_type, AccountType::Margin);
2478        // Balance invariant: total == venue total_usd_balance; free == available_margin.
2479        assert_eq!(
2480            state.balances[0].total.as_decimal(),
2481            Decimal::from_str("500.00").unwrap()
2482        );
2483        assert_eq!(
2484            state.balances[0].free.as_decimal(),
2485            Decimal::from_str("350.00").unwrap()
2486        );
2487        // Intraday wins on initial (800 > 500); its maintenance comes along.
2488        assert_eq!(state.margins.len(), 1);
2489        assert_eq!(
2490            state.margins[0].initial.as_decimal(),
2491            Decimal::from_str("800.00").unwrap()
2492        );
2493        assert_eq!(
2494            state.margins[0].maintenance.as_decimal(),
2495            Decimal::from_str("100.00").unwrap()
2496        );
2497    }
2498
2499    #[rstest]
2500    #[case(CoinbaseFcmPositionSide::Long, PositionSide::Long)]
2501    #[case(CoinbaseFcmPositionSide::Short, PositionSide::Short)]
2502    #[case(CoinbaseFcmPositionSide::Unspecified, PositionSide::Flat)]
2503    fn test_parse_cfm_position_side_maps_all_variants(
2504        #[case] venue_side: CoinbaseFcmPositionSide,
2505        #[case] expected: PositionSide,
2506    ) {
2507        let report = parse_cfm_position_status_report(
2508            &cfm_position(venue_side, "1", "49000.00"),
2509            &btc_perp_instrument(),
2510            AccountId::new("COINBASE-001"),
2511            UnixNanos::default(),
2512        )
2513        .unwrap();
2514        assert_eq!(report.position_side, expected);
2515    }
2516
2517    #[rstest]
2518    fn test_parse_cfm_position_drops_avg_px_when_entry_zero() {
2519        // Coinbase reports `avg_entry_price=0` on freshly-opened positions
2520        // before a fill lands; Nautilus represents "no open price" as None.
2521        let report = parse_cfm_position_status_report(
2522            &cfm_position(CoinbaseFcmPositionSide::Long, "1", "0"),
2523            &btc_perp_instrument(),
2524            AccountId::new("COINBASE-001"),
2525            UnixNanos::default(),
2526        )
2527        .unwrap();
2528        assert!(report.avg_px_open.is_none());
2529    }
2530
2531    fn cfm_amount(value: &str) -> crate::http::models::CfmAmount {
2532        crate::http::models::CfmAmount {
2533            value: Decimal::from_str(value).unwrap(),
2534            currency: Ustr::from("USD"),
2535        }
2536    }
2537
2538    fn cfm_window(
2539        kind: CoinbaseMarginWindowType,
2540        initial: &str,
2541        maintenance: &str,
2542    ) -> crate::http::models::CfmMarginWindowMeasure {
2543        crate::http::models::CfmMarginWindowMeasure {
2544            margin_window_type: kind,
2545            margin_level: CoinbaseMarginLevel::Base,
2546            initial_margin: cfm_amount(initial),
2547            maintenance_margin: cfm_amount(maintenance),
2548            liquidation_buffer_percentage: String::new(),
2549            total_hold: cfm_amount("0"),
2550            futures_buying_power: cfm_amount("0"),
2551        }
2552    }
2553
2554    fn cfm_summary_with_windows(
2555        intraday: Option<crate::http::models::CfmMarginWindowMeasure>,
2556        overnight: Option<crate::http::models::CfmMarginWindowMeasure>,
2557    ) -> CfmBalanceSummary {
2558        CfmBalanceSummary {
2559            futures_buying_power: cfm_amount("0"),
2560            total_usd_balance: cfm_amount("0"),
2561            cbi_usd_balance: cfm_amount("0"),
2562            cfm_usd_balance: cfm_amount("0"),
2563            total_open_orders_hold_amount: cfm_amount("0"),
2564            unrealized_pnl: cfm_amount("0"),
2565            daily_realized_pnl: cfm_amount("0"),
2566            initial_margin: cfm_amount("0"),
2567            available_margin: cfm_amount("0"),
2568            liquidation_threshold: cfm_amount("0"),
2569            liquidation_buffer_amount: cfm_amount("0"),
2570            liquidation_buffer_percentage: String::new(),
2571            intraday_margin_window_measure: intraday,
2572            overnight_margin_window_measure: overnight,
2573        }
2574    }
2575
2576    #[rstest]
2577    #[case::below_threshold("15", true)]
2578    #[case::at_threshold("20", false)]
2579    #[case::just_above("21", false)]
2580    #[case::well_above("100", false)]
2581    #[case::zero("0", true)]
2582    fn test_liquidation_buffer_in_warn_band(#[case] value: &str, #[case] expected_in_band: bool) {
2583        let pct = Decimal::from_str(value).unwrap();
2584        assert_eq!(liquidation_buffer_in_warn_band(pct), expected_in_band);
2585    }
2586
2587    #[rstest]
2588    #[case::below_threshold("5")]
2589    #[case::above_threshold("100")]
2590    #[case::empty_string_silently_skips_warn("")]
2591    fn test_parse_cfm_account_state_buffer_threshold_paths(#[case] buffer_pct: &str) {
2592        use nautilus_model::enums::AccountType;
2593
2594        let mut summary = cfm_summary_with_windows(
2595            Some(cfm_window(
2596                CoinbaseMarginWindowType::Intraday,
2597                "100.00",
2598                "50.00",
2599            )),
2600            None,
2601        );
2602        summary.total_usd_balance = cfm_amount("100.00");
2603        summary.available_margin = cfm_amount("50.00");
2604        summary.liquidation_buffer_percentage = buffer_pct.to_string();
2605
2606        let state = parse_cfm_account_state(
2607            &summary,
2608            AccountId::new("COINBASE-001"),
2609            true,
2610            UnixNanos::default(),
2611            UnixNanos::default(),
2612        )
2613        .unwrap();
2614
2615        assert_eq!(state.account_type, AccountType::Margin);
2616        assert!(!state.balances.is_empty());
2617    }
2618
2619    #[rstest]
2620    #[case::below_threshold("5")]
2621    #[case::above_threshold("100")]
2622    fn test_parse_ws_cfm_account_state_buffer_threshold_paths(#[case] buffer_pct: &str) {
2623        use nautilus_model::enums::AccountType;
2624
2625        use crate::websocket::messages::{WsFcmBalanceSummary, WsMarginWindowMeasure};
2626
2627        fn ws_window(kind: CoinbaseMarginWindowType) -> WsMarginWindowMeasure {
2628            WsMarginWindowMeasure {
2629                margin_window_type: kind,
2630                margin_level: CoinbaseMarginLevel::Base,
2631                initial_margin: Decimal::from_str("100.00").unwrap(),
2632                maintenance_margin: Decimal::from_str("50.00").unwrap(),
2633                liquidation_buffer_percentage: Decimal::ZERO,
2634                total_hold: Decimal::ZERO,
2635                futures_buying_power: Decimal::ZERO,
2636            }
2637        }
2638
2639        let summary = WsFcmBalanceSummary {
2640            futures_buying_power: Decimal::ZERO,
2641            total_usd_balance: Decimal::from_str("100.00").unwrap(),
2642            cbi_usd_balance: Decimal::ZERO,
2643            cfm_usd_balance: Decimal::ZERO,
2644            total_open_orders_hold_amount: Decimal::ZERO,
2645            unrealized_pnl: Decimal::ZERO,
2646            daily_realized_pnl: Decimal::ZERO,
2647            initial_margin: Decimal::ZERO,
2648            available_margin: Decimal::from_str("50.00").unwrap(),
2649            liquidation_threshold: Decimal::ZERO,
2650            liquidation_buffer_amount: Decimal::ZERO,
2651            liquidation_buffer_percentage: Decimal::from_str(buffer_pct).unwrap(),
2652            intraday_margin_window_measure: ws_window(CoinbaseMarginWindowType::Intraday),
2653            overnight_margin_window_measure: ws_window(CoinbaseMarginWindowType::Overnight),
2654        };
2655
2656        let state = parse_ws_cfm_account_state(
2657            &summary,
2658            AccountId::new("COINBASE-001"),
2659            UnixNanos::default(),
2660            UnixNanos::default(),
2661        )
2662        .unwrap();
2663
2664        assert_eq!(state.account_type, AccountType::Margin);
2665        assert!(!state.balances.is_empty());
2666    }
2667
2668    fn cfm_position(
2669        side: CoinbaseFcmPositionSide,
2670        contracts: &str,
2671        avg_entry: &str,
2672    ) -> CfmPosition {
2673        CfmPosition {
2674            product_id: Ustr::from("BIP-20DEC30-CDE"),
2675            expiration_time: String::new(),
2676            side,
2677            number_of_contracts: Decimal::from_str(contracts).unwrap(),
2678            current_price: cfm_amount("50000.00"),
2679            avg_entry_price: cfm_amount(avg_entry),
2680            unrealized_pnl: cfm_amount("0"),
2681            daily_realized_pnl: cfm_amount("0"),
2682            total_fees: None,
2683            contract_size: "0.01".to_string(),
2684            entry_vwap: None,
2685            liquidation_price: None,
2686            leverage: String::new(),
2687            im_contribution: None,
2688            mm_contribution: None,
2689            position_notional: None,
2690        }
2691    }
2692
2693    fn btc_perp_instrument() -> InstrumentAny {
2694        let json = load_test_fixture("http_products_future.json");
2695        let response: crate::http::models::ProductsResponse = serde_json::from_str(&json).unwrap();
2696        parse_instrument(&response.products[0], UnixNanos::default()).unwrap()
2697    }
2698}