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