Skip to main content

nautilus_lighter/websocket/
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//! Parsers from Lighter streaming payloads to Nautilus domain types.
17
18use anyhow::Context;
19use nautilus_core::{UUID4, UnixNanos};
20use nautilus_model::{
21    data::{
22        Bar, BarType, BookOrder, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate,
23        OrderBookDelta, OrderBookDeltas, OrderBookDepth, QuoteTick, TradeTick, depth::DEPTH10_LEN,
24    },
25    enums::{
26        AccountType, AggregationSource, BookAction, LiquiditySide, OrderSide, OrderStatus,
27        OrderType, PositionSide, RecordFlag, TimeInForce, TriggerType,
28    },
29    events::{
30        AccountState, OrderAccepted, OrderCanceled, OrderExpired, OrderFilled, OrderRejected,
31        OrderTriggered, OrderUpdated,
32    },
33    identifiers::{AccountId, ClientOrderId, InstrumentId, TradeId, TraderId, VenueOrderId},
34    instruments::{Instrument, InstrumentAny},
35    orders::{LIMIT_ORDER_TYPES, STOP_ORDER_TYPES, TRIGGERABLE_ORDER_TYPES},
36    reports::{FillReport, OrderStatusReport, PositionStatusReport},
37    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
38};
39use rust_decimal::Decimal;
40use ustr::Ustr;
41
42use crate::{
43    common::{
44        enums::{
45            LighterCandleResolution, LighterOrderKind, LighterOrderSide, LighterOrderStatus,
46            LighterOrderTimeInForce, LighterTriggerStatus, order_side_from_is_ask,
47        },
48        parse::{
49            funding_rate_from_percent, parse_millis_to_nanos, price_from_decimal,
50            quantity_from_decimal,
51        },
52    },
53    http::{
54        models::{LighterOrder, LighterPriceLevel, LighterTrade},
55        parse::parse_trade_tick,
56    },
57    websocket::{
58        dispatch::{OrderIdentity, OrderShapeSnapshot},
59        messages::{
60            LighterAsset, LighterMarketStats, LighterPosition, LighterSpotMarketStats,
61            LighterTicker, LighterUserStats, LighterWsCandle, LighterWsOrderBook,
62        },
63    },
64};
65
66// Trade fee ticks encode rates: 100 ticks = 1 basis point
67const FEE_DECIMALS: u32 = 6;
68
69#[derive(Debug, thiserror::Error)]
70#[error("failed to construct Lighter commission: {detail}")]
71pub(crate) struct LighterCommissionError {
72    detail: String,
73}
74
75impl LighterCommissionError {
76    pub(crate) fn new(detail: impl Into<String>) -> Self {
77        Self {
78            detail: detail.into(),
79        }
80    }
81}
82
83/// Parses a Lighter trade stream item into a Nautilus [`TradeTick`].
84///
85/// # Errors
86///
87/// Returns an error if the trade cannot be converted into a Nautilus tick.
88pub fn parse_ws_trade_tick(
89    trade: &LighterTrade,
90    instrument: &InstrumentAny,
91    ts_init: UnixNanos,
92) -> anyhow::Result<TradeTick> {
93    parse_trade_tick(trade, instrument, ts_init)
94}
95
96/// Parses a Lighter order book update into Nautilus deltas.
97///
98/// `is_snapshot` must be supplied by the caller because Lighter sends
99/// `subscribed/order_book` for the full book on subscription and
100/// `update/order_book` for incremental level changes afterwards.
101///
102/// # Errors
103///
104/// Returns an error if any price or size cannot be converted.
105pub fn parse_ws_order_book_deltas(
106    book: &LighterWsOrderBook,
107    instrument: &InstrumentAny,
108    timestamp_ms: u64,
109    is_snapshot: bool,
110    ts_init: UnixNanos,
111) -> anyhow::Result<OrderBookDeltas> {
112    let ts_event = parse_millis_to_nanos(timestamp_ms)?;
113    let sequence = u64::try_from(book.nonce).context("negative Lighter book nonce")?;
114    let total_levels = book.bids.len() + book.asks.len();
115
116    anyhow::ensure!(
117        is_snapshot || total_levels > 0,
118        "empty Lighter WebSocket order book update",
119    );
120
121    let mut deltas = Vec::with_capacity(total_levels + usize::from(is_snapshot));
122
123    if is_snapshot {
124        let mut clear = OrderBookDelta::clear(instrument.id(), sequence, ts_event, ts_init);
125        if total_levels == 0 {
126            clear.flags |= RecordFlag::F_LAST as u8;
127        }
128        deltas.push(clear);
129    }
130
131    let mut processed = 0_usize;
132
133    for bid in &book.bids {
134        processed += 1;
135        deltas.push(parse_book_level_delta(
136            bid,
137            instrument,
138            OrderSide::Buy,
139            sequence,
140            ts_event,
141            ts_init,
142            book_flags(is_snapshot, processed, total_levels),
143        )?);
144    }
145
146    for ask in &book.asks {
147        processed += 1;
148        deltas.push(parse_book_level_delta(
149            ask,
150            instrument,
151            OrderSide::Sell,
152            sequence,
153            ts_event,
154            ts_init,
155            book_flags(is_snapshot, processed, total_levels),
156        )?);
157    }
158
159    OrderBookDeltas::new_checked(instrument.id(), deltas)
160        .context("failed to construct OrderBookDeltas from Lighter WebSocket book")
161}
162
163/// Parses a full Lighter order book payload into a Nautilus [`OrderBookDepth`].
164///
165/// Call this only for snapshot or depth payloads that contain the full visible
166/// book. Incremental updates should be parsed as deltas.
167///
168/// # Errors
169///
170/// Returns an error if any price or size cannot be converted.
171pub fn parse_ws_order_book_depth(
172    book: &LighterWsOrderBook,
173    instrument: &InstrumentAny,
174    timestamp_ms: u64,
175    ts_init: UnixNanos,
176) -> anyhow::Result<OrderBookDepth> {
177    let ts_event = parse_millis_to_nanos(timestamp_ms)?;
178    let sequence = u64::try_from(book.nonce).context("negative Lighter book nonce")?;
179    let mut bids = [BookOrder::default(); DEPTH10_LEN];
180    let mut asks = [BookOrder::default(); DEPTH10_LEN];
181    let mut bid_counts = [0_u32; DEPTH10_LEN];
182    let mut ask_counts = [0_u32; DEPTH10_LEN];
183
184    for (idx, level) in book.bids.iter().take(DEPTH10_LEN).enumerate() {
185        bids[idx] = BookOrder::new(
186            OrderSide::Buy,
187            price_from_decimal(level.price, instrument.price_precision())?,
188            quantity_from_decimal(level.size, instrument.size_precision())?,
189            0,
190        );
191        bid_counts[idx] = 1;
192    }
193
194    for bid in bids.iter_mut().skip(book.bids.len().min(DEPTH10_LEN)) {
195        *bid = BookOrder::new(
196            OrderSide::Buy,
197            Price::zero(instrument.price_precision()),
198            Quantity::zero(instrument.size_precision()),
199            0,
200        );
201    }
202
203    for (idx, level) in book.asks.iter().take(DEPTH10_LEN).enumerate() {
204        asks[idx] = BookOrder::new(
205            OrderSide::Sell,
206            price_from_decimal(level.price, instrument.price_precision())?,
207            quantity_from_decimal(level.size, instrument.size_precision())?,
208            0,
209        );
210        ask_counts[idx] = 1;
211    }
212
213    for ask in asks.iter_mut().skip(book.asks.len().min(DEPTH10_LEN)) {
214        *ask = BookOrder::new(
215            OrderSide::Sell,
216            Price::zero(instrument.price_precision()),
217            Quantity::zero(instrument.size_precision()),
218            0,
219        );
220    }
221
222    Ok(OrderBookDepth::new(
223        instrument.id(),
224        bids,
225        asks,
226        bid_counts,
227        ask_counts,
228        RecordFlag::F_SNAPSHOT as u8,
229        sequence,
230        ts_event,
231        ts_init,
232    ))
233}
234
235/// Parses a Lighter ticker stream payload into a Nautilus [`QuoteTick`].
236///
237/// Returns `Ok(None)` if either side carries an empty price/size string,
238/// which Lighter emits when one book side is currently uninhabited (no
239/// resting orders). A one-sided book cannot be expressed as a [`QuoteTick`],
240/// so the frame is skipped rather than rejected.
241///
242/// # Errors
243///
244/// Returns an error if a non-empty bid or ask field cannot be converted.
245pub fn parse_ws_quote_tick(
246    ticker: &LighterTicker,
247    instrument: &InstrumentAny,
248    timestamp_ms: u64,
249    ts_init: UnixNanos,
250) -> anyhow::Result<Option<QuoteTick>> {
251    // Lighter sends zero (or empty string, mapped to zero by the wire deserializer)
252    // for a side that currently has no resting orders; a one-sided book cannot be
253    // expressed as a `QuoteTick`, so the frame is skipped rather than rejected.
254    if ticker.b.price.is_zero()
255        || ticker.b.size.is_zero()
256        || ticker.a.price.is_zero()
257        || ticker.a.size.is_zero()
258    {
259        return Ok(None);
260    }
261
262    let bid_price = price_from_decimal(ticker.b.price, instrument.price_precision())?;
263    let ask_price = price_from_decimal(ticker.a.price, instrument.price_precision())?;
264    let bid_size = quantity_from_decimal(ticker.b.size, instrument.size_precision())?;
265    let ask_size = quantity_from_decimal(ticker.a.size, instrument.size_precision())?;
266    let ts_event = parse_millis_to_nanos(timestamp_ms)?;
267
268    QuoteTick::new_checked(
269        instrument.id(),
270        bid_price,
271        ask_price,
272        bid_size,
273        ask_size,
274        ts_event,
275        ts_init,
276    )
277    .map(Some)
278    .context("failed to construct QuoteTick from Lighter ticker")
279}
280
281/// Parses a Lighter perpetual market-stat update into a mark price update.
282///
283/// # Errors
284///
285/// Returns an error if the mark price or timestamp cannot be converted.
286pub fn parse_ws_mark_price_update(
287    stats: &LighterMarketStats,
288    instrument: &InstrumentAny,
289    timestamp_ms: u64,
290    ts_init: UnixNanos,
291) -> anyhow::Result<MarkPriceUpdate> {
292    build_price_update(
293        instrument,
294        stats.mark_price,
295        timestamp_ms,
296        ts_init,
297        MarkPriceUpdate::new,
298    )
299}
300
301/// Parses a Lighter perpetual market-stat update into an index price update.
302///
303/// # Errors
304///
305/// Returns an error if the index price or timestamp cannot be converted.
306pub fn parse_ws_index_price_update(
307    stats: &LighterMarketStats,
308    instrument: &InstrumentAny,
309    timestamp_ms: u64,
310    ts_init: UnixNanos,
311) -> anyhow::Result<IndexPriceUpdate> {
312    build_price_update(
313        instrument,
314        stats.index_price,
315        timestamp_ms,
316        ts_init,
317        IndexPriceUpdate::new,
318    )
319}
320
321/// Parses a Lighter spot market-stat update into an index price update.
322///
323/// # Errors
324///
325/// Returns an error if the index price or timestamp cannot be converted.
326pub fn parse_ws_spot_index_price_update(
327    stats: &LighterSpotMarketStats,
328    instrument: &InstrumentAny,
329    timestamp_ms: u64,
330    ts_init: UnixNanos,
331) -> anyhow::Result<IndexPriceUpdate> {
332    build_price_update(
333        instrument,
334        stats.index_price,
335        timestamp_ms,
336        ts_init,
337        IndexPriceUpdate::new,
338    )
339}
340
341fn build_price_update<T>(
342    instrument: &InstrumentAny,
343    price: Decimal,
344    timestamp_ms: u64,
345    ts_init: UnixNanos,
346    constructor: impl FnOnce(InstrumentId, Price, UnixNanos, UnixNanos) -> T,
347) -> anyhow::Result<T> {
348    let price = price_from_decimal(price, instrument.price_precision())?;
349    let ts_event = parse_millis_to_nanos(timestamp_ms)?;
350    Ok(constructor(instrument.id(), price, ts_event, ts_init))
351}
352
353/// Parses a Lighter perpetual market-stat update into a funding-rate update.
354///
355/// Lighter exposes `current_funding_rate` as the estimate for the upcoming
356/// payment. The `funding_rate` field is the last completed payment, so it is
357/// not used for the streaming Nautilus update. The accompanying
358/// `funding_timestamp` identifies that completed payment; market stats do not
359/// provide the next settlement time.
360///
361/// # Errors
362///
363/// Returns an error if the event timestamp cannot be converted.
364pub fn parse_ws_funding_rate_update(
365    stats: &LighterMarketStats,
366    instrument: &InstrumentAny,
367    timestamp_ms: u64,
368    ts_init: UnixNanos,
369) -> anyhow::Result<FundingRateUpdate> {
370    let rate = funding_rate_from_percent(stats.current_funding_rate);
371    let ts_event = parse_millis_to_nanos(timestamp_ms)?;
372    Ok(FundingRateUpdate::new(
373        instrument.id(),
374        rate,
375        Some(60),
376        None,
377        ts_event,
378        ts_init,
379    ))
380}
381
382/// Parses a Lighter WebSocket candle into a Nautilus [`Bar`] with `ts_event` set to the bar open.
383///
384/// # Errors
385///
386/// Returns an error if the OHLCV decimals overflow the instrument's precision, or if the
387/// timestamp cannot be converted.
388pub fn parse_ws_bar(
389    instrument: &InstrumentAny,
390    candle: &LighterWsCandle,
391    resolution: LighterCandleResolution,
392    ts_init: UnixNanos,
393) -> anyhow::Result<Bar> {
394    let price_precision = instrument.price_precision();
395    let size_precision = instrument.size_precision();
396
397    let open = Price::from_decimal_dp(candle.o, price_precision)
398        .map_err(|e| anyhow::anyhow!("invalid candle open: {e}"))?;
399    let high = Price::from_decimal_dp(candle.h, price_precision)
400        .map_err(|e| anyhow::anyhow!("invalid candle high: {e}"))?;
401    let low = Price::from_decimal_dp(candle.l, price_precision)
402        .map_err(|e| anyhow::anyhow!("invalid candle low: {e}"))?;
403    let close = Price::from_decimal_dp(candle.c, price_precision)
404        .map_err(|e| anyhow::anyhow!("invalid candle close: {e}"))?;
405    let volume = Quantity::from_decimal_dp(candle.v, size_precision)
406        .map_err(|e| anyhow::anyhow!("invalid candle volume: {e}"))?;
407
408    let t_ms = u64::try_from(candle.t)
409        .map_err(|_| anyhow::anyhow!("negative candle timestamp: {}", candle.t))?;
410    let ts_event = parse_millis_to_nanos(t_ms)?;
411
412    let bar_type = BarType::new(
413        instrument.id(),
414        resolution.to_bar_spec(),
415        AggregationSource::External,
416    );
417
418    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
419        .map_err(|e| anyhow::anyhow!("invalid candle bar: {e}"))
420}
421
422fn parse_book_level_delta(
423    level: &LighterPriceLevel,
424    instrument: &InstrumentAny,
425    side: OrderSide,
426    sequence: u64,
427    ts_event: UnixNanos,
428    ts_init: UnixNanos,
429    flags: u8,
430) -> anyhow::Result<OrderBookDelta> {
431    let price = price_from_decimal(level.price, instrument.price_precision())?;
432    let size = quantity_from_decimal(level.size, instrument.size_precision())?;
433    let action = if flags & RecordFlag::F_SNAPSHOT as u8 != 0 {
434        BookAction::Add
435    } else if size.is_zero() {
436        BookAction::Delete
437    } else {
438        BookAction::Update
439    };
440    let order = BookOrder::new(side, price, size, 0);
441
442    OrderBookDelta::new_checked(
443        instrument.id(),
444        action,
445        order,
446        flags,
447        sequence,
448        ts_event,
449        ts_init,
450    )
451    .context("failed to construct Lighter WebSocket book delta")
452}
453
454fn book_flags(is_snapshot: bool, processed: usize, total_levels: usize) -> u8 {
455    let mut flags = if is_snapshot {
456        RecordFlag::F_SNAPSHOT as u8
457    } else {
458        0
459    };
460
461    if processed == total_levels {
462        flags |= RecordFlag::F_LAST as u8;
463    }
464
465    flags
466}
467
468/// Parses a Lighter account-stream order payload into an [`OrderStatusReport`].
469///
470/// The venue exposes partial fills implicitly: the order remains in `Open`
471/// status with `filled_base_amount > 0`. The mapping promotes such an order
472/// to [`OrderStatus::PartiallyFilled`] so downstream consumers do not need to
473/// re-derive it.
474/// Working and filled order quantities exclude amounts netted by self-trade prevention.
475///
476/// # Errors
477///
478/// Returns an error if any quantity, price, or timestamp field cannot be
479/// converted, or if the venue order kind has no Nautilus equivalent.
480pub fn parse_ws_order_status_report(
481    order: &LighterOrder,
482    instrument: &InstrumentAny,
483    account_id: AccountId,
484    ts_init: UnixNanos,
485) -> anyhow::Result<OrderStatusReport> {
486    let instrument_id = instrument.id();
487    let venue_order_id = VenueOrderId::new(order.order_id.as_str());
488    let order_side = order
489        .side
490        .map_or_else(|| order_side_from_is_ask(order.is_ask), nautilus_order_side);
491    let mut order_type = nautilus_order_type(order.order_type)?;
492    if is_order_triggered(order)
493        && order.trigger_price.is_zero()
494        && matches!(order_type, OrderType::StopLimit | OrderType::LimitIfTouched)
495    {
496        order_type = OrderType::Limit;
497    }
498
499    let (time_in_force, expire_time) =
500        nautilus_time_in_force(order.time_in_force, order.order_expiry);
501    let post_only = order.time_in_force == LighterOrderTimeInForce::PostOnly;
502
503    let quantity = lighter_order_quantity(order, instrument.size_precision())?;
504    let filled_qty = quantity_from_decimal(order.filled_base_amount, instrument.size_precision())?;
505    let mut order_status = nautilus_order_status(order.status, &filled_qty);
506    if order_status == OrderStatus::Accepted
507        && is_order_triggered(order)
508        && TRIGGERABLE_ORDER_TYPES.contains(&order_type)
509    {
510        order_status = OrderStatus::Triggered;
511    }
512
513    let cancel_reason = order.status.as_cancel_reason();
514
515    let ts_accepted = parse_optional_order_timestamp(order.created_at)?;
516    let ts_last = parse_optional_order_timestamp(order.updated_at)?;
517
518    let mut report = OrderStatusReport::new(
519        account_id,
520        instrument_id,
521        None, // client_order_id set below when present
522        venue_order_id,
523        order_side.into(),
524        order_type,
525        time_in_force,
526        order_status,
527        quantity,
528        filled_qty,
529        ts_accepted,
530        ts_last,
531        ts_init,
532        Some(UUID4::new()),
533    )
534    .with_post_only(post_only)
535    .with_reduce_only(order.reduce_only);
536
537    if !order.client_order_id.is_empty() && order.client_order_id != "0" {
538        report = report.with_client_order_id(ClientOrderId::new(order.client_order_id.as_str()));
539    }
540
541    if let Some(price) = parse_optional_price(order.price, instrument.price_precision())? {
542        report = report.with_price(price);
543    }
544
545    if let Some(trigger_price) =
546        parse_optional_price(order.trigger_price, instrument.price_precision())?
547    {
548        report = report.with_trigger_price(trigger_price);
549    }
550
551    if order_type_requires_trigger_type(order_type) {
552        report = report.with_trigger_type(TriggerType::Default);
553    }
554
555    if let Some(expire) = expire_time {
556        report = report.with_expire_time(expire);
557    }
558
559    if let Some(reason) = cancel_reason {
560        report = report.with_cancel_reason(reason.to_string());
561    }
562
563    // Lighter publishes `parent_order_id` in the venue namespace (matching
564    // `order_id`), not the client namespace. Nautilus
565    // `OrderStatusReport::parent_order_id` expects a `ClientOrderId`, so
566    // populating it from the venue id would mislabel namespaces. Contingency
567    // linking for OTO/OCO groups must be applied at the execution-client
568    // layer, where the venue-to-client id mapping is tracked.
569
570    Ok(report)
571}
572
573pub(crate) fn is_order_triggered(order: &LighterOrder) -> bool {
574    order.status == LighterOrderStatus::Open
575        && (order.trigger_status == LighterTriggerStatus::Ready
576            || (order.trigger_status == LighterTriggerStatus::Na
577                && matches!(
578                    order.order_type,
579                    LighterOrderKind::StopLoss
580                        | LighterOrderKind::StopLossLimit
581                        | LighterOrderKind::TakeProfit
582                        | LighterOrderKind::TakeProfitLimit
583                )))
584}
585
586fn order_type_requires_trigger_type(order_type: OrderType) -> bool {
587    matches!(
588        order_type,
589        OrderType::StopMarket
590            | OrderType::StopLimit
591            | OrderType::MarketIfTouched
592            | OrderType::LimitIfTouched
593            | OrderType::TrailingStopMarket
594            | OrderType::TrailingStopLimit
595    )
596}
597
598/// Parses a Lighter account-trade payload into a [`FillReport`] when the trade
599/// involves the supplied account.
600///
601/// Returns `Ok(None)` if `account_index` is neither the bid nor ask account on
602/// the trade. The handler routes account-stream trades through this parser, so
603/// crossed pairs the user is not part of (e.g. when sharing a market with
604/// other participants) are skipped silently rather than misattributed.
605///
606/// # Errors
607///
608/// Returns an error if:
609/// - The trade ID, price, size, or timestamp cannot be converted.
610/// - The commission calculation overflows or cannot be represented as [`Money`].
611pub fn parse_ws_fill_report(
612    trade: &LighterTrade,
613    account_index: i64,
614    instrument: &InstrumentAny,
615    account_id: AccountId,
616    ts_init: UnixNanos,
617) -> anyhow::Result<Option<FillReport>> {
618    let user_is_bidder = trade.bid_account_id == account_index;
619    let user_is_asker = trade.ask_account_id == account_index;
620    if !user_is_bidder && !user_is_asker {
621        return Ok(None);
622    }
623
624    let order_side = if user_is_bidder {
625        OrderSide::Buy
626    } else {
627        OrderSide::Sell
628    };
629
630    // `is_maker_ask` says which book side rested as the maker; combined with
631    // which side the user filled, that determines whether the user provided
632    // or removed liquidity.
633    let liquidity_side = if user_is_asker == trade.is_maker_ask {
634        LiquiditySide::Maker
635    } else {
636        LiquiditySide::Taker
637    };
638
639    let venue_order_id = if user_is_bidder {
640        venue_order_id_from(trade.bid_id_str.as_deref(), trade.bid_id)
641    } else {
642        venue_order_id_from(trade.ask_id_str.as_deref(), trade.ask_id)
643    };
644
645    let trade_id = parse_lighter_trade_id(trade)?;
646
647    let last_qty = quantity_from_decimal(trade.size, instrument.size_precision())?;
648    let last_px = price_from_decimal(trade.price, instrument.price_precision())?;
649
650    let fee_value = if liquidity_side == LiquiditySide::Maker {
651        trade.maker_fee
652    } else {
653        trade.taker_fee
654    };
655
656    let commission = lighter_fee_to_commission(fee_value, trade, instrument.quote_currency())?;
657    let client_order_id = if user_is_bidder {
658        client_order_id_from(trade.bid_client_id_str.as_deref(), trade.bid_client_id)
659    } else {
660        client_order_id_from(trade.ask_client_id_str.as_deref(), trade.ask_client_id)
661    };
662
663    let timestamp_ms =
664        u64::try_from(trade.timestamp).context("negative Lighter trade timestamp")?;
665    let ts_event = parse_millis_to_nanos(timestamp_ms)?;
666
667    Ok(Some(FillReport::new(
668        account_id,
669        instrument.id(),
670        venue_order_id,
671        trade_id,
672        order_side,
673        last_qty,
674        last_px,
675        commission,
676        liquidity_side,
677        client_order_id,
678        None, // venue_position_id: Lighter perps run NETTING (one position per market)
679        ts_event,
680        ts_init,
681        Some(UUID4::new()),
682    )))
683}
684
685pub(crate) fn parse_lighter_trade_id(trade: &LighterTrade) -> anyhow::Result<TradeId> {
686    match trade.trade_id_str.as_deref() {
687        Some(s) => TradeId::new_checked(s),
688        None => TradeId::new_checked(trade.trade_id.to_string()),
689    }
690    .context("invalid Lighter trade identifier")
691}
692
693/// Outcome of [`parse_lighter_order_event`] for tracked orders.
694///
695/// Parses raw order events into typed intermediate events (see
696/// the execution
697/// consumption loop maps these into [`nautilus_model::events::OrderEventAny`]
698/// variants for tracked orders; untracked orders flow through the
699/// `OrderStatusReport` path instead.
700#[derive(Debug, Clone)]
701#[allow(clippy::large_enum_variant)]
702pub(crate) enum ParsedOrderEvent {
703    Accepted(OrderAccepted),
704    Canceled(OrderCanceled),
705    Expired(OrderExpired),
706    Triggered(OrderTriggered),
707    Rejected(OrderRejected),
708    Updated(OrderUpdated),
709    UpdatedThenTriggered {
710        updated: OrderUpdated,
711        triggered: OrderTriggered,
712    },
713}
714
715/// Inputs that the consumption-loop dispatcher hands to
716/// [`parse_lighter_order_event`] for an acknowledged `Pending` or `Open`
717/// frame. The dispatcher precomputes the accept/trigger gates and the
718/// modify-detection diff against
719/// [`crate::websocket::dispatch::WsDispatchState::order_snapshots`]. The parser
720/// uses the flags to pick the correct typed event without dispatch state
721/// lookups.
722///
723/// `shape_changed` compares quantity, price, and trigger price with the stored
724/// snapshot and is meaningful only after `OrderAccepted` has been emitted.
725#[derive(Debug, Clone, Copy)]
726pub(crate) struct OpenFrameContext {
727    pub(crate) accepted_already_emitted: bool,
728    pub(crate) triggered_already_emitted: bool,
729    pub(crate) shape_changed: bool,
730}
731
732/// Extract the mutable shape (qty / price / trigger) from a Lighter order
733/// payload so the dispatcher can diff against the stored snapshot. Returns
734/// the values in the instrument's precision so equality is well-defined.
735///
736/// # Errors
737///
738/// Returns an error if any price or quantity field cannot be converted at
739/// the instrument's precision.
740pub(crate) fn lighter_order_shape(
741    order: &LighterOrder,
742    instrument: &InstrumentAny,
743    order_type: OrderType,
744) -> anyhow::Result<OrderShapeSnapshot> {
745    let quantity = lighter_order_quantity(order, instrument.size_precision())?;
746    let price = if LIMIT_ORDER_TYPES.contains(&order_type) {
747        parse_optional_price(order.price, instrument.price_precision())?
748    } else {
749        None
750    };
751    let trigger_price = if STOP_ORDER_TYPES.contains(&order_type) {
752        parse_optional_price(order.trigger_price, instrument.price_precision())?
753    } else {
754        None
755    };
756    Ok(OrderShapeSnapshot {
757        quantity,
758        price,
759        trigger_price,
760    })
761}
762
763fn lighter_order_quantity(order: &LighterOrder, precision: u8) -> anyhow::Result<Quantity> {
764    let mut amount = order.initial_base_amount;
765
766    // Reduce lowers remaining without a fill; cancellations also zero remaining
767    if !order.status.is_terminal() || order.status == LighterOrderStatus::Filled {
768        let effective = order
769            .filled_base_amount
770            .checked_add(order.remaining_base_amount)
771            .context("Lighter order quantity overflow")?;
772
773        if effective > Decimal::ZERO && effective < amount {
774            amount = effective;
775        }
776    }
777
778    quantity_from_decimal(amount, precision)
779}
780
781/// Build a typed order event from a Lighter `account_orders` payload, using
782/// the identity context captured at submit time.
783///
784/// The caller (the execution consumption loop) decides between this path and
785/// the [`OrderStatusReport`] fallback based on whether the cloid is in
786/// `WsDispatchState::order_identities`. Returns `None` for `InProgress` and
787/// unchanged `Filled` frames. A changed `Filled` frame produces `Updated`;
788/// actual fills flow through the trade stream via [`parse_lighter_order_filled`].
789/// Lighter `Pending` means the venue has
790/// acknowledged the order, so it follows the accepted/update path without
791/// the `Open`-only trigger transition.
792///
793/// The `Open` branch decision matrix (in order):
794///
795/// - Already accepted with a fresh trigger and a changed shape
796///   -> `Updated`, then `Triggered`.
797/// - An open conditional limit with `Ready` or `Na` trigger status and no prior trigger -> `Triggered`.
798/// - Not yet accepted -> `Accepted` (the dispatcher seeds the shape
799///   snapshot so subsequent diffs are meaningful).
800/// - Already accepted and the order shape changed (qty / price / trigger)
801///   -> `Updated` (the dispatcher refreshes the shape snapshot).
802/// - Already accepted with no shape change -> `None` (snapshot replay).
803///
804/// # Errors
805///
806/// Returns an error if any price, quantity, or timestamp field cannot be
807/// converted.
808#[expect(
809    clippy::too_many_arguments,
810    reason = "identity and the precomputed open-frame context are independent inputs threaded by the caller"
811)]
812pub(crate) fn parse_lighter_order_event(
813    order: &LighterOrder,
814    instrument: &InstrumentAny,
815    identity: &OrderIdentity,
816    cloid: ClientOrderId,
817    account_id: AccountId,
818    trader_id: TraderId,
819    open_ctx: OpenFrameContext,
820    ts_init: UnixNanos,
821) -> anyhow::Result<Option<ParsedOrderEvent>> {
822    let venue_order_id = VenueOrderId::new(order.order_id.as_str());
823    let ts_event = parse_optional_order_timestamp(order.updated_at)?;
824    let ts_accept = parse_optional_order_timestamp(order.created_at)?;
825
826    match order.status {
827        LighterOrderStatus::InProgress => Ok(None),
828        LighterOrderStatus::Pending | LighterOrderStatus::Open => {
829            let fresh_trigger = is_order_triggered(order)
830                && TRIGGERABLE_ORDER_TYPES.contains(&identity.order_type)
831                && !open_ctx.triggered_already_emitted;
832
833            if fresh_trigger && open_ctx.accepted_already_emitted && open_ctx.shape_changed {
834                let updated = parse_lighter_order_updated(
835                    order, instrument, identity, cloid, account_id, trader_id, ts_init,
836                )?;
837
838                let triggered = OrderTriggered::new(
839                    trader_id,
840                    identity.strategy_id,
841                    identity.instrument_id,
842                    cloid,
843                    UUID4::new(),
844                    ts_event,
845                    ts_init,
846                    false,
847                    Some(venue_order_id),
848                    Some(account_id),
849                );
850                Ok(Some(ParsedOrderEvent::UpdatedThenTriggered {
851                    updated,
852                    triggered,
853                }))
854            } else if fresh_trigger {
855                let triggered = OrderTriggered::new(
856                    trader_id,
857                    identity.strategy_id,
858                    identity.instrument_id,
859                    cloid,
860                    UUID4::new(),
861                    ts_event,
862                    ts_init,
863                    false,
864                    Some(venue_order_id),
865                    Some(account_id),
866                );
867                Ok(Some(ParsedOrderEvent::Triggered(triggered)))
868            } else if !open_ctx.accepted_already_emitted {
869                let accepted = OrderAccepted::new(
870                    trader_id,
871                    identity.strategy_id,
872                    identity.instrument_id,
873                    cloid,
874                    venue_order_id,
875                    account_id,
876                    UUID4::new(),
877                    ts_accept,
878                    ts_init,
879                    false,
880                );
881                Ok(Some(ParsedOrderEvent::Accepted(accepted)))
882            } else if open_ctx.shape_changed {
883                let updated = parse_lighter_order_updated(
884                    order, instrument, identity, cloid, account_id, trader_id, ts_init,
885                )?;
886                Ok(Some(ParsedOrderEvent::Updated(updated)))
887            } else {
888                Ok(None)
889            }
890        }
891        LighterOrderStatus::Filled => {
892            if open_ctx.accepted_already_emitted && open_ctx.shape_changed {
893                let updated = parse_lighter_order_updated(
894                    order, instrument, identity, cloid, account_id, trader_id, ts_init,
895                )?;
896                Ok(Some(ParsedOrderEvent::Updated(updated)))
897            } else {
898                Ok(None)
899            }
900        }
901        LighterOrderStatus::CanceledExpired => {
902            let expired = OrderExpired::new(
903                trader_id,
904                identity.strategy_id,
905                identity.instrument_id,
906                cloid,
907                UUID4::new(),
908                ts_event,
909                ts_init,
910                false,
911                Some(venue_order_id),
912                Some(account_id),
913            );
914            Ok(Some(ParsedOrderEvent::Expired(expired)))
915        }
916        LighterOrderStatus::CanceledPostOnly
917            if !open_ctx.accepted_already_emitted && order.filled_base_amount.is_zero() =>
918        {
919            let rejected = OrderRejected::new(
920                trader_id,
921                identity.strategy_id,
922                identity.instrument_id,
923                cloid,
924                account_id,
925                Ustr::from("post-only"),
926                UUID4::new(),
927                ts_event,
928                ts_init,
929                false,
930                true, // due_post_only
931            );
932            Ok(Some(ParsedOrderEvent::Rejected(rejected)))
933        }
934        LighterOrderStatus::CanceledPostOnly
935        | LighterOrderStatus::Canceled
936        | LighterOrderStatus::CanceledReduceOnly
937        | LighterOrderStatus::CanceledPositionNotAllowed
938        | LighterOrderStatus::CanceledMarginNotAllowed
939        | LighterOrderStatus::CanceledTooMuchSlippage
940        | LighterOrderStatus::CanceledNotEnoughLiquidity
941        | LighterOrderStatus::CanceledSelfTrade
942        | LighterOrderStatus::CanceledOco
943        | LighterOrderStatus::CanceledChild
944        | LighterOrderStatus::CanceledLiquidation
945        | LighterOrderStatus::CanceledInvalidBalance => {
946            let canceled = OrderCanceled::new(
947                trader_id,
948                identity.strategy_id,
949                identity.instrument_id,
950                cloid,
951                UUID4::new(),
952                ts_event,
953                ts_init,
954                false,
955                Some(venue_order_id),
956                Some(account_id),
957                order.status.as_cancel_reason().map(Ustr::from),
958            );
959            Ok(Some(ParsedOrderEvent::Canceled(canceled)))
960        }
961    }
962}
963
964pub(crate) fn parse_lighter_order_updated(
965    order: &LighterOrder,
966    instrument: &InstrumentAny,
967    identity: &OrderIdentity,
968    cloid: ClientOrderId,
969    account_id: AccountId,
970    trader_id: TraderId,
971    ts_init: UnixNanos,
972) -> anyhow::Result<OrderUpdated> {
973    let shape =
974        identity.normalize_shape(lighter_order_shape(order, instrument, identity.order_type)?);
975    let ts_event = parse_optional_order_timestamp(order.updated_at)?;
976    let venue_order_id = VenueOrderId::new(order.order_id.as_str());
977
978    // A late reduction must close an order whose final fill is already applied
979    let reconciliation = shape.quantity.as_decimal() < order.initial_base_amount;
980    Ok(OrderUpdated::new(
981        trader_id,
982        identity.strategy_id,
983        identity.instrument_id,
984        cloid,
985        shape.quantity,
986        UUID4::new(),
987        ts_event,
988        ts_init,
989        reconciliation,
990        Some(venue_order_id),
991        Some(account_id),
992        shape.price,
993        shape.trigger_price,
994        None,
995        false,
996    ))
997}
998
999/// Build an [`OrderFilled`] event from a Lighter `account_trades` payload,
1000/// using the identity context captured at submit time.
1001///
1002/// Returns `Ok(None)` if the trade does not involve `account_index` (the
1003/// venue forwards crossed pairs the account is not part of on the same
1004/// channel). The caller dedupes by `TradeId` against
1005/// `WsDispatchState::seen_trade_ids` to drop repeats on reconnect.
1006///
1007/// # Errors
1008///
1009/// Returns an error if:
1010/// - The trade ID, price, size, or timestamp cannot be converted.
1011/// - The commission calculation overflows or cannot be represented as [`Money`].
1012#[expect(
1013    clippy::too_many_arguments,
1014    reason = "identity and account context are independent inputs threaded by the dispatcher"
1015)]
1016pub(crate) fn parse_lighter_order_filled(
1017    trade: &LighterTrade,
1018    instrument: &InstrumentAny,
1019    identity: &OrderIdentity,
1020    cloid: ClientOrderId,
1021    account_id: AccountId,
1022    trader_id: TraderId,
1023    account_index: i64,
1024    ts_init: UnixNanos,
1025) -> anyhow::Result<Option<OrderFilled>> {
1026    let user_is_bidder = trade.bid_account_id == account_index;
1027    let user_is_asker = trade.ask_account_id == account_index;
1028    if !user_is_bidder && !user_is_asker {
1029        return Ok(None);
1030    }
1031
1032    let liquidity_side = if user_is_asker == trade.is_maker_ask {
1033        LiquiditySide::Maker
1034    } else {
1035        LiquiditySide::Taker
1036    };
1037
1038    let venue_order_id = if user_is_bidder {
1039        venue_order_id_from(trade.bid_id_str.as_deref(), trade.bid_id)
1040    } else {
1041        venue_order_id_from(trade.ask_id_str.as_deref(), trade.ask_id)
1042    };
1043
1044    let trade_id = match trade.trade_id_str.as_deref() {
1045        Some(s) => TradeId::new_checked(s),
1046        None => TradeId::new_checked(trade.trade_id.to_string()),
1047    }
1048    .context("invalid Lighter trade identifier")?;
1049
1050    let last_qty = quantity_from_decimal(trade.size, instrument.size_precision())?;
1051    let last_px = price_from_decimal(trade.price, instrument.price_precision())?;
1052
1053    let fee_value = if liquidity_side == LiquiditySide::Maker {
1054        trade.maker_fee
1055    } else {
1056        trade.taker_fee
1057    };
1058
1059    let commission = lighter_fee_to_commission(fee_value, trade, instrument.quote_currency())?;
1060
1061    let timestamp_ms =
1062        u64::try_from(trade.timestamp).context("negative Lighter trade timestamp")?;
1063    let ts_event = parse_millis_to_nanos(timestamp_ms)?;
1064
1065    Ok(Some(OrderFilled::new(
1066        trader_id,
1067        identity.strategy_id,
1068        identity.instrument_id,
1069        cloid,
1070        venue_order_id,
1071        account_id,
1072        trade_id,
1073        identity.order_side,
1074        identity.order_type,
1075        last_qty,
1076        last_px,
1077        instrument.quote_currency(),
1078        liquidity_side,
1079        UUID4::new(),
1080        ts_event,
1081        ts_init,
1082        false, // reconciliation
1083        None,  // venue_position_id: Lighter perps run NETTING
1084        Some(commission),
1085        None,
1086    )))
1087}
1088
1089/// Parses a Lighter position payload into a [`PositionStatusReport`].
1090///
1091/// The `account_all_positions` frame carries no top-level event timestamp;
1092/// callers should pass the wall-clock arrival time captured by the handler.
1093///
1094/// # Errors
1095///
1096/// Returns an error if the size or entry price cannot be converted.
1097pub fn parse_ws_position_status_report(
1098    position: &LighterPosition,
1099    instrument: &InstrumentAny,
1100    account_id: AccountId,
1101    ts_event: UnixNanos,
1102    ts_init: UnixNanos,
1103) -> anyhow::Result<PositionStatusReport> {
1104    let quantity = quantity_from_decimal(position.position, instrument.size_precision())?;
1105    let position_side = if quantity.is_zero() {
1106        PositionSide::Flat
1107    } else if position.sign < 0 {
1108        PositionSide::Short
1109    } else {
1110        PositionSide::Long
1111    };
1112
1113    let avg_px_open = if position_side == PositionSide::Flat {
1114        None
1115    } else {
1116        Some(position.avg_entry_price)
1117    };
1118
1119    let mut report = PositionStatusReport::new(
1120        account_id,
1121        instrument.id(),
1122        position_side,
1123        quantity,
1124        ts_event,
1125        ts_init,
1126        Some(UUID4::new()),
1127        None, // venue_position_id: NETTING, Nautilus identifies by instrument
1128        avg_px_open,
1129    );
1130    report.liquidation_price = Some(position.liquidation_price);
1131    Ok(report)
1132}
1133
1134/// Builds the per-asset [`AccountBalance`] before applying `user_stats.available_balance`.
1135///
1136/// The total is `balance + margin_balance`, and `locked_balance` reserves resting spot orders.
1137/// The account-state reconciler then caps settlement-currency free funds at
1138/// `max(user_stats.available_balance, 0)`. [`MarginBalance`] reports account-wide margin separately.
1139///
1140/// # Errors
1141///
1142/// Returns an error if `AccountBalance::from_total_and_locked` rejects
1143/// the computed values.
1144pub fn account_balance_from_lighter_asset(asset: &LighterAsset) -> anyhow::Result<AccountBalance> {
1145    let currency = Currency::get_or_create_crypto(asset.symbol);
1146    let total = asset.balance + asset.margin_balance;
1147    let locked = asset.locked_balance;
1148    AccountBalance::from_total_and_locked(total, locked, currency)
1149        .context("failed to construct Lighter account balance")
1150}
1151
1152/// Builds the cross-margin [`MarginBalance`] from a `user_stats` frame.
1153///
1154/// This compatibility entry point uses USDC. Deployment-aware clients call
1155/// [`margin_balance_from_user_stats_with_currency`].
1156///
1157/// `user_stats` is the deployment's perp-side settlement-currency rollup. We derive:
1158/// - `initial = max(collateral - available_balance, 0)`: collateral
1159///   currently allocated to open positions/orders
1160/// - `maintenance = 0`: Lighter does not publish maintenance margin on
1161///   `user_stats`. `margin_usage` looks like a maintenance ratio but is
1162///   actually the initial-margin-usage percentage
1163///   (`(collateral - available) / collateral * 100`), so it carries no
1164///   information about maintenance. Computing maintenance per-position
1165///   from the positions stream would be more accurate; until that's
1166///   wired we report zero rather than fabricate a value.
1167///
1168/// `instrument_id = None` routes this into `MarginAccount.account_margins`
1169/// (cross margin keyed by currency), which is what the portfolio reads for
1170/// venues running unified cross-margin mode.
1171///
1172/// # Errors
1173///
1174/// Returns an error if either `Money::from_decimal` call rejects the value.
1175pub fn margin_balance_from_user_stats(stats: &LighterUserStats) -> anyhow::Result<MarginBalance> {
1176    margin_balance_from_user_stats_with_currency(stats, Currency::get_or_create_crypto("USDC"))
1177}
1178
1179/// Builds the cross-margin [`MarginBalance`] in the supplied settlement currency.
1180///
1181/// # Errors
1182///
1183/// Returns an error if either `Money::from_decimal` call rejects the value.
1184pub fn margin_balance_from_user_stats_with_currency(
1185    stats: &LighterUserStats,
1186    settlement_currency: Currency,
1187) -> anyhow::Result<MarginBalance> {
1188    let initial_dec = (stats.collateral - stats.available_balance).max(Decimal::ZERO);
1189    let initial = Money::from_decimal(initial_dec, settlement_currency)
1190        .map_err(|e| anyhow::anyhow!("failed to construct initial margin: {e}"))?;
1191    let maintenance = Money::from_decimal(Decimal::ZERO, settlement_currency)
1192        .map_err(|e| anyhow::anyhow!("failed to construct maintenance margin: {e}"))?;
1193    Ok(MarginBalance::new(initial, maintenance, None))
1194}
1195
1196/// Assembles the unified [`AccountState`] from already-parsed components.
1197///
1198/// The reconciler in the `websocket::account_state` module owns the latest
1199/// snapshot of each input stream and calls this once per emission.
1200/// `AccountType::Margin` is invariant for Lighter; `base_currency` is `None`
1201/// because the account holds multiple spot currencies.
1202#[must_use]
1203pub fn build_unified_account_state(
1204    balances: Vec<AccountBalance>,
1205    margin: Option<MarginBalance>,
1206    account_id: AccountId,
1207    ts_event: UnixNanos,
1208    ts_init: UnixNanos,
1209) -> AccountState {
1210    let margins = margin.map(|m| vec![m]).unwrap_or_default();
1211    AccountState::new(
1212        account_id,
1213        AccountType::Margin,
1214        balances,
1215        margins,
1216        true,
1217        UUID4::new(),
1218        ts_event,
1219        ts_init,
1220        None,
1221    )
1222}
1223
1224/// Largest ten-digit Unix timestamp. Lighter order frames deliver `created_at` and
1225/// `updated_at` in seconds or milliseconds depending on the frame source, so parsing
1226/// normalizes second-scale values before nanosecond conversion.
1227const UNIX_TIMESTAMP_SECONDS_MAX: i64 = 9_999_999_999;
1228
1229fn parse_optional_order_timestamp(timestamp: i64) -> anyhow::Result<UnixNanos> {
1230    if timestamp <= 0 {
1231        return Ok(UnixNanos::default());
1232    }
1233
1234    let millis = if timestamp <= UNIX_TIMESTAMP_SECONDS_MAX {
1235        timestamp * 1_000
1236    } else {
1237        timestamp
1238    };
1239
1240    parse_millis_to_nanos(millis as u64)
1241}
1242
1243fn parse_optional_price(value: Decimal, precision: u8) -> anyhow::Result<Option<Price>> {
1244    if value.is_zero() {
1245        return Ok(None);
1246    }
1247    Price::from_decimal_dp(value, precision)
1248        .map(Some)
1249        .map_err(|e| anyhow::anyhow!("invalid price `{value}` at precision {precision}: {e}"))
1250}
1251
1252fn lighter_fee_to_commission(
1253    fee_ticks: Option<i32>,
1254    trade: &LighterTrade,
1255    currency: Currency,
1256) -> Result<Money, LighterCommissionError> {
1257    let ticks = fee_ticks.unwrap_or(0);
1258    let rate = Decimal::new(i64::from(ticks), FEE_DECIMALS);
1259    let amount = rate
1260        .checked_mul(trade.size)
1261        .and_then(|amount| amount.checked_mul(trade.price))
1262        .ok_or_else(|| LighterCommissionError::new("overflow calculating fee amount"))?;
1263    Money::from_decimal(amount, currency).map_err(|e| LighterCommissionError::new(e.to_string()))
1264}
1265
1266fn nautilus_order_side(side: LighterOrderSide) -> OrderSide {
1267    match side {
1268        LighterOrderSide::Buy => OrderSide::Buy,
1269        LighterOrderSide::Sell => OrderSide::Sell,
1270    }
1271}
1272
1273fn nautilus_order_type(kind: LighterOrderKind) -> anyhow::Result<OrderType> {
1274    match kind {
1275        LighterOrderKind::Limit => Ok(OrderType::Limit),
1276        LighterOrderKind::Market => Ok(OrderType::Market),
1277        LighterOrderKind::StopLoss => Ok(OrderType::StopMarket),
1278        LighterOrderKind::StopLossLimit => Ok(OrderType::StopLimit),
1279        LighterOrderKind::TakeProfit => Ok(OrderType::MarketIfTouched),
1280        LighterOrderKind::TakeProfitLimit => Ok(OrderType::LimitIfTouched),
1281        LighterOrderKind::Twap | LighterOrderKind::TwapSub | LighterOrderKind::Liquidation => Err(
1282            anyhow::anyhow!("Lighter `{kind:?}` has no Nautilus order-type equivalent",),
1283        ),
1284    }
1285}
1286
1287fn nautilus_time_in_force(
1288    tif: LighterOrderTimeInForce,
1289    order_expiry: i64,
1290) -> (TimeInForce, Option<UnixNanos>) {
1291    match tif {
1292        LighterOrderTimeInForce::ImmediateOrCancel => (TimeInForce::Ioc, None),
1293        LighterOrderTimeInForce::PostOnly | LighterOrderTimeInForce::GoodTillTime => {
1294            // Lighter uses positive expiry for GTD and nonpositive expiry for GTC;
1295            // PostOnly uses the same expiry field plus an independent report flag.
1296            if order_expiry > 0 {
1297                match parse_millis_to_nanos(order_expiry as u64) {
1298                    Ok(expiry) => (TimeInForce::Gtd, Some(expiry)),
1299                    Err(_) => (TimeInForce::Gtc, None),
1300                }
1301            } else {
1302                (TimeInForce::Gtc, None)
1303            }
1304        }
1305        LighterOrderTimeInForce::Unknown => (TimeInForce::Gtc, None),
1306    }
1307}
1308
1309fn nautilus_order_status(status: LighterOrderStatus, filled_qty: &Quantity) -> OrderStatus {
1310    match status {
1311        LighterOrderStatus::InProgress => OrderStatus::Submitted,
1312        LighterOrderStatus::Pending | LighterOrderStatus::Open => {
1313            if filled_qty.is_zero() {
1314                OrderStatus::Accepted
1315            } else {
1316                OrderStatus::PartiallyFilled
1317            }
1318        }
1319        LighterOrderStatus::Filled => OrderStatus::Filled,
1320        LighterOrderStatus::CanceledExpired => OrderStatus::Expired,
1321        LighterOrderStatus::CanceledPostOnly if filled_qty.is_zero() => OrderStatus::Rejected,
1322        LighterOrderStatus::CanceledPostOnly
1323        | LighterOrderStatus::Canceled
1324        | LighterOrderStatus::CanceledReduceOnly
1325        | LighterOrderStatus::CanceledPositionNotAllowed
1326        | LighterOrderStatus::CanceledMarginNotAllowed
1327        | LighterOrderStatus::CanceledTooMuchSlippage
1328        | LighterOrderStatus::CanceledNotEnoughLiquidity
1329        | LighterOrderStatus::CanceledSelfTrade
1330        | LighterOrderStatus::CanceledOco
1331        | LighterOrderStatus::CanceledChild
1332        | LighterOrderStatus::CanceledLiquidation
1333        | LighterOrderStatus::CanceledInvalidBalance => OrderStatus::Canceled,
1334    }
1335}
1336
1337/// Resolve a venue order id from the venue-provided string field, falling
1338/// back to the numeric `i64` mirror when the string field is absent. Skips
1339/// the `Option<String>::clone` the previous code paid on every fill.
1340fn venue_order_id_from(str_field: Option<&str>, numeric_fallback: i64) -> VenueOrderId {
1341    match str_field {
1342        Some(s) => VenueOrderId::new(s),
1343        None => VenueOrderId::new(numeric_fallback.to_string()),
1344    }
1345}
1346
1347/// Resolve an optional client order id from the venue's string field, treating
1348/// empty and the sentinel `"0"` as absent; falls back to the numeric `i64`
1349/// mirror when the string field is `None`.
1350fn client_order_id_from(str_field: Option<&str>, numeric_fallback: i64) -> Option<ClientOrderId> {
1351    match str_field {
1352        Some(s) if !s.is_empty() && s != "0" => Some(ClientOrderId::new(s)),
1353        None if numeric_fallback != 0 => Some(ClientOrderId::new(numeric_fallback.to_string())),
1354        _ => None,
1355    }
1356}
1357
1358#[cfg(test)]
1359mod tests {
1360    use std::str::FromStr;
1361
1362    use nautilus_model::{
1363        enums::{AvgPxReconciliation, BarAggregation, PriceType},
1364        identifiers::{InstrumentId, StrategyId, Symbol, Venue},
1365        instruments::CryptoPerpetual,
1366        types::{Price, Quantity, currency::Currency},
1367    };
1368    use rstest::rstest;
1369    use ustr::Ustr;
1370
1371    use super::*;
1372    use crate::{
1373        common::enums::LighterTradeType,
1374        http::models::LighterTrade,
1375        websocket::messages::{LighterMarketStats, LighterSpotMarketStats},
1376    };
1377
1378    fn create_test_instrument() -> InstrumentAny {
1379        create_test_instrument_with_quote(Venue::new("LIGHTER"), Currency::from("USDC"))
1380    }
1381
1382    fn create_test_instrument_with_quote(venue: Venue, quote_currency: Currency) -> InstrumentAny {
1383        let instrument_id = InstrumentId::new(Symbol::new("ETH-PERP"), venue);
1384
1385        InstrumentAny::CryptoPerpetual(
1386            CryptoPerpetual::builder()
1387                .instrument_id(instrument_id)
1388                .raw_symbol(Symbol::new("ETH-PERP"))
1389                .base_currency(Currency::from("ETH"))
1390                .quote_currency(quote_currency)
1391                .settlement_currency(quote_currency)
1392                .is_inverse(false)
1393                .price_precision(2)
1394                .size_precision(4)
1395                .price_increment(Price::from("0.01"))
1396                .size_increment(Quantity::from("0.0001"))
1397                .ts_event(UnixNanos::default())
1398                .ts_init(UnixNanos::default())
1399                .build()
1400                .unwrap(),
1401        )
1402    }
1403
1404    fn stub_book() -> LighterWsOrderBook {
1405        LighterWsOrderBook {
1406            code: 0,
1407            asks: vec![LighterPriceLevel {
1408                price: Decimal::from_str("2064.54").unwrap(),
1409                size: Decimal::from_str("0.3285").unwrap(),
1410            }],
1411            bids: vec![LighterPriceLevel {
1412                price: Decimal::from_str("2064.30").unwrap(),
1413                size: Decimal::from_str("1.0392").unwrap(),
1414            }],
1415            offset: 1558300,
1416            nonce: 9182390020,
1417            last_updated_at: 1774884082309144,
1418            begin_nonce: 9182389998,
1419        }
1420    }
1421
1422    fn stub_market_stats() -> LighterMarketStats {
1423        LighterMarketStats {
1424            symbol: Ustr::from("ETH"),
1425            market_id: 0,
1426            index_price: Decimal::from_str("2064.48").unwrap(),
1427            mark_price: Decimal::from_str("2064.47").unwrap(),
1428            mid_price: Decimal::from_str("2064.39").unwrap(),
1429            open_interest: Decimal::from_str("27250.8411").unwrap(),
1430            open_interest_limit: Decimal::from_str("50000.0000").unwrap(),
1431            funding_clamp_small: Decimal::from_str("0.0001").unwrap(),
1432            funding_clamp_big: Decimal::from_str("0.0002").unwrap(),
1433            last_trade_price: Decimal::from_str("2064.50").unwrap(),
1434            current_funding_rate: Decimal::from_str("0.000001").unwrap(),
1435            funding_rate: Decimal::from_str("0.000002").unwrap(),
1436            funding_timestamp: 1_774_879_200_000,
1437            daily_base_token_volume: Decimal::new(1_999_586_931, 4),
1438            daily_quote_token_volume: Decimal::new(471_193_598_847_246, 6),
1439            daily_price_low: Decimal::new(231_181, 2),
1440            daily_price_high: Decimal::new(2_398, 0),
1441            daily_price_change: Decimal::new(16_854_147_780_232_130, 17),
1442        }
1443    }
1444
1445    fn stub_spot_market_stats() -> LighterSpotMarketStats {
1446        LighterSpotMarketStats {
1447            symbol: Ustr::from("ETH"),
1448            market_id: 2048,
1449            index_price: Decimal::from_str("1.000000").unwrap(),
1450            mid_price: Decimal::from_str("1.000001").unwrap(),
1451            last_trade_price: Decimal::from_str("1.000002").unwrap(),
1452            daily_base_token_volume: Decimal::from(1000),
1453            daily_quote_token_volume: Decimal::new(10_001, 1),
1454            daily_price_low: Decimal::new(999_999, 6),
1455            daily_price_high: Decimal::new(1_000_002, 6),
1456            daily_price_change: Decimal::new(1, 6),
1457        }
1458    }
1459
1460    #[rstest]
1461    fn test_parse_ws_order_book_deltas_snapshot() {
1462        let instrument = create_test_instrument();
1463        let ts_init = UnixNanos::from(1);
1464
1465        let deltas =
1466            parse_ws_order_book_deltas(&stub_book(), &instrument, 1774884082326, true, ts_init)
1467                .unwrap();
1468
1469        assert_eq!(deltas.deltas.len(), 3);
1470        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1471        assert_eq!(deltas.deltas[1].action, BookAction::Add);
1472        assert_eq!(deltas.deltas[1].order.side, OrderSide::Buy.into());
1473        assert_eq!(deltas.deltas[1].order.price, Price::from("2064.30"));
1474        assert_eq!(deltas.deltas[1].order.size, Quantity::from("1.0392"));
1475        assert_eq!(deltas.deltas[2].order.side, OrderSide::Sell.into());
1476        assert_eq!(deltas.deltas[2].order.price, Price::from("2064.54"));
1477        assert_eq!(deltas.deltas[2].order.size, Quantity::from("0.3285"));
1478        assert_eq!(deltas.deltas[0].sequence, 9_182_390_020);
1479        assert_eq!(deltas.deltas[1].sequence, 9_182_390_020);
1480        assert_eq!(deltas.deltas[2].sequence, 9_182_390_020);
1481        assert_eq!(deltas.sequence, 9_182_390_020);
1482        assert_eq!(
1483            deltas.deltas[2].flags & RecordFlag::F_LAST as u8,
1484            RecordFlag::F_LAST as u8,
1485        );
1486    }
1487
1488    #[rstest]
1489    fn test_parse_ws_order_book_deltas_update_delete_zero_size() {
1490        let instrument = create_test_instrument();
1491        let mut book = stub_book();
1492        book.asks[0].size = Decimal::ZERO;
1493
1494        let deltas = parse_ws_order_book_deltas(
1495            &book,
1496            &instrument,
1497            1774884082326,
1498            false,
1499            UnixNanos::from(1),
1500        )
1501        .unwrap();
1502
1503        assert_eq!(deltas.deltas.len(), 2);
1504        assert_eq!(deltas.deltas[0].action, BookAction::Update);
1505        assert_eq!(deltas.deltas[0].order.side, OrderSide::Buy.into());
1506        assert_eq!(deltas.deltas[0].order.price, Price::from("2064.30"));
1507        assert_eq!(deltas.deltas[1].action, BookAction::Delete);
1508        assert_eq!(deltas.deltas[1].order.side, OrderSide::Sell.into());
1509        assert_eq!(deltas.deltas[1].order.price, Price::from("2064.54"));
1510    }
1511
1512    #[rstest]
1513    fn test_parse_ws_order_book_deltas_rejects_negative_nonce() {
1514        let instrument = create_test_instrument();
1515        let mut book = stub_book();
1516        book.nonce = -1;
1517
1518        let err = parse_ws_order_book_deltas(
1519            &book,
1520            &instrument,
1521            1774884082326,
1522            false,
1523            UnixNanos::from(1),
1524        )
1525        .unwrap_err();
1526
1527        assert!(err.to_string().contains("negative Lighter book nonce"));
1528    }
1529
1530    #[rstest]
1531    fn test_parse_ws_order_book_deltas_rejects_empty_update() {
1532        let instrument = create_test_instrument();
1533        let mut book = stub_book();
1534        book.asks.clear();
1535        book.bids.clear();
1536
1537        let err = parse_ws_order_book_deltas(
1538            &book,
1539            &instrument,
1540            1774884082326,
1541            false,
1542            UnixNanos::from(1),
1543        )
1544        .unwrap_err();
1545
1546        assert!(
1547            err.to_string()
1548                .contains("empty Lighter WebSocket order book update")
1549        );
1550    }
1551
1552    #[rstest]
1553    fn test_parse_ws_order_book_deltas_rejects_zero_size_snapshot_level() {
1554        let instrument = create_test_instrument();
1555        let mut book = stub_book();
1556        book.bids[0].size = Decimal::ZERO;
1557
1558        let err =
1559            parse_ws_order_book_deltas(&book, &instrument, 1774884082326, true, UnixNanos::from(1))
1560                .unwrap_err();
1561
1562        assert!(
1563            err.to_string()
1564                .contains("failed to construct Lighter WebSocket book delta")
1565        );
1566    }
1567
1568    #[rstest]
1569    fn test_parse_ws_quote_tick() {
1570        let instrument = create_test_instrument();
1571        let ticker = LighterTicker {
1572            s: Ustr::from("ETH"),
1573            a: LighterPriceLevel {
1574                price: Decimal::from_str("2064.48").unwrap(),
1575                size: Decimal::from_str("0.4950").unwrap(),
1576            },
1577            b: LighterPriceLevel {
1578                price: Decimal::from_str("2064.30").unwrap(),
1579                size: Decimal::from_str("1.0392").unwrap(),
1580            },
1581            last_updated_at: 1774883844921166,
1582        };
1583
1584        let quote = parse_ws_quote_tick(&ticker, &instrument, 1774883844933, UnixNanos::from(1))
1585            .unwrap()
1586            .expect("two-sided ticker yields a quote");
1587
1588        assert_eq!(quote.instrument_id, instrument.id());
1589        assert_eq!(quote.bid_price, Price::from("2064.30"));
1590        assert_eq!(quote.ask_price, Price::from("2064.48"));
1591        assert_eq!(quote.bid_size, Quantity::from("1.0392"));
1592        assert_eq!(quote.ask_size, Quantity::from("0.4950"));
1593        assert_eq!(quote.ts_event, UnixNanos::from(1_774_883_844_933_000_000),);
1594    }
1595
1596    #[rstest]
1597    fn test_parse_ws_quote_tick_skips_one_sided_book() {
1598        let instrument = create_test_instrument();
1599        let ticker = LighterTicker {
1600            s: Ustr::from("ETH"),
1601            a: LighterPriceLevel {
1602                price: Decimal::from_str("2064.48").unwrap(),
1603                size: Decimal::from_str("0.4950").unwrap(),
1604            },
1605            b: LighterPriceLevel {
1606                // Lighter emits empty strings when one side has no resting
1607                // orders; the wire deserializer maps those to `Decimal::ZERO`.
1608                price: Decimal::ZERO,
1609                size: Decimal::ZERO,
1610            },
1611            last_updated_at: 1774883844921166,
1612        };
1613
1614        let result =
1615            parse_ws_quote_tick(&ticker, &instrument, 1774883844933, UnixNanos::from(1)).unwrap();
1616
1617        assert!(result.is_none());
1618    }
1619
1620    #[rstest]
1621    fn test_parse_ws_quote_tick_rejects_invalid_price() {
1622        // With Decimal model fields, wire-malformed prices are rejected at
1623        // JSON deserialize time; this test guards the deserialize boundary so
1624        // a bad payload does not silently construct a zero-priced quote.
1625        let payload = serde_json::json!({
1626            "s": "ETH",
1627            "a": {"price": "not-a-price", "size": "0.4950"},
1628            "b": {"price": "2064.30", "size": "1.0392"},
1629            "last_updated_at": 1774883844921166u64,
1630        });
1631
1632        let err = serde_json::from_value::<LighterTicker>(payload).unwrap_err();
1633        assert!(err.to_string().to_lowercase().contains("decimal"));
1634    }
1635
1636    #[rstest]
1637    fn test_parse_ws_mark_price_update() {
1638        let instrument = create_test_instrument();
1639
1640        let update = parse_ws_mark_price_update(
1641            &stub_market_stats(),
1642            &instrument,
1643            1_774_883_844_933,
1644            UnixNanos::from(1),
1645        )
1646        .unwrap();
1647
1648        assert_eq!(update.instrument_id, instrument.id());
1649        assert_eq!(update.value, Price::from("2064.47"));
1650        assert_eq!(update.ts_event, UnixNanos::from(1_774_883_844_933_000_000));
1651        assert_eq!(update.ts_init, UnixNanos::from(1));
1652    }
1653
1654    #[rstest]
1655    fn test_parse_ws_index_price_update() {
1656        let instrument = create_test_instrument();
1657
1658        let update = parse_ws_index_price_update(
1659            &stub_market_stats(),
1660            &instrument,
1661            1_774_883_844_933,
1662            UnixNanos::from(1),
1663        )
1664        .unwrap();
1665
1666        assert_eq!(update.instrument_id, instrument.id());
1667        assert_eq!(update.value, Price::from("2064.48"));
1668        assert_eq!(update.ts_event, UnixNanos::from(1_774_883_844_933_000_000));
1669    }
1670
1671    #[rstest]
1672    fn test_parse_ws_spot_index_price_update() {
1673        let instrument = create_test_instrument();
1674
1675        let update = parse_ws_spot_index_price_update(
1676            &stub_spot_market_stats(),
1677            &instrument,
1678            1_774_883_844_933,
1679            UnixNanos::from(1),
1680        )
1681        .unwrap();
1682
1683        assert_eq!(update.instrument_id, instrument.id());
1684        assert_eq!(update.value, Price::from("1.00"));
1685        assert_eq!(update.ts_event, UnixNanos::from(1_774_883_844_933_000_000));
1686    }
1687
1688    #[rstest]
1689    fn test_parse_ws_funding_rate_update_omits_last_payment_timestamp() {
1690        let instrument = create_test_instrument();
1691        let stats = stub_market_stats();
1692        let ts_init = UnixNanos::from(1_774_883_900_000_000_000);
1693
1694        let update =
1695            parse_ws_funding_rate_update(&stats, &instrument, 1_774_883_844_933, ts_init).unwrap();
1696
1697        assert_eq!(stats.funding_timestamp, 1_774_879_200_000);
1698        assert_eq!(update.instrument_id, instrument.id());
1699        assert_eq!(update.rate, Decimal::from_str("0.00000001").unwrap());
1700        assert_eq!(update.interval, Some(60));
1701        assert_eq!(update.next_funding_ns, None);
1702        assert_eq!(update.ts_event, UnixNanos::from(1_774_883_844_933_000_000));
1703        assert_eq!(update.ts_init, ts_init);
1704    }
1705
1706    // Pins which field each price-update parser reads from `LighterMarketStats`.
1707    // The three parsers share `build_price_update`; without these guards a
1708    // regression that swaps `mark_price` and `index_price` (or that has
1709    // `funding_rate_update` accidentally reading `funding_rate` instead of
1710    // `current_funding_rate`) would only fail one of the three happy-path
1711    // tests above and might pass them all if their fixtures happen to align.
1712    #[rstest]
1713    fn test_parse_ws_mark_price_update_reads_mark_field_only() {
1714        let instrument = create_test_instrument();
1715        let mut stats = stub_market_stats();
1716        let sentinel = Decimal::from_str("1234.56").unwrap();
1717        let other = Decimal::from_str("9999.99").unwrap();
1718        stats.mark_price = sentinel;
1719        stats.index_price = other;
1720        stats.mid_price = other;
1721        stats.last_trade_price = other;
1722
1723        let update =
1724            parse_ws_mark_price_update(&stats, &instrument, 1_774_883_844_933, UnixNanos::from(1))
1725                .unwrap();
1726
1727        assert_eq!(update.value, Price::from("1234.56"));
1728    }
1729
1730    #[rstest]
1731    fn test_parse_ws_index_price_update_reads_index_field_only() {
1732        let instrument = create_test_instrument();
1733        let mut stats = stub_market_stats();
1734        let sentinel = Decimal::from_str("1234.56").unwrap();
1735        let other = Decimal::from_str("9999.99").unwrap();
1736        stats.index_price = sentinel;
1737        stats.mark_price = other;
1738        stats.mid_price = other;
1739        stats.last_trade_price = other;
1740
1741        let update =
1742            parse_ws_index_price_update(&stats, &instrument, 1_774_883_844_933, UnixNanos::from(1))
1743                .unwrap();
1744
1745        assert_eq!(update.value, Price::from("1234.56"));
1746    }
1747
1748    #[rstest]
1749    fn test_parse_ws_funding_rate_update_reads_current_funding_rate_field_only() {
1750        let instrument = create_test_instrument();
1751        let mut stats = stub_market_stats();
1752        // `funding_rate` is the prior payment; the parser must read
1753        // `current_funding_rate` instead. Setting distinct sentinel values
1754        // catches a field-swap regression.
1755        let sentinel = Decimal::from_str("0.0000123").unwrap();
1756        let other = Decimal::from_str("0.9999").unwrap();
1757        stats.current_funding_rate = sentinel;
1758        stats.funding_rate = other;
1759
1760        let update = parse_ws_funding_rate_update(
1761            &stats,
1762            &instrument,
1763            1_774_883_844_933,
1764            UnixNanos::from(1),
1765        )
1766        .unwrap();
1767
1768        assert_eq!(update.rate, Decimal::from_str("0.000000123").unwrap());
1769    }
1770
1771    #[rstest]
1772    fn test_parse_ws_funding_rate_update_converts_percent_to_fraction() {
1773        let instrument = create_test_instrument();
1774        let mut stats = stub_market_stats();
1775        stats.current_funding_rate = Decimal::from_str("0.00125").unwrap();
1776
1777        let update = parse_ws_funding_rate_update(
1778            &stats,
1779            &instrument,
1780            1_774_883_844_933,
1781            UnixNanos::from(1),
1782        )
1783        .unwrap();
1784
1785        assert_eq!(update.rate, Decimal::from_str("0.0000125").unwrap());
1786        assert_eq!(update.interval, Some(60));
1787        let annualized =
1788            update.rate * Decimal::from(525_600) / Decimal::from(update.interval.unwrap());
1789        assert_eq!(annualized, Decimal::from_str("0.1095").unwrap());
1790    }
1791
1792    #[rstest]
1793    fn test_parse_ws_order_book_depth_preserves_sparse_levels() {
1794        let instrument = create_test_instrument();
1795        let depth =
1796            parse_ws_order_book_depth(&stub_book(), &instrument, 1774884082326, UnixNanos::from(1))
1797                .unwrap();
1798
1799        assert_eq!(depth.instrument_id, instrument.id());
1800        assert_eq!(depth.bids.len(), 1);
1801        assert_eq!(depth.asks.len(), 1);
1802        assert_eq!(depth.bids[0].price, Price::from("2064.30"));
1803        assert_eq!(depth.bids[0].size, Quantity::from("1.0392"));
1804        assert_eq!(depth.bids[0].side, OrderSide::Buy.into());
1805        assert_eq!(depth.bids[0].order_id, 0);
1806        assert_eq!(depth.asks[0].price, Price::from("2064.54"));
1807        assert_eq!(depth.asks[0].size, Quantity::from("0.3285"));
1808        assert_eq!(depth.asks[0].side, OrderSide::Sell.into());
1809        assert_eq!(depth.asks[0].order_id, 0);
1810        assert_eq!(depth.sequence, 9_182_390_020);
1811        assert_eq!(depth.bid_counts.as_slice(), &[1]);
1812        assert_eq!(depth.ask_counts.as_slice(), &[1]);
1813        assert_eq!(depth.flags, RecordFlag::F_SNAPSHOT as u8);
1814        assert_eq!(depth.ts_event, UnixNanos::from(1_774_884_082_326_000_000));
1815        assert_eq!(depth.ts_init, UnixNanos::from(1));
1816    }
1817
1818    #[rstest]
1819    fn test_parse_ws_trade_tick_delegates_trade_parser() {
1820        let instrument = create_test_instrument();
1821        let trade = LighterTrade {
1822            trade_id: 16164557907,
1823            trade_id_str: Some("16164557907".to_string()),
1824            tx_hash: "019f2b9c".to_string(),
1825            trade_type: LighterTradeType::Trade,
1826            market_id: 0,
1827            size: Decimal::from_str("0.1336").unwrap(),
1828            price: Decimal::from_str("2181.83").unwrap(),
1829            usd_amount: Decimal::from_str("291.492488").unwrap(),
1830            ask_id: 281476612587355,
1831            ask_id_str: Some("281476612587355".to_string()),
1832            bid_id: 562948334068259,
1833            bid_id_str: Some("562948334068259".to_string()),
1834            ask_client_id: 363283,
1835            ask_client_id_str: Some("363283".to_string()),
1836            bid_client_id: 23004521241,
1837            bid_client_id_str: Some("23004521241".to_string()),
1838            ask_account_id: 57890,
1839            bid_account_id: 317068,
1840            is_maker_ask: false,
1841            block_height: 198321831,
1842            timestamp: 1773854156654,
1843            taker_fee: Some(196),
1844            taker_position_size_before: None,
1845            taker_entry_quote_before: None,
1846            taker_initial_margin_fraction_before: None,
1847            taker_position_sign_changed: None,
1848            maker_fee: Some(28),
1849            maker_position_size_before: None,
1850            maker_entry_quote_before: None,
1851            maker_initial_margin_fraction_before: None,
1852            maker_position_sign_changed: None,
1853            transaction_time: 1773854156686065,
1854            ask_account_pnl: None,
1855            bid_account_pnl: None,
1856        };
1857
1858        let tick = parse_ws_trade_tick(&trade, &instrument, UnixNanos::from(1)).unwrap();
1859
1860        assert_eq!(tick.trade_id.to_string(), "16164557907");
1861        assert_eq!(tick.price, Price::from("2181.83"));
1862    }
1863
1864    fn account_id() -> AccountId {
1865        AccountId::from("LIGHTER-1234")
1866    }
1867
1868    fn stub_order(status: LighterOrderStatus) -> LighterOrder {
1869        LighterOrder {
1870            order_index: 281476929510110,
1871            client_order_index: 42,
1872            order_id: "281476929510110".to_string(),
1873            client_order_id: "42".to_string(),
1874            market_index: 0,
1875            owner_account_index: 1234,
1876            initial_base_amount: Decimal::from_str("0.0050").unwrap(),
1877            price: Decimal::from_str("2352.74").unwrap(),
1878            nonce: 9182390020,
1879            remaining_base_amount: Decimal::from_str("0.0030").unwrap(),
1880            is_ask: true,
1881            base_size: 50,
1882            base_price: 235274,
1883            filled_base_amount: Decimal::from_str("0.0020").unwrap(),
1884            filled_quote_amount: Decimal::from_str("4.705480").unwrap(),
1885            side: Some(LighterOrderSide::Sell),
1886            order_type: LighterOrderKind::Limit,
1887            time_in_force: LighterOrderTimeInForce::GoodTillTime,
1888            reduce_only: false,
1889            trigger_price: Decimal::ZERO,
1890            order_expiry: 1_780_360_584_479,
1891            status,
1892            trigger_status: LighterTriggerStatus::Na,
1893            trigger_time: 0,
1894            parent_order_index: 0,
1895            parent_order_id: "0".to_string(),
1896            to_trigger_order_id_0: "0".to_string(),
1897            to_trigger_order_id_1: "0".to_string(),
1898            to_cancel_order_id_0: "0".to_string(),
1899            integrator_fee_collector_index: "0".to_string(),
1900            integrator_taker_fee: Decimal::ZERO,
1901            integrator_maker_fee: Decimal::ZERO,
1902            block_height: 227_535_532,
1903            timestamp: 1_777_941_383_576,
1904            created_at: 1_777_941_383_576,
1905            updated_at: 1_777_941_383_900,
1906            transaction_time: 1_777_941_383_576_735,
1907        }
1908    }
1909
1910    fn stub_account_trade(
1911        account_index: i64,
1912        is_maker_ask: bool,
1913        user_is_bidder: bool,
1914    ) -> LighterTrade {
1915        LighterTrade {
1916            trade_id: 19_209_006_902,
1917            trade_id_str: Some("19209006902".to_string()),
1918            tx_hash: "000000128b1ee814".to_string(),
1919            trade_type: LighterTradeType::Trade,
1920            market_id: 0,
1921            size: Decimal::from_str("0.1336").unwrap(),
1922            price: Decimal::from_str("2352.73").unwrap(),
1923            usd_amount: Decimal::from_str("314.324728").unwrap(),
1924            ask_id: 281_476_929_510_102,
1925            ask_id_str: Some("281476929510102".to_string()),
1926            bid_id: 562_947_905_631_053,
1927            bid_id_str: Some("562947905631053".to_string()),
1928            ask_client_id: 0,
1929            ask_client_id_str: Some("0".to_string()),
1930            bid_client_id: 7_001_011_966,
1931            bid_client_id_str: Some("7001011966".to_string()),
1932            ask_account_id: if user_is_bidder {
1933                91_249
1934            } else {
1935                account_index
1936            },
1937            bid_account_id: if user_is_bidder {
1938                account_index
1939            } else {
1940                91_249
1941            },
1942            is_maker_ask,
1943            block_height: 227_535_535,
1944            timestamp: 1_777_941_384_181,
1945            taker_fee: Some(196),
1946            taker_position_size_before: None,
1947            taker_entry_quote_before: None,
1948            taker_initial_margin_fraction_before: None,
1949            taker_position_sign_changed: None,
1950            maker_fee: Some(28),
1951            maker_position_size_before: None,
1952            maker_entry_quote_before: None,
1953            maker_initial_margin_fraction_before: None,
1954            maker_position_sign_changed: None,
1955            transaction_time: 1_777_941_384_181_586,
1956            ask_account_pnl: None,
1957            bid_account_pnl: None,
1958        }
1959    }
1960
1961    #[rstest]
1962    fn test_parse_ws_order_status_report_partial_fill_promotes_status() {
1963        let instrument = create_test_instrument();
1964        let order = stub_order(LighterOrderStatus::Open);
1965
1966        let report =
1967            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(7))
1968                .unwrap();
1969
1970        assert_eq!(report.venue_order_id.to_string(), "281476929510110");
1971        assert_eq!(report.client_order_id.unwrap().to_string(), "42");
1972        assert_eq!(report.order_side, OrderSide::Sell.into());
1973        assert_eq!(report.order_type, OrderType::Limit);
1974        // Open + filled_qty > 0 must surface as PartiallyFilled.
1975        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
1976        assert_eq!(report.filled_qty, Quantity::from("0.0020"));
1977        assert_eq!(report.quantity, Quantity::from("0.0050"));
1978        assert_eq!(report.price, Some(Price::from("2352.74")));
1979        assert_eq!(report.trigger_price, None);
1980        assert_eq!(report.time_in_force, TimeInForce::Gtd);
1981        assert!(report.expire_time.is_some());
1982        assert_eq!(report.ts_init, UnixNanos::from(7));
1983        assert_eq!(
1984            report.ts_accepted,
1985            UnixNanos::from(1_777_941_383_576_000_000),
1986        );
1987        assert_eq!(report.ts_last, UnixNanos::from(1_777_941_383_900_000_000));
1988    }
1989
1990    #[rstest]
1991    fn test_parse_ws_order_status_report_normalizes_second_scale_timestamps() {
1992        let instrument = create_test_instrument();
1993        // Mainnet order frames deliver `created_at`/`updated_at` in seconds,
1994        // while other frame sources use milliseconds.
1995        let mut order = stub_order(LighterOrderStatus::Open);
1996        order.timestamp = 1_777_941_383;
1997        order.created_at = 1_777_941_383;
1998        order.updated_at = 1_777_941_383;
1999
2000        let report =
2001            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(7))
2002                .unwrap();
2003
2004        assert_eq!(
2005            report.ts_accepted,
2006            UnixNanos::from(1_777_941_383_000_000_000),
2007        );
2008        assert_eq!(report.ts_last, UnixNanos::from(1_777_941_383_000_000_000),);
2009    }
2010
2011    #[rstest]
2012    fn test_parse_ws_order_status_report_pending_is_acknowledged() {
2013        let instrument = create_test_instrument();
2014        let mut order = stub_order(LighterOrderStatus::Pending);
2015        order.filled_base_amount = Decimal::ZERO;
2016
2017        let report =
2018            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(7))
2019                .unwrap();
2020
2021        assert_eq!(report.order_status, OrderStatus::Accepted);
2022    }
2023
2024    #[rstest]
2025    #[case::unfilled("0", OrderStatus::Rejected)]
2026    #[case::partially_filled("0.0020", OrderStatus::Canceled)]
2027    fn test_parse_ws_order_status_report_post_only_cancel(
2028        #[case] filled_qty: &str,
2029        #[case] expected: OrderStatus,
2030    ) {
2031        let instrument = create_test_instrument();
2032        let mut order = stub_order(LighterOrderStatus::CanceledPostOnly);
2033        order.filled_base_amount = Decimal::from_str(filled_qty).unwrap();
2034
2035        let report =
2036            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(1))
2037                .unwrap();
2038
2039        assert_eq!(report.order_status, expected);
2040        assert_eq!(report.cancel_reason.as_deref(), Some("post-only"));
2041    }
2042
2043    #[rstest]
2044    fn test_parse_ws_order_status_report_falls_back_to_is_ask() {
2045        let instrument = create_test_instrument();
2046        let mut order = stub_order(LighterOrderStatus::Open);
2047        order.side = None;
2048        order.is_ask = false;
2049
2050        let report =
2051            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(7))
2052                .unwrap();
2053
2054        assert_eq!(report.order_side, OrderSide::Buy.into());
2055    }
2056
2057    #[rstest]
2058    #[case(LighterOrderKind::StopLossLimit, LighterTriggerStatus::Na)]
2059    #[case(LighterOrderKind::TakeProfitLimit, LighterTriggerStatus::Na)]
2060    #[case(LighterOrderKind::StopLossLimit, LighterTriggerStatus::Ready)]
2061    #[case(LighterOrderKind::StopLoss, LighterTriggerStatus::Na)]
2062    #[case(LighterOrderKind::TakeProfit, LighterTriggerStatus::Na)]
2063    #[case(LighterOrderKind::StopLoss, LighterTriggerStatus::Ready)]
2064    fn conditional_open_reports_and_events_normalize_trigger(
2065        #[case] kind: LighterOrderKind,
2066        #[case] trigger_status: LighterTriggerStatus,
2067    ) {
2068        let instrument = create_test_instrument();
2069        let mut order = stub_order(LighterOrderStatus::Open);
2070        order.order_type = kind;
2071        order.filled_base_amount = Decimal::ZERO;
2072        order.trigger_status = trigger_status;
2073        order.trigger_price = Decimal::from(2300);
2074        let report =
2075            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(7))
2076                .unwrap();
2077
2078        let event = parse_lighter_order_event(
2079            &order,
2080            &instrument,
2081            &test_identity_for(report.order_type),
2082            test_cloid(),
2083            account_id(),
2084            test_trader_id(),
2085            OpenFrameContext {
2086                accepted_already_emitted: true,
2087                triggered_already_emitted: false,
2088                shape_changed: false,
2089            },
2090            UnixNanos::from(7),
2091        )
2092        .unwrap();
2093
2094        let replay = parse_lighter_order_event(
2095            &order,
2096            &instrument,
2097            &test_identity_for(report.order_type),
2098            test_cloid(),
2099            account_id(),
2100            test_trader_id(),
2101            OpenFrameContext {
2102                accepted_already_emitted: true,
2103                triggered_already_emitted: true,
2104                shape_changed: false,
2105            },
2106            UnixNanos::from(8),
2107        )
2108        .unwrap();
2109
2110        if TRIGGERABLE_ORDER_TYPES.contains(&report.order_type) {
2111            assert_eq!(report.order_status, OrderStatus::Triggered);
2112            assert!(
2113                matches!(event, Some(ParsedOrderEvent::Triggered(triggered)) if triggered.client_order_id == test_cloid())
2114            );
2115        } else {
2116            assert_eq!(report.order_status, OrderStatus::Accepted);
2117            assert!(event.is_none());
2118        }
2119
2120        assert!(replay.is_none());
2121    }
2122
2123    #[rstest]
2124    fn triggered_external_limit_without_trigger_price_reports_active_limit() {
2125        let instrument = create_test_instrument();
2126        let mut order = stub_order(LighterOrderStatus::Open);
2127        order.order_type = LighterOrderKind::TakeProfitLimit;
2128        order.filled_base_amount = Decimal::ZERO;
2129        order.trigger_status = LighterTriggerStatus::Na;
2130        order.trigger_price = Decimal::ZERO;
2131        let report =
2132            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(7))
2133                .unwrap();
2134        assert_eq!(report.order_type, OrderType::Limit);
2135        assert_eq!(report.order_status, OrderStatus::Accepted);
2136        assert_eq!(report.trigger_price, None);
2137        assert_eq!(report.price, Some(Price::from("2352.74")));
2138    }
2139
2140    #[rstest]
2141    fn test_parse_ws_order_status_report_omits_parent_order_id() {
2142        // Lighter's `parent_order_id` lives in the venue namespace; populating
2143        // Nautilus `OrderStatusReport::parent_order_id` (a `ClientOrderId`)
2144        // from it would mislabel namespaces. This guards against re-introducing
2145        // that mapping.
2146        let instrument = create_test_instrument();
2147        let mut order = stub_order(LighterOrderStatus::Open);
2148        order.parent_order_id = "999999".to_string();
2149        order.parent_order_index = 999_999;
2150
2151        let report =
2152            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(1))
2153                .unwrap();
2154
2155        assert!(report.parent_order_id.is_none());
2156        assert_eq!(report.contingency_type, None);
2157    }
2158
2159    #[rstest]
2160    #[case::stop_market(LighterOrderKind::StopLoss, OrderType::StopMarket)]
2161    #[case::stop_limit(LighterOrderKind::StopLossLimit, OrderType::StopLimit)]
2162    #[case::market_if_touched(LighterOrderKind::TakeProfit, OrderType::MarketIfTouched)]
2163    #[case::limit_if_touched(LighterOrderKind::TakeProfitLimit, OrderType::LimitIfTouched)]
2164    fn test_parse_ws_order_status_report_conditional_sets_default_trigger_type(
2165        #[case] lighter_order_type: LighterOrderKind,
2166        #[case] expected_order_type: OrderType,
2167    ) {
2168        let instrument = create_test_instrument();
2169        let mut order = stub_order(LighterOrderStatus::Open);
2170        order.order_type = lighter_order_type;
2171        order.trigger_price = Decimal::from_str("2200.00").unwrap();
2172
2173        let report =
2174            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(1))
2175                .unwrap();
2176
2177        assert_eq!(report.order_type, expected_order_type);
2178        assert_eq!(report.trigger_price, Some(Price::from("2200.00")));
2179        assert_eq!(report.trigger_type, Some(TriggerType::Default));
2180    }
2181
2182    #[rstest]
2183    #[case::ioc(
2184        LighterOrderTimeInForce::ImmediateOrCancel,
2185        0,
2186        TimeInForce::Ioc,
2187        None,
2188        false
2189    )]
2190    #[case::post_only_negative_expiry(
2191        LighterOrderTimeInForce::PostOnly,
2192        -1,
2193        TimeInForce::Gtc,
2194        None,
2195        true
2196    )]
2197    #[case::post_only_zero_expiry(
2198        LighterOrderTimeInForce::PostOnly,
2199        0,
2200        TimeInForce::Gtc,
2201        None,
2202        true
2203    )]
2204    #[case::post_only_positive_expiry(
2205        LighterOrderTimeInForce::PostOnly,
2206        1_780_000_000_000,
2207        TimeInForce::Gtd,
2208        Some(UnixNanos::from(1_780_000_000_000_000_000_u64)),
2209        true
2210    )]
2211    #[case::gtt_negative_expiry(LighterOrderTimeInForce::GoodTillTime, -1, TimeInForce::Gtc, None, false)]
2212    #[case::gtt_zero_expiry(
2213        LighterOrderTimeInForce::GoodTillTime,
2214        0,
2215        TimeInForce::Gtc,
2216        None,
2217        false
2218    )]
2219    #[case::gtt_positive_expiry(
2220        LighterOrderTimeInForce::GoodTillTime,
2221        1_780_000_000_000,
2222        TimeInForce::Gtd,
2223        Some(UnixNanos::from(1_780_000_000_000_000_000_u64)),
2224        false
2225    )]
2226    #[case::unknown(LighterOrderTimeInForce::Unknown, 0, TimeInForce::Gtc, None, false)]
2227    fn test_parse_ws_order_status_report_time_in_force_matrix(
2228        #[case] tif: LighterOrderTimeInForce,
2229        #[case] order_expiry: i64,
2230        #[case] expected_tif: TimeInForce,
2231        #[case] expected_expire_time: Option<UnixNanos>,
2232        #[case] expected_post_only: bool,
2233    ) {
2234        let instrument = create_test_instrument();
2235        let mut order = stub_order(LighterOrderStatus::Open);
2236        order.time_in_force = tif;
2237        order.order_expiry = order_expiry;
2238
2239        let report =
2240            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(1))
2241                .unwrap();
2242
2243        assert_eq!(report.time_in_force, expected_tif);
2244        assert_eq!(report.expire_time, expected_expire_time);
2245        assert_eq!(report.post_only, expected_post_only);
2246    }
2247
2248    #[rstest]
2249    #[case::active(LighterOrderStatus::Open, OrderStatus::Accepted)]
2250    #[case::terminal(LighterOrderStatus::Canceled, OrderStatus::Canceled)]
2251    fn test_parse_ws_post_only_expiry_is_consistent_across_statuses(
2252        #[case] status: LighterOrderStatus,
2253        #[case] expected_status: OrderStatus,
2254    ) {
2255        let instrument = create_test_instrument();
2256        let mut order = stub_order(status);
2257        order.time_in_force = LighterOrderTimeInForce::PostOnly;
2258        order.order_expiry = 1_780_000_000_000;
2259        order.filled_base_amount = Decimal::ZERO;
2260
2261        let report =
2262            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(1))
2263                .unwrap();
2264
2265        assert_eq!(report.order_status, expected_status);
2266        assert_eq!(report.time_in_force, TimeInForce::Gtd);
2267        assert_eq!(
2268            report.expire_time,
2269            Some(UnixNanos::from(1_780_000_000_000_000_000_u64))
2270        );
2271        assert!(report.post_only);
2272    }
2273
2274    #[rstest]
2275    fn test_parse_ws_order_status_report_rejects_twap() {
2276        let instrument = create_test_instrument();
2277        let mut order = stub_order(LighterOrderStatus::Open);
2278        order.order_type = LighterOrderKind::Twap;
2279
2280        let err =
2281            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(1))
2282                .unwrap_err();
2283
2284        assert!(
2285            err.to_string()
2286                .contains("no Nautilus order-type equivalent")
2287        );
2288    }
2289
2290    // Liquidity side is decided by `user_is_asker == trade.is_maker_ask`:
2291    // when the user sat on the same side that rested as the maker, they
2292    // were the maker; otherwise they crossed the book as the taker. The
2293    // four combinations exhaustively cover that branch.
2294    #[rstest]
2295    #[case::bidder_maker_ask_is_taker(
2296        true,
2297        true,
2298        OrderSide::Buy,
2299        LiquiditySide::Taker,
2300        "0.06160765 USDC"
2301    )]
2302    #[case::asker_maker_ask_is_maker(
2303        false,
2304        true,
2305        OrderSide::Sell,
2306        LiquiditySide::Maker,
2307        "0.00880109 USDC"
2308    )]
2309    #[case::bidder_maker_bid_is_maker(
2310        true,
2311        false,
2312        OrderSide::Buy,
2313        LiquiditySide::Maker,
2314        "0.00880109 USDC"
2315    )]
2316    #[case::asker_maker_bid_is_taker(
2317        false,
2318        false,
2319        OrderSide::Sell,
2320        LiquiditySide::Taker,
2321        "0.06160765 USDC"
2322    )]
2323    fn test_parse_ws_fill_report_liquidity_side_matrix(
2324        #[case] user_is_bidder: bool,
2325        #[case] is_maker_ask: bool,
2326        #[case] expected_side: OrderSide,
2327        #[case] expected_liquidity: LiquiditySide,
2328        #[case] expected_commission: &str,
2329    ) {
2330        let instrument = create_test_instrument();
2331        let trade = stub_account_trade(1234, is_maker_ask, user_is_bidder);
2332
2333        let report =
2334            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(9))
2335                .unwrap()
2336                .expect("user-side fill");
2337
2338        assert_eq!(report.order_side, expected_side);
2339        assert_eq!(report.liquidity_side, expected_liquidity);
2340        assert_eq!(report.last_qty, Quantity::from("0.1336"));
2341        assert_eq!(report.last_px, Price::from("2352.73"));
2342        assert_eq!(report.commission, Money::from(expected_commission));
2343        let expected_voi = if user_is_bidder {
2344            "562947905631053"
2345        } else {
2346            "281476929510102"
2347        };
2348        assert_eq!(report.venue_order_id.to_string(), expected_voi);
2349    }
2350
2351    #[rstest]
2352    #[case::larger_size("0.2672", "2352.73", Some(196), "0.12321529 USDC")]
2353    #[case::higher_price("0.1336", "4705.46", Some(196), "0.12321529 USDC")]
2354    #[case::small_notional("0.0001", "2352.73", Some(196), "0.00004611 USDC")]
2355    #[case::missing_fee("0.1336", "2352.73", None, "0 USDC")]
2356    #[case::zero_fee("0.1336", "2352.73", Some(0), "0 USDC")]
2357    fn test_fill_commission_scales_with_notional(
2358        #[case] size: &str,
2359        #[case] price: &str,
2360        #[case] fee: Option<i32>,
2361        #[case] expected: &str,
2362    ) {
2363        let instrument = create_test_instrument();
2364        let mut trade = stub_account_trade(1234, true, true);
2365        trade.size = Decimal::from_str(size).unwrap();
2366        trade.price = Decimal::from_str(price).unwrap();
2367        trade.taker_fee = fee;
2368
2369        let report =
2370            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(1))
2371                .unwrap()
2372                .expect("user-side fill");
2373        let filled = parse_lighter_order_filled(
2374            &trade,
2375            &instrument,
2376            &test_identity(),
2377            test_cloid(),
2378            account_id(),
2379            test_trader_id(),
2380            1234,
2381            UnixNanos::from(1),
2382        )
2383        .unwrap()
2384        .expect("user-side fill");
2385
2386        assert_eq!(report.commission, Money::from(expected));
2387        assert_eq!(filled.commission, Some(report.commission));
2388    }
2389
2390    #[rstest]
2391    fn test_lighter_fee_to_commission_rejects_overflow() {
2392        let mut trade = stub_account_trade(1234, true, true);
2393        trade.size = Decimal::MAX;
2394        trade.price = Decimal::MAX;
2395
2396        let err = lighter_fee_to_commission(Some(196), &trade, Currency::USDC()).unwrap_err();
2397
2398        assert_eq!(err.detail, "overflow calculating fee amount");
2399    }
2400
2401    #[rstest]
2402    fn test_parse_ws_fill_report_skips_other_accounts() {
2403        let instrument = create_test_instrument();
2404        let trade = stub_account_trade(9999, false, true);
2405
2406        let report =
2407            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(1))
2408                .unwrap();
2409
2410        assert!(report.is_none());
2411    }
2412
2413    // When the venue drops the `*_id_str` field (the typed numeric fields are
2414    // always populated), the parser must fall back to stringifying the i64
2415    // mirror to seed VenueOrderId. Pins the numeric-fallback branch in
2416    // `venue_order_id_from`; the matrix above always populates the strings.
2417    #[rstest]
2418    fn test_parse_ws_fill_report_venue_order_id_falls_back_to_numeric() {
2419        let instrument = create_test_instrument();
2420        let mut trade = stub_account_trade(1234, false, true);
2421        trade.bid_id_str = None;
2422        trade.ask_id_str = None;
2423
2424        let report =
2425            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(1))
2426                .unwrap()
2427                .expect("user-side fill");
2428
2429        // user_is_bidder=true => VenueOrderId derives from bid_id.
2430        assert_eq!(report.venue_order_id.to_string(), "562947905631053");
2431    }
2432
2433    // Same fallback contract for `client_order_id_from`: when `*_client_id_str`
2434    // is absent but the numeric mirror is non-zero, the cloid must surface as
2435    // the numeric value; when both string is absent and numeric is zero, the
2436    // cloid is `None`.
2437    #[rstest]
2438    fn test_parse_ws_fill_report_client_order_id_falls_back_to_numeric() {
2439        let instrument = create_test_instrument();
2440        let mut trade = stub_account_trade(1234, false, true);
2441        trade.bid_client_id_str = None;
2442        trade.ask_client_id_str = None;
2443
2444        let report =
2445            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(1))
2446                .unwrap()
2447                .expect("user-side fill");
2448
2449        // user_is_bidder=true with bid_client_id=7_001_011_966 (non-zero).
2450        assert_eq!(report.client_order_id.unwrap().to_string(), "7001011966");
2451    }
2452
2453    #[rstest]
2454    fn test_parse_ws_fill_report_client_order_id_absent_when_zero_numeric() {
2455        let instrument = create_test_instrument();
2456        // user_is_bidder=false => looks at ask_client_id, which is 0 in the stub.
2457        let mut trade = stub_account_trade(1234, true, false);
2458        trade.ask_client_id_str = None;
2459
2460        let report =
2461            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(1))
2462                .unwrap()
2463                .expect("user-side fill");
2464
2465        assert!(report.client_order_id.is_none());
2466    }
2467
2468    #[rstest]
2469    fn test_parse_ws_fill_report_client_order_id_absent_when_string_is_zero_sentinel() {
2470        let instrument = create_test_instrument();
2471        // user_is_bidder=false => looks at ask_client_id_str, which is "0" in the stub.
2472        let trade = stub_account_trade(1234, true, false);
2473
2474        let report =
2475            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(1))
2476                .unwrap()
2477                .expect("user-side fill");
2478
2479        assert!(report.client_order_id.is_none());
2480    }
2481
2482    #[rstest]
2483    #[case::missing(None)]
2484    #[case::zero(Some(0))]
2485    fn test_parse_ws_fill_report_handles_zero_fee(#[case] fee: Option<i32>) {
2486        let instrument = create_test_instrument();
2487        let mut trade = stub_account_trade(1234, true, true);
2488        trade.taker_fee = fee;
2489        trade.maker_fee = fee;
2490
2491        let report =
2492            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(1))
2493                .unwrap()
2494                .expect("user-side fill");
2495
2496        assert_eq!(report.commission, Money::from("0 USDC"));
2497    }
2498
2499    #[rstest]
2500    fn test_parse_ws_fill_report_uses_instrument_quote_currency_for_fee() {
2501        let currency = Currency::USDG();
2502        let instrument =
2503            create_test_instrument_with_quote(Venue::new("LIGHTER_ROBINHOOD"), currency);
2504
2505        let trade = stub_account_trade(1234, true, true);
2506
2507        let report =
2508            parse_ws_fill_report(&trade, 1234, &instrument, account_id(), UnixNanos::from(1))
2509                .unwrap()
2510                .expect("user-side fill");
2511
2512        assert_eq!(report.commission, Money::from("0.06160765 USDG"));
2513    }
2514
2515    #[rstest]
2516    fn test_parse_ws_position_status_report_long_position() {
2517        let instrument = create_test_instrument();
2518        let position = LighterPosition {
2519            market_id: 0,
2520            symbol: Ustr::from("ETH"),
2521            initial_margin_fraction: Decimal::from_str("0.0500").unwrap(),
2522            open_order_count: 1,
2523            pending_order_count: 0,
2524            position_tied_order_count: 0,
2525            sign: 1,
2526            position: Decimal::from_str("1.5000").unwrap(),
2527            avg_entry_price: Decimal::from_str("2350.10").unwrap(),
2528            position_value: Decimal::from_str("3525.15").unwrap(),
2529            unrealized_pnl: Decimal::from_str("3.45").unwrap(),
2530            realized_pnl: Decimal::ZERO,
2531            liquidation_price: Decimal::from_str("1900.123456789123456789").unwrap(),
2532            total_funding_paid_out: Some(Decimal::from_str("0.05").unwrap()),
2533            margin_mode: 0,
2534            allocated_margin: Decimal::from_str("176.25").unwrap(),
2535            total_discount: Some(Decimal::ZERO),
2536        };
2537
2538        let report = parse_ws_position_status_report(
2539            &position,
2540            &instrument,
2541            account_id(),
2542            UnixNanos::from(50),
2543            UnixNanos::from(70),
2544        )
2545        .unwrap();
2546
2547        assert_eq!(report.position_side, PositionSide::Long);
2548        assert_eq!(report.quantity, Quantity::from("1.5000"));
2549        assert_eq!(report.signed_decimal_qty, Decimal::new(15, 1));
2550        assert_eq!(report.avg_px_open, Some(Decimal::new(235010, 2)));
2551        assert_eq!(report.account_id, account_id());
2552        assert_eq!(report.instrument_id, instrument.id());
2553        assert_eq!(report.ts_last, UnixNanos::from(50));
2554        assert_eq!(report.ts_init, UnixNanos::from(70));
2555        assert_eq!(report.venue_position_id, None);
2556        assert_eq!(
2557            report.avg_px_open_reconciliation,
2558            AvgPxReconciliation::Match
2559        );
2560        assert_eq!(report.avg_px_open_precision, None);
2561        assert_eq!(
2562            report.liquidation_price,
2563            Some(Decimal::from_str("1900.123456789123456789").unwrap()),
2564        );
2565    }
2566
2567    #[rstest]
2568    fn test_parse_ws_position_status_report_short_position() {
2569        let instrument = create_test_instrument();
2570        let position = LighterPosition {
2571            market_id: 0,
2572            symbol: Ustr::from("ETH"),
2573            initial_margin_fraction: Decimal::from_str("0.0500").unwrap(),
2574            open_order_count: 0,
2575            pending_order_count: 0,
2576            position_tied_order_count: 0,
2577            sign: -1,
2578            position: Decimal::from_str("0.7500").unwrap(),
2579            avg_entry_price: Decimal::from_str("2400.00").unwrap(),
2580            position_value: Decimal::from_str("1800.00").unwrap(),
2581            unrealized_pnl: Decimal::ZERO,
2582            realized_pnl: Decimal::ZERO,
2583            liquidation_price: Decimal::from_str("3000.00").unwrap(),
2584            total_funding_paid_out: None,
2585            margin_mode: 0,
2586            allocated_margin: Decimal::from_str("90.00").unwrap(),
2587            total_discount: None,
2588        };
2589
2590        let report = parse_ws_position_status_report(
2591            &position,
2592            &instrument,
2593            account_id(),
2594            UnixNanos::default(),
2595            UnixNanos::default(),
2596        )
2597        .unwrap();
2598
2599        assert_eq!(report.position_side, PositionSide::Short);
2600        assert_eq!(report.quantity, Quantity::from("0.7500"));
2601        assert_eq!(report.signed_decimal_qty, Decimal::new(-75, 2));
2602        assert_eq!(report.account_id, account_id());
2603        assert_eq!(report.instrument_id, instrument.id());
2604        assert_eq!(report.ts_last, UnixNanos::default());
2605        assert_eq!(report.ts_init, UnixNanos::default());
2606        assert_eq!(report.venue_position_id, None);
2607        assert_eq!(report.avg_px_open, Some(Decimal::new(240000, 2)));
2608        assert_eq!(
2609            report.avg_px_open_reconciliation,
2610            AvgPxReconciliation::Match
2611        );
2612        assert_eq!(report.avg_px_open_precision, None);
2613        assert_eq!(report.liquidation_price, Some(Decimal::new(300000, 2)));
2614    }
2615
2616    #[rstest]
2617    fn test_parse_ws_position_status_report_flat_position() {
2618        let instrument = create_test_instrument();
2619        let position = LighterPosition {
2620            market_id: 0,
2621            symbol: Ustr::from("ETH"),
2622            initial_margin_fraction: Decimal::from_str("0.0500").unwrap(),
2623            open_order_count: 0,
2624            pending_order_count: 0,
2625            position_tied_order_count: 0,
2626            sign: 0,
2627            position: Decimal::ZERO,
2628            avg_entry_price: Decimal::ZERO,
2629            position_value: Decimal::ZERO,
2630            unrealized_pnl: Decimal::ZERO,
2631            realized_pnl: Decimal::ZERO,
2632            liquidation_price: Decimal::ZERO,
2633            total_funding_paid_out: None,
2634            margin_mode: 0,
2635            allocated_margin: Decimal::ZERO,
2636            total_discount: None,
2637        };
2638
2639        let report = parse_ws_position_status_report(
2640            &position,
2641            &instrument,
2642            account_id(),
2643            UnixNanos::default(),
2644            UnixNanos::default(),
2645        )
2646        .unwrap();
2647
2648        assert_eq!(report.position_side, PositionSide::Flat);
2649        assert!(report.quantity.is_zero());
2650        assert_eq!(report.signed_decimal_qty, Decimal::ZERO);
2651        assert!(report.avg_px_open.is_none());
2652        assert_eq!(report.account_id, account_id());
2653        assert_eq!(report.instrument_id, instrument.id());
2654        assert_eq!(report.ts_last, UnixNanos::default());
2655        assert_eq!(report.ts_init, UnixNanos::default());
2656        assert_eq!(report.venue_position_id, None);
2657        assert_eq!(
2658            report.avg_px_open_reconciliation,
2659            AvgPxReconciliation::Match
2660        );
2661        assert_eq!(report.avg_px_open_precision, None);
2662        assert_eq!(report.liquidation_price, Some(Decimal::ZERO));
2663    }
2664
2665    #[rstest]
2666    fn test_account_balance_from_lighter_asset_spot_only() {
2667        // Asset with only a spot balance (margin_balance=0): perp leg is
2668        // empty so total == spot balance, locked == locked_balance only.
2669        let asset = LighterAsset {
2670            symbol: Ustr::from("USDC"),
2671            asset_id: 0,
2672            balance: Decimal::from_str("100.000000").unwrap(),
2673            locked_balance: Decimal::from_str("1.000000").unwrap(),
2674            margin_balance: Decimal::ZERO,
2675            margin_mode: Ustr::default(),
2676        };
2677
2678        let balance = account_balance_from_lighter_asset(&asset).unwrap();
2679        let usdc = Currency::get_or_create_crypto("USDC");
2680        assert_eq!(balance.currency, usdc);
2681        assert_eq!(balance.total, Money::from("100.000000 USDC"));
2682        assert_eq!(balance.locked, Money::from("1.000000 USDC"));
2683        assert_eq!(balance.free, Money::from("99.000000 USDC"));
2684    }
2685
2686    #[rstest]
2687    fn test_account_balance_from_lighter_asset_combines_spot_and_perp() {
2688        // Worked example: 10 USDC sitting on spot, 40 USDC pledged as
2689        // perp collateral, no resting spot orders. Lighter runs unified
2690        // margin: both legs are deployable equity, so the merged view
2691        // is total=50, locked=0, free=50. Perp margin currently in use
2692        // is tracked separately via MarginBalance, not via locked here.
2693        let asset = LighterAsset {
2694            symbol: Ustr::from("USDC"),
2695            asset_id: 3,
2696            balance: Decimal::from_str("10.000000").unwrap(),
2697            locked_balance: Decimal::ZERO,
2698            margin_balance: Decimal::from_str("40.000000").unwrap(),
2699            margin_mode: Ustr::from("disabled"),
2700        };
2701
2702        let balance = account_balance_from_lighter_asset(&asset).unwrap();
2703        assert_eq!(balance.total, Money::from("50.000000 USDC"));
2704        assert_eq!(balance.locked, Money::from("0 USDC"));
2705        assert_eq!(balance.free, Money::from("50.000000 USDC"));
2706    }
2707
2708    #[rstest]
2709    fn test_account_balance_from_lighter_asset_locks_only_spot_order_reservation() {
2710        // A resting spot limit order locks 1 USDC. total still reflects
2711        // both legs (10 + 40 = 50); locked tracks the spot reservation
2712        // only, free = 49.
2713        let asset = LighterAsset {
2714            symbol: Ustr::from("USDC"),
2715            asset_id: 3,
2716            balance: Decimal::from_str("10.000000").unwrap(),
2717            locked_balance: Decimal::from_str("1.000000").unwrap(),
2718            margin_balance: Decimal::from_str("40.000000").unwrap(),
2719            margin_mode: Ustr::from("disabled"),
2720        };
2721
2722        let balance = account_balance_from_lighter_asset(&asset).unwrap();
2723        assert_eq!(balance.total, Money::from("50.000000 USDC"));
2724        assert_eq!(balance.locked, Money::from("1.000000 USDC"));
2725        assert_eq!(balance.free, Money::from("49.000000 USDC"));
2726    }
2727
2728    #[rstest]
2729    fn test_margin_balance_from_user_stats_no_positions() {
2730        // 40 USDC collateral, 40 available, no positions open: both initial
2731        // and maintenance must be zero; strategies should see "full
2732        // collateral free to deploy".
2733        let stats = LighterUserStats {
2734            account_trading_mode: 0,
2735            available_balance: Decimal::from_str("40.000000").unwrap(),
2736            buying_power: Decimal::ZERO,
2737            collateral: Decimal::from_str("40.000000").unwrap(),
2738            leverage: Decimal::ZERO,
2739            margin_usage: Decimal::ZERO,
2740            portfolio_value: Decimal::from_str("40.000000").unwrap(),
2741            cross_stats: None,
2742            total_stats: None,
2743        };
2744
2745        let margin = margin_balance_from_user_stats(&stats).unwrap();
2746        let usdc = Currency::get_or_create_crypto("USDC");
2747        assert_eq!(margin.currency, usdc);
2748        assert_eq!(margin.initial, Money::from("0 USDC"));
2749        assert_eq!(margin.maintenance, Money::from("0 USDC"));
2750        assert_eq!(margin.instrument_id, None);
2751    }
2752
2753    #[rstest]
2754    fn test_margin_balance_from_user_stats_with_position() {
2755        // 40 USDC collateral, 35 available -> 5 USDC initial margin in use.
2756        // Maintenance is always 0 here: Lighter's `margin_usage` is an
2757        // initial-margin-usage percent, not a maintenance ratio, so we
2758        // don't derive maintenance from `user_stats` at all (see comment
2759        // on `margin_balance_from_user_stats`).
2760        let stats = LighterUserStats {
2761            account_trading_mode: 0,
2762            available_balance: Decimal::from_str("35.000000").unwrap(),
2763            buying_power: Decimal::from_str("100.000000").unwrap(),
2764            collateral: Decimal::from_str("40.000000").unwrap(),
2765            leverage: Decimal::from_str("5.00").unwrap(),
2766            margin_usage: Decimal::from_str("12.50").unwrap(),
2767            portfolio_value: Decimal::from_str("40.000000").unwrap(),
2768            cross_stats: None,
2769            total_stats: None,
2770        };
2771
2772        let margin = margin_balance_from_user_stats(&stats).unwrap();
2773        assert_eq!(margin.initial, Money::from("5.000000 USDC"));
2774        assert_eq!(margin.maintenance, Money::from("0 USDC"));
2775    }
2776
2777    #[rstest]
2778    fn test_build_unified_account_state_emits_margin_account() {
2779        let asset = LighterAsset {
2780            symbol: Ustr::from("USDC"),
2781            asset_id: 3,
2782            balance: Decimal::from_str("10.000000").unwrap(),
2783            locked_balance: Decimal::ZERO,
2784            margin_balance: Decimal::from_str("40.000000").unwrap(),
2785            margin_mode: Ustr::from("disabled"),
2786        };
2787        let balances = vec![account_balance_from_lighter_asset(&asset).unwrap()];
2788
2789        let stats = LighterUserStats {
2790            account_trading_mode: 0,
2791            available_balance: Decimal::from_str("40.000000").unwrap(),
2792            buying_power: Decimal::ZERO,
2793            collateral: Decimal::from_str("40.000000").unwrap(),
2794            leverage: Decimal::ZERO,
2795            margin_usage: Decimal::ZERO,
2796            portfolio_value: Decimal::from_str("40.000000").unwrap(),
2797            cross_stats: None,
2798            total_stats: None,
2799        };
2800        let margin = margin_balance_from_user_stats(&stats).unwrap();
2801
2802        let state = build_unified_account_state(
2803            balances,
2804            Some(margin),
2805            account_id(),
2806            UnixNanos::from(1_000),
2807            UnixNanos::from(1_001),
2808        );
2809
2810        let usdc = Currency::get_or_create_crypto("USDC");
2811        assert_eq!(state.account_id, account_id());
2812        assert_eq!(state.account_type, AccountType::Margin);
2813        assert_eq!(state.base_currency, None);
2814        assert!(state.is_reported);
2815        assert_eq!(state.balances.len(), 1);
2816        assert_eq!(state.balances[0].total, Money::from("50.000000 USDC"));
2817        assert_eq!(state.balances[0].locked, Money::from("0 USDC"));
2818        assert_eq!(state.balances[0].free, Money::from("50.000000 USDC"));
2819        assert_eq!(state.margins.len(), 1);
2820        assert_eq!(state.margins[0].currency, usdc);
2821        assert_eq!(state.margins[0].initial, Money::from("0 USDC"));
2822        assert!(state.margins[0].instrument_id.is_none());
2823    }
2824
2825    fn stub_candle() -> LighterWsCandle {
2826        LighterWsCandle {
2827            t: 1_778_821_440_000,
2828            o: Decimal::new(226_420, 2),
2829            h: Decimal::new(226_434, 2),
2830            l: Decimal::new(226_336, 2),
2831            c: Decimal::new(226_397, 2),
2832            v: Decimal::new(132_237, 4),
2833            quote_volume: Decimal::ZERO,
2834            i: 0,
2835        }
2836    }
2837
2838    #[rstest]
2839    fn test_parse_ws_bar_emits_open_timestamp_and_external_last_spec() {
2840        let instrument = create_test_instrument();
2841        let candle = stub_candle();
2842
2843        let bar = parse_ws_bar(
2844            &instrument,
2845            &candle,
2846            LighterCandleResolution::OneMinute,
2847            UnixNanos::from(99_999),
2848        )
2849        .unwrap();
2850
2851        assert_eq!(bar.bar_type.instrument_id(), instrument.id());
2852        assert_eq!(bar.bar_type.spec().step.get(), 1);
2853        assert_eq!(bar.bar_type.spec().aggregation, BarAggregation::Minute);
2854        assert_eq!(bar.bar_type.spec().price_type, PriceType::Last);
2855        assert_eq!(
2856            bar.bar_type.aggregation_source(),
2857            AggregationSource::External
2858        );
2859        assert_eq!(bar.open, Price::from("2264.20"));
2860        assert_eq!(bar.high, Price::from("2264.34"));
2861        assert_eq!(bar.low, Price::from("2263.36"));
2862        assert_eq!(bar.close, Price::from("2263.97"));
2863        assert_eq!(bar.volume, Quantity::from("13.2237"));
2864        assert_eq!(bar.ts_event, UnixNanos::from(1_778_821_440_000_000_000));
2865        assert_eq!(bar.ts_init, UnixNanos::from(99_999));
2866    }
2867
2868    #[rstest]
2869    fn test_parse_ws_bar_rejects_negative_timestamp() {
2870        let instrument = create_test_instrument();
2871        let mut candle = stub_candle();
2872        candle.t = -1;
2873
2874        let err = parse_ws_bar(
2875            &instrument,
2876            &candle,
2877            LighterCandleResolution::OneMinute,
2878            UnixNanos::default(),
2879        )
2880        .unwrap_err();
2881
2882        assert!(
2883            err.to_string().contains("negative candle timestamp"),
2884            "expected negative-timestamp error, was: {err}",
2885        );
2886    }
2887
2888    fn test_identity() -> OrderIdentity {
2889        test_identity_for(OrderType::Limit)
2890    }
2891
2892    fn test_identity_for(order_type: OrderType) -> OrderIdentity {
2893        OrderIdentity::new(
2894            create_test_instrument().id(),
2895            StrategyId::new("S-TEST"),
2896            OrderSide::Sell,
2897            order_type,
2898            1,
2899        )
2900    }
2901
2902    fn test_trader_id() -> TraderId {
2903        TraderId::new("TRADER-001")
2904    }
2905
2906    fn test_cloid() -> ClientOrderId {
2907        ClientOrderId::new("MY-ORDER-001")
2908    }
2909
2910    #[rstest]
2911    fn parse_lighter_order_event_emits_accepted_on_open() {
2912        let instrument = create_test_instrument();
2913        let mut order = stub_order(LighterOrderStatus::Open);
2914        order.filled_base_amount = Decimal::ZERO;
2915
2916        let event = parse_lighter_order_event(
2917            &order,
2918            &instrument,
2919            &test_identity(),
2920            test_cloid(),
2921            account_id(),
2922            test_trader_id(),
2923            OpenFrameContext {
2924                accepted_already_emitted: false,
2925                triggered_already_emitted: false,
2926                shape_changed: false,
2927            },
2928            UnixNanos::from(7),
2929        )
2930        .unwrap()
2931        .expect("Open with no prior accept emits Accepted");
2932
2933        match event {
2934            ParsedOrderEvent::Accepted(e) => {
2935                assert_eq!(e.client_order_id, test_cloid());
2936                assert_eq!(e.venue_order_id.to_string(), "281476929510110");
2937            }
2938            other => panic!("expected Accepted, was {other:?}"),
2939        }
2940    }
2941
2942    #[rstest]
2943    fn parse_lighter_order_event_emits_accepted_on_pending() {
2944        let instrument = create_test_instrument();
2945        let order = stub_order(LighterOrderStatus::Pending);
2946
2947        let event = parse_lighter_order_event(
2948            &order,
2949            &instrument,
2950            &test_identity(),
2951            test_cloid(),
2952            account_id(),
2953            test_trader_id(),
2954            OpenFrameContext {
2955                accepted_already_emitted: false,
2956                triggered_already_emitted: false,
2957                shape_changed: false,
2958            },
2959            UnixNanos::from(7),
2960        )
2961        .unwrap()
2962        .expect("Pending is venue-acknowledged and emits Accepted");
2963
2964        assert!(matches!(event, ParsedOrderEvent::Accepted(_)));
2965    }
2966
2967    #[rstest]
2968    fn parse_lighter_order_event_emits_updated_on_pending_shape_change() {
2969        let instrument = create_test_instrument();
2970        let mut order = stub_order(LighterOrderStatus::Pending);
2971        order.order_type = LighterOrderKind::StopLossLimit;
2972        order.trigger_price = Decimal::from_str("2300.00").unwrap();
2973
2974        let event = parse_lighter_order_event(
2975            &order,
2976            &instrument,
2977            &test_identity_for(OrderType::StopLimit),
2978            test_cloid(),
2979            account_id(),
2980            test_trader_id(),
2981            OpenFrameContext {
2982                accepted_already_emitted: true,
2983                triggered_already_emitted: false,
2984                shape_changed: true,
2985            },
2986            UnixNanos::from(7),
2987        )
2988        .unwrap()
2989        .expect("modified Pending order emits Updated");
2990
2991        match event {
2992            ParsedOrderEvent::Updated(event) => {
2993                assert_eq!(event.price, Some(Price::from("2352.74")));
2994                assert_eq!(event.trigger_price, Some(Price::from("2300.00")));
2995            }
2996            other => panic!("expected Updated, was {other:?}"),
2997        }
2998    }
2999
3000    #[rstest]
3001    fn parse_lighter_order_event_pending_ready_does_not_emit_triggered() {
3002        let instrument = create_test_instrument();
3003        let mut order = stub_order(LighterOrderStatus::Pending);
3004        order.trigger_status = LighterTriggerStatus::Ready;
3005
3006        let event = parse_lighter_order_event(
3007            &order,
3008            &instrument,
3009            &test_identity_for(OrderType::StopLimit),
3010            test_cloid(),
3011            account_id(),
3012            test_trader_id(),
3013            OpenFrameContext {
3014                accepted_already_emitted: false,
3015                triggered_already_emitted: false,
3016                shape_changed: false,
3017            },
3018            UnixNanos::from(7),
3019        )
3020        .unwrap()
3021        .expect("Pending Ready still emits its acknowledgement");
3022
3023        assert!(matches!(event, ParsedOrderEvent::Accepted(_)));
3024    }
3025
3026    #[rstest]
3027    fn parse_lighter_order_event_emits_updated_only_when_shape_changed() {
3028        // Lighter's modify-as-restate: the venue echoes the modified order
3029        // as `Open`. Updated must fire only when the shape (qty / price /
3030        // trigger) actually changed; otherwise repeat `Open` echoes
3031        // (partial-fill snapshots, reconnect replays) would mint spurious
3032        // modify events.
3033        let instrument = create_test_instrument();
3034        let order = stub_order(LighterOrderStatus::Open);
3035
3036        let event = parse_lighter_order_event(
3037            &order,
3038            &instrument,
3039            &test_identity(),
3040            test_cloid(),
3041            account_id(),
3042            test_trader_id(),
3043            OpenFrameContext {
3044                accepted_already_emitted: true,
3045                triggered_already_emitted: false,
3046                shape_changed: true,
3047            },
3048            UnixNanos::from(7),
3049        )
3050        .unwrap()
3051        .expect("Open with shape_changed emits Updated");
3052
3053        match event {
3054            ParsedOrderEvent::Updated(e) => {
3055                assert_eq!(e.client_order_id, test_cloid());
3056                assert_eq!(e.quantity, Quantity::from("0.0050"));
3057                assert_eq!(e.price, Some(Price::from("2352.74")));
3058            }
3059            other => panic!("expected Updated, was {other:?}"),
3060        }
3061    }
3062
3063    #[rstest]
3064    fn parse_lighter_order_event_repeat_open_after_accept_is_silent() {
3065        // Without a shape change, a repeat `Open` for an already-accepted
3066        // tracked order must return `None` so partial-fill snapshots and
3067        // reconnect replays do not flood the engine with phantom updates.
3068        let instrument = create_test_instrument();
3069        let order = stub_order(LighterOrderStatus::Open);
3070
3071        let event = parse_lighter_order_event(
3072            &order,
3073            &instrument,
3074            &test_identity(),
3075            test_cloid(),
3076            account_id(),
3077            test_trader_id(),
3078            OpenFrameContext {
3079                accepted_already_emitted: true,
3080                triggered_already_emitted: false,
3081                shape_changed: false,
3082            },
3083            UnixNanos::from(7),
3084        )
3085        .unwrap();
3086
3087        assert!(event.is_none());
3088    }
3089
3090    #[rstest]
3091    fn parse_lighter_order_event_triggered_dedup_via_open_ctx() {
3092        // A subsequent `Open` frame after `Triggered` already fired must
3093        // not re-emit `Triggered`. The dispatcher tracks this via the
3094        // `triggered_already_emitted` flag.
3095        let instrument = create_test_instrument();
3096        let mut order = stub_order(LighterOrderStatus::Open);
3097        order.trigger_status = LighterTriggerStatus::Ready;
3098
3099        let event = parse_lighter_order_event(
3100            &order,
3101            &instrument,
3102            &test_identity(),
3103            test_cloid(),
3104            account_id(),
3105            test_trader_id(),
3106            OpenFrameContext {
3107                accepted_already_emitted: true,
3108                triggered_already_emitted: true,
3109                shape_changed: false,
3110            },
3111            UnixNanos::from(7),
3112        )
3113        .unwrap();
3114
3115        // After triggered_already_emitted and accepted_already_emitted,
3116        // with no shape change, the frame is silent.
3117        assert!(event.is_none());
3118    }
3119
3120    #[rstest]
3121    fn parse_lighter_order_event_emits_triggered_after_accept() {
3122        // A conditional order's trigger can fire AFTER the initial accept
3123        // landed. The Open frame's `trigger_status = Ready` must produce
3124        // `Triggered` regardless of `accepted_already_emitted`.
3125        let instrument = create_test_instrument();
3126        let mut order = stub_order(LighterOrderStatus::Open);
3127        order.order_type = LighterOrderKind::StopLossLimit;
3128        order.trigger_price = Decimal::from(2300);
3129        order.trigger_status = LighterTriggerStatus::Ready;
3130
3131        let event = parse_lighter_order_event(
3132            &order,
3133            &instrument,
3134            &test_identity_for(OrderType::StopLimit),
3135            test_cloid(),
3136            account_id(),
3137            test_trader_id(),
3138            OpenFrameContext {
3139                accepted_already_emitted: true,
3140                triggered_already_emitted: false,
3141                shape_changed: false,
3142            },
3143            UnixNanos::from(7),
3144        )
3145        .unwrap()
3146        .expect("trigger Ready after accept emits Triggered");
3147
3148        match event {
3149            ParsedOrderEvent::Triggered(_) => {}
3150            other => panic!("expected Triggered, was {other:?}"),
3151        }
3152    }
3153
3154    #[rstest]
3155    fn parse_lighter_order_event_emits_triggered_when_trigger_ready_fresh() {
3156        let instrument = create_test_instrument();
3157        let mut order = stub_order(LighterOrderStatus::Open);
3158        order.filled_base_amount = Decimal::ZERO;
3159        order.order_type = LighterOrderKind::StopLossLimit;
3160        order.trigger_price = Decimal::from(2300);
3161        order.trigger_status = LighterTriggerStatus::Ready;
3162
3163        let event_fresh = parse_lighter_order_event(
3164            &order,
3165            &instrument,
3166            &test_identity_for(OrderType::StopLimit),
3167            test_cloid(),
3168            account_id(),
3169            test_trader_id(),
3170            OpenFrameContext {
3171                accepted_already_emitted: false,
3172                triggered_already_emitted: false,
3173                shape_changed: false,
3174            },
3175            UnixNanos::from(7),
3176        )
3177        .unwrap()
3178        .expect("trigger_status=Ready on fresh open emits Triggered");
3179
3180        match event_fresh {
3181            ParsedOrderEvent::Triggered(_) => {}
3182            other => panic!("expected Triggered for fresh ready trigger, was {other:?}"),
3183        }
3184    }
3185
3186    #[rstest]
3187    fn lighter_order_shape_round_trips_values() {
3188        let instrument = create_test_instrument();
3189        let order = stub_order(LighterOrderStatus::Open);
3190
3191        let shape = lighter_order_shape(&order, &instrument, OrderType::Limit).unwrap();
3192
3193        assert_eq!(shape.quantity, Quantity::from("0.0050"));
3194        assert_eq!(shape.price, Some(Price::from("2352.74")));
3195        assert_eq!(shape.trigger_price, None);
3196    }
3197
3198    #[rstest]
3199    fn lighter_order_shape_distinguishes_modified_payload() {
3200        let instrument = create_test_instrument();
3201        let original = stub_order(LighterOrderStatus::Open);
3202        let mut modified = original.clone();
3203        modified.price = Decimal::from_str("2400.00").unwrap();
3204
3205        let shape_original = lighter_order_shape(&original, &instrument, OrderType::Limit).unwrap();
3206        let shape_modified = lighter_order_shape(&modified, &instrument, OrderType::Limit).unwrap();
3207
3208        assert_ne!(shape_original, shape_modified);
3209    }
3210
3211    #[rstest]
3212    #[case::limit(OrderType::Limit, Some(Price::from("2352.74")), None)]
3213    #[case::market(OrderType::Market, None, None)]
3214    #[case::stop_market(OrderType::StopMarket, None, Some(Price::from("2300.00")))]
3215    #[case::stop_limit(
3216        OrderType::StopLimit,
3217        Some(Price::from("2352.74")),
3218        Some(Price::from("2300.00"))
3219    )]
3220    fn lighter_order_shape_projects_fields_for_order_type(
3221        #[case] order_type: OrderType,
3222        #[case] expected_price: Option<Price>,
3223        #[case] expected_trigger: Option<Price>,
3224    ) {
3225        let instrument = create_test_instrument();
3226        let mut order = stub_order(LighterOrderStatus::Pending);
3227        order.trigger_price = Decimal::from_str("2300.00").unwrap();
3228
3229        let shape = lighter_order_shape(&order, &instrument, order_type).unwrap();
3230
3231        assert_eq!(shape.price, expected_price);
3232        assert_eq!(shape.trigger_price, expected_trigger);
3233    }
3234
3235    #[rstest]
3236    #[case::new_unfilled(false, "0", false)]
3237    #[case::new_traded(false, "0.0020", true)]
3238    #[case::accepted_unfilled(true, "0", true)]
3239    #[case::accepted_traded(true, "0.0020", true)]
3240    fn parse_lighter_order_event_post_only_cancel(
3241        #[case] accepted: bool,
3242        #[case] filled_qty: &str,
3243        #[case] canceled: bool,
3244    ) {
3245        let instrument = create_test_instrument();
3246        let mut order = stub_order(LighterOrderStatus::CanceledPostOnly);
3247        order.filled_base_amount = Decimal::from_str(filled_qty).unwrap();
3248
3249        let event = parse_lighter_order_event(
3250            &order,
3251            &instrument,
3252            &test_identity(),
3253            test_cloid(),
3254            account_id(),
3255            test_trader_id(),
3256            OpenFrameContext {
3257                accepted_already_emitted: accepted,
3258                triggered_already_emitted: false,
3259                shape_changed: false,
3260            },
3261            UnixNanos::from(7),
3262        )
3263        .unwrap()
3264        .expect("post-only cancellation emits an event");
3265
3266        match event {
3267            ParsedOrderEvent::Rejected(e) => {
3268                assert!(!canceled);
3269                assert!(e.due_post_only);
3270                assert_eq!(e.reason, "post-only");
3271            }
3272            ParsedOrderEvent::Canceled(e) => {
3273                assert!(canceled);
3274                assert_eq!(e.reason.as_deref(), Some("post-only"));
3275            }
3276            other => panic!("expected post-only terminal, was {other:?}"),
3277        }
3278    }
3279
3280    #[rstest]
3281    fn parse_lighter_order_event_emits_expired_for_canceled_expired() {
3282        let instrument = create_test_instrument();
3283        let order = stub_order(LighterOrderStatus::CanceledExpired);
3284
3285        let event = parse_lighter_order_event(
3286            &order,
3287            &instrument,
3288            &test_identity(),
3289            test_cloid(),
3290            account_id(),
3291            test_trader_id(),
3292            OpenFrameContext {
3293                accepted_already_emitted: false,
3294                triggered_already_emitted: false,
3295                shape_changed: false,
3296            },
3297            UnixNanos::from(7),
3298        )
3299        .unwrap()
3300        .expect("canceled-expired emits Expired");
3301
3302        match event {
3303            ParsedOrderEvent::Expired(_) => {}
3304            other => panic!("expected Expired, was {other:?}"),
3305        }
3306    }
3307
3308    #[rstest]
3309    #[case::canceled(LighterOrderStatus::Canceled, None)]
3310    #[case::reduce_only(LighterOrderStatus::CanceledReduceOnly, Some("reduce-only"))]
3311    #[case::self_trade(LighterOrderStatus::CanceledSelfTrade, Some("self-trade"))]
3312    #[case::liquidation(LighterOrderStatus::CanceledLiquidation, Some("liquidation"))]
3313    fn parse_lighter_order_event_emits_canceled_for_other_cancel_variants(
3314        #[case] status: LighterOrderStatus,
3315        #[case] expected_reason: Option<&str>,
3316    ) {
3317        let instrument = create_test_instrument();
3318        let order = stub_order(status);
3319
3320        let event = parse_lighter_order_event(
3321            &order,
3322            &instrument,
3323            &test_identity(),
3324            test_cloid(),
3325            account_id(),
3326            test_trader_id(),
3327            OpenFrameContext {
3328                accepted_already_emitted: false,
3329                triggered_already_emitted: false,
3330                shape_changed: false,
3331            },
3332            UnixNanos::from(7),
3333        )
3334        .unwrap()
3335        .expect("cancel variant emits Canceled");
3336
3337        match event {
3338            ParsedOrderEvent::Canceled(canceled) => {
3339                assert_eq!(
3340                    canceled.reason.map(|reason| reason.as_str()),
3341                    expected_reason
3342                );
3343            }
3344            other => panic!("expected Canceled, was {other:?}"),
3345        }
3346    }
3347
3348    #[rstest]
3349    #[case::in_progress(LighterOrderStatus::InProgress)]
3350    #[case::filled(LighterOrderStatus::Filled)]
3351    fn parse_lighter_order_event_returns_none_for_silent_statuses(
3352        #[case] status: LighterOrderStatus,
3353    ) {
3354        // InProgress carries no actionable event; Filled flows through the
3355        // trade stream and produces `OrderFilled` from `parse_lighter_order_filled`.
3356        let instrument = create_test_instrument();
3357        let order = stub_order(status);
3358
3359        let event = parse_lighter_order_event(
3360            &order,
3361            &instrument,
3362            &test_identity(),
3363            test_cloid(),
3364            account_id(),
3365            test_trader_id(),
3366            OpenFrameContext {
3367                accepted_already_emitted: false,
3368                triggered_already_emitted: false,
3369                shape_changed: false,
3370            },
3371            UnixNanos::from(7),
3372        )
3373        .unwrap();
3374
3375        assert!(event.is_none(), "expected None for {status:?}");
3376    }
3377
3378    #[rstest]
3379    #[case::bidder_maker_ask_is_taker(true, true, "0.06160765 USDC")]
3380    #[case::asker_maker_ask_is_maker(true, false, "0.00880109 USDC")]
3381    #[case::bidder_maker_bid_is_maker(false, true, "0.00880109 USDC")]
3382    #[case::asker_maker_bid_is_taker(false, false, "0.06160765 USDC")]
3383    fn parse_lighter_order_filled_builds_order_filled_for_account(
3384        #[case] is_maker_ask: bool,
3385        #[case] user_is_bidder: bool,
3386        #[case] expected_commission: &str,
3387    ) {
3388        let instrument = create_test_instrument();
3389        let trade = stub_account_trade(1234, is_maker_ask, user_is_bidder);
3390
3391        let filled = parse_lighter_order_filled(
3392            &trade,
3393            &instrument,
3394            &test_identity(),
3395            test_cloid(),
3396            account_id(),
3397            test_trader_id(),
3398            1234,
3399            UnixNanos::from(7),
3400        )
3401        .unwrap()
3402        .expect("trade involving account emits OrderFilled");
3403
3404        assert_eq!(filled.client_order_id, test_cloid());
3405        assert_eq!(filled.order_side, OrderSide::Sell); // identity wins
3406        assert_eq!(filled.order_type, OrderType::Limit);
3407        assert_eq!(filled.last_qty, Quantity::from("0.1336"));
3408        assert_eq!(filled.last_px, Price::from("2352.73"));
3409        assert_eq!(filled.commission, Some(Money::from(expected_commission)));
3410    }
3411
3412    #[rstest]
3413    fn parse_lighter_order_filled_returns_none_for_other_account() {
3414        let instrument = create_test_instrument();
3415        // account_index does not appear on either side of the trade.
3416        let trade = stub_account_trade(1234, true, true);
3417
3418        let filled = parse_lighter_order_filled(
3419            &trade,
3420            &instrument,
3421            &test_identity(),
3422            test_cloid(),
3423            account_id(),
3424            test_trader_id(),
3425            99_999, // mismatched account_index
3426            UnixNanos::from(7),
3427        )
3428        .unwrap();
3429
3430        assert!(filled.is_none());
3431    }
3432
3433    #[rstest]
3434    #[case::unchanged(
3435        LighterOrderStatus::Open,
3436        "0.0027",
3437        "0.0027",
3438        "0.0000",
3439        "0.0027",
3440        OrderStatus::Accepted
3441    )]
3442    #[case::partial_fill(
3443        LighterOrderStatus::Open,
3444        "0.0027",
3445        "0.0001",
3446        "0.0026",
3447        "0.0027",
3448        OrderStatus::PartiallyFilled
3449    )]
3450    #[case::modify(
3451        LighterOrderStatus::Open,
3452        "0.0001",
3453        "0.0001",
3454        "0.0000",
3455        "0.0001",
3456        OrderStatus::Accepted
3457    )]
3458    #[case::reduce(
3459        LighterOrderStatus::Open,
3460        "0.0027",
3461        "0.0001",
3462        "0.0000",
3463        "0.0001",
3464        OrderStatus::Accepted
3465    )]
3466    #[case::reduce_after_fill(
3467        LighterOrderStatus::Open,
3468        "0.0027",
3469        "0.0001",
3470        "0.0001",
3471        "0.0002",
3472        OrderStatus::PartiallyFilled
3473    )]
3474    #[case::reduce_filled(
3475        LighterOrderStatus::Filled,
3476        "0.0027",
3477        "0.0000",
3478        "0.0001",
3479        "0.0001",
3480        OrderStatus::Filled
3481    )]
3482    #[case::canceled(
3483        LighterOrderStatus::Canceled,
3484        "0.0027",
3485        "0.0000",
3486        "0.0000",
3487        "0.0027",
3488        OrderStatus::Canceled
3489    )]
3490    #[case::partial_canceled(
3491        LighterOrderStatus::Canceled,
3492        "0.0027",
3493        "0.0000",
3494        "0.0001",
3495        "0.0027",
3496        OrderStatus::Canceled
3497    )]
3498    #[case::self_trade_canceled(
3499        LighterOrderStatus::CanceledSelfTrade,
3500        "0.0027",
3501        "0.0000",
3502        "0.0001",
3503        "0.0027",
3504        OrderStatus::Canceled
3505    )]
3506    #[case::expired(
3507        LighterOrderStatus::CanceledExpired,
3508        "0.0027",
3509        "0.0000",
3510        "0.0000",
3511        "0.0027",
3512        OrderStatus::Expired
3513    )]
3514    #[case::rejected(
3515        LighterOrderStatus::CanceledPostOnly,
3516        "0.0027",
3517        "0.0000",
3518        "0.0000",
3519        "0.0027",
3520        OrderStatus::Rejected
3521    )]
3522    #[case::held(
3523        LighterOrderStatus::Pending,
3524        "0.0000",
3525        "0.0000",
3526        "0.0000",
3527        "0.0000",
3528        OrderStatus::Accepted
3529    )]
3530    #[case::held_remaining(
3531        LighterOrderStatus::Pending,
3532        "0.0000",
3533        "0.0027",
3534        "0.0000",
3535        "0.0000",
3536        OrderStatus::Accepted
3537    )]
3538    #[case::zero_remaining(
3539        LighterOrderStatus::Open,
3540        "0.0027",
3541        "0.0000",
3542        "0.0000",
3543        "0.0027",
3544        OrderStatus::Accepted
3545    )]
3546    fn test_self_trade_reduce_quantity(
3547        #[case] status: LighterOrderStatus,
3548        #[case] initial: &str,
3549        #[case] remaining: &str,
3550        #[case] filled: &str,
3551        #[case] expected: &str,
3552        #[case] expected_status: OrderStatus,
3553    ) {
3554        let instrument = create_test_instrument();
3555        let mut order = stub_order(status);
3556        order.initial_base_amount = Decimal::from_str(initial).unwrap();
3557        order.remaining_base_amount = Decimal::from_str(remaining).unwrap();
3558        order.filled_base_amount = Decimal::from_str(filled).unwrap();
3559        let report =
3560            parse_ws_order_status_report(&order, &instrument, account_id(), UnixNanos::from(7))
3561                .unwrap();
3562        let shape = lighter_order_shape(&order, &instrument, OrderType::Limit).unwrap();
3563        let update = parse_lighter_order_updated(
3564            &order,
3565            &instrument,
3566            &test_identity(),
3567            test_cloid(),
3568            account_id(),
3569            test_trader_id(),
3570            UnixNanos::from(7),
3571        )
3572        .unwrap();
3573
3574        assert_eq!(report.quantity, Quantity::from(expected));
3575        assert_eq!(report.filled_qty, Quantity::from(filled));
3576        assert_eq!(report.order_status, expected_status);
3577        assert_eq!(shape.quantity, Quantity::from(expected));
3578        assert_eq!(update.quantity, Quantity::from(expected));
3579        assert_eq!(
3580            update.reconciliation,
3581            Decimal::from_str(expected).unwrap() < order.initial_base_amount
3582        );
3583    }
3584
3585    #[rstest]
3586    fn test_self_trade_reduce_quantity_overflow() {
3587        let mut order = stub_order(LighterOrderStatus::Open);
3588        order.filled_base_amount = Decimal::MAX;
3589        order.remaining_base_amount = Decimal::ONE;
3590
3591        let error = lighter_order_quantity(&order, 4).unwrap_err();
3592
3593        assert_eq!(error.to_string(), "Lighter order quantity overflow");
3594    }
3595}