Skip to main content

nautilus_lighter/common/
enums.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//! Lighter venue enums mirrored from REST and WebSocket payloads.
17
18use std::fmt::Display;
19
20use nautilus_model::{
21    data::{BarSpecification, BarType},
22    enums::{AggregationSource, BarAggregation, OrderSide, OrderType, PriceType},
23};
24use serde::{Deserialize, Serialize};
25use serde_repr::{Deserialize_repr, Serialize_repr};
26use strum::{AsRefStr, Display, EnumIter, EnumString};
27
28/// Lighter protocol deployment.
29#[derive(
30    Copy,
31    Clone,
32    Debug,
33    Default,
34    Display,
35    PartialEq,
36    Eq,
37    Hash,
38    AsRefStr,
39    EnumIter,
40    EnumString,
41    Serialize,
42    Deserialize,
43)]
44#[serde(rename_all = "lowercase")]
45#[strum(ascii_case_insensitive, serialize_all = "lowercase")]
46#[cfg_attr(
47    feature = "python",
48    pyo3::pyclass(
49        eq,
50        eq_int,
51        module = "nautilus_trader.adapters.lighter",
52        from_py_object,
53        rename_all = "SCREAMING_SNAKE_CASE",
54    )
55)]
56#[cfg_attr(
57    feature = "python",
58    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.adapters.lighter")
59)]
60pub enum LighterDeployment {
61    /// The Lighter deployment.
62    #[default]
63    Lighter,
64    /// The Robinhood Chain deployment of the Lighter protocol.
65    Robinhood,
66}
67
68/// Lighter API environment.
69#[derive(
70    Copy,
71    Clone,
72    Debug,
73    Default,
74    Display,
75    PartialEq,
76    Eq,
77    Hash,
78    AsRefStr,
79    EnumIter,
80    EnumString,
81    Serialize,
82    Deserialize,
83)]
84#[serde(rename_all = "lowercase")]
85#[strum(ascii_case_insensitive, serialize_all = "lowercase")]
86#[cfg_attr(
87    feature = "python",
88    pyo3::pyclass(
89        eq,
90        eq_int,
91        module = "nautilus_trader.adapters.lighter",
92        from_py_object,
93        rename_all = "SCREAMING_SNAKE_CASE",
94    )
95)]
96#[cfg_attr(
97    feature = "python",
98    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.adapters.lighter")
99)]
100pub enum LighterEnvironment {
101    /// Mainnet trading environment.
102    #[default]
103    Mainnet,
104    /// Testnet environment.
105    Testnet,
106}
107
108/// Lighter product type reported by market metadata.
109#[derive(
110    Copy,
111    Clone,
112    Debug,
113    Display,
114    PartialEq,
115    Eq,
116    Hash,
117    AsRefStr,
118    EnumIter,
119    EnumString,
120    Serialize,
121    Deserialize,
122)]
123#[serde(rename_all = "snake_case")]
124#[strum(ascii_case_insensitive, serialize_all = "snake_case")]
125pub enum LighterProductType {
126    /// Perpetual futures.
127    Perp,
128    /// Spot markets.
129    Spot,
130    /// Binary options, which the adapter does not support.
131    BinaryOptions,
132    /// Forward-compatible fallback for any value the venue adds later.
133    #[serde(other)]
134    Other,
135}
136
137impl LighterProductType {
138    /// Returns whether the adapter supports this product type.
139    #[must_use]
140    pub const fn is_supported(self) -> bool {
141        matches!(self, Self::Perp | Self::Spot)
142    }
143}
144
145/// Lighter historical candle resolution.
146#[derive(
147    Copy,
148    Clone,
149    Debug,
150    Display,
151    PartialEq,
152    Eq,
153    Hash,
154    AsRefStr,
155    EnumIter,
156    EnumString,
157    Serialize,
158    Deserialize,
159)]
160#[strum(ascii_case_insensitive)]
161pub enum LighterCandleResolution {
162    /// One-minute candles.
163    #[serde(rename = "1m")]
164    #[strum(serialize = "1m")]
165    OneMinute,
166    /// Five-minute candles.
167    #[serde(rename = "5m")]
168    #[strum(serialize = "5m")]
169    FiveMinute,
170    /// Fifteen-minute candles.
171    #[serde(rename = "15m")]
172    #[strum(serialize = "15m")]
173    FifteenMinute,
174    /// Thirty-minute candles.
175    #[serde(rename = "30m")]
176    #[strum(serialize = "30m")]
177    ThirtyMinute,
178    /// One-hour candles.
179    #[serde(rename = "1h")]
180    #[strum(serialize = "1h")]
181    OneHour,
182    /// Four-hour candles.
183    #[serde(rename = "4h")]
184    #[strum(serialize = "4h")]
185    FourHour,
186    /// Twelve-hour candles.
187    #[serde(rename = "12h")]
188    #[strum(serialize = "12h")]
189    TwelveHour,
190    /// One-day candles.
191    #[serde(rename = "1d")]
192    #[strum(serialize = "1d")]
193    OneDay,
194    /// One-week candles.
195    #[serde(rename = "1w")]
196    #[strum(serialize = "1w")]
197    OneWeek,
198}
199
200impl LighterCandleResolution {
201    /// Returns the REST `resolution` string accepted by Lighter.
202    #[must_use]
203    pub const fn as_str(self) -> &'static str {
204        match self {
205            Self::OneMinute => "1m",
206            Self::FiveMinute => "5m",
207            Self::FifteenMinute => "15m",
208            Self::ThirtyMinute => "30m",
209            Self::OneHour => "1h",
210            Self::FourHour => "4h",
211            Self::TwelveHour => "12h",
212            Self::OneDay => "1d",
213            Self::OneWeek => "1w",
214        }
215    }
216
217    /// Returns the candle interval in milliseconds.
218    #[must_use]
219    pub const fn interval_millis(self) -> i64 {
220        match self {
221            Self::OneMinute => 60_000,
222            Self::FiveMinute => 5 * 60_000,
223            Self::FifteenMinute => 15 * 60_000,
224            Self::ThirtyMinute => 30 * 60_000,
225            Self::OneHour => 60 * 60_000,
226            Self::FourHour => 4 * 60 * 60_000,
227            Self::TwelveHour => 12 * 60 * 60_000,
228            Self::OneDay => 24 * 60 * 60_000,
229            Self::OneWeek => 7 * 24 * 60 * 60_000,
230        }
231    }
232
233    /// Returns the Nautilus [`BarSpecification`] for this candle resolution (`Last` / `External`).
234    #[must_use]
235    pub fn to_bar_spec(self) -> BarSpecification {
236        let (step, aggregation) = match self {
237            Self::OneMinute => (1, BarAggregation::Minute),
238            Self::FiveMinute => (5, BarAggregation::Minute),
239            Self::FifteenMinute => (15, BarAggregation::Minute),
240            Self::ThirtyMinute => (30, BarAggregation::Minute),
241            Self::OneHour => (1, BarAggregation::Hour),
242            Self::FourHour => (4, BarAggregation::Hour),
243            Self::TwelveHour => (12, BarAggregation::Hour),
244            Self::OneDay => (1, BarAggregation::Day),
245            Self::OneWeek => (1, BarAggregation::Week),
246        };
247        BarSpecification::new(step, aggregation, PriceType::Last)
248    }
249
250    /// Returns `true` when this resolution is offered on the candle WebSocket stream.
251    ///
252    /// `1w` is REST-only; the streaming channel only carries `1m`..=`1d`.
253    #[must_use]
254    pub const fn is_ws_streamable(self) -> bool {
255        !matches!(self, Self::OneWeek)
256    }
257}
258
259impl TryFrom<&BarType> for LighterCandleResolution {
260    type Error = anyhow::Error;
261
262    fn try_from(value: &BarType) -> Result<Self, Self::Error> {
263        anyhow::ensure!(
264            value.aggregation_source() == AggregationSource::External,
265            "Lighter candles only support EXTERNAL aggregation",
266        );
267
268        let spec = value.spec();
269        anyhow::ensure!(
270            spec.price_type == PriceType::Last,
271            "Lighter candles only support LAST price type",
272        );
273
274        let step = spec.step.get();
275        match spec.aggregation {
276            BarAggregation::Minute => match step {
277                1 => Ok(Self::OneMinute),
278                5 => Ok(Self::FiveMinute),
279                15 => Ok(Self::FifteenMinute),
280                30 => Ok(Self::ThirtyMinute),
281                _ => anyhow::bail!("unsupported Lighter candle minute step: {step}"),
282            },
283            BarAggregation::Hour => match step {
284                1 => Ok(Self::OneHour),
285                4 => Ok(Self::FourHour),
286                12 => Ok(Self::TwelveHour),
287                _ => anyhow::bail!("unsupported Lighter candle hour step: {step}"),
288            },
289            BarAggregation::Day => match step {
290                1 => Ok(Self::OneDay),
291                _ => anyhow::bail!("unsupported Lighter candle day step: {step}"),
292            },
293            BarAggregation::Week => match step {
294                1 => Ok(Self::OneWeek),
295                _ => anyhow::bail!("unsupported Lighter candle week step: {step}"),
296            },
297            other => anyhow::bail!("unsupported Lighter candle aggregation: {other}"),
298        }
299    }
300}
301
302/// Lighter historical funding resolution.
303#[derive(
304    Copy,
305    Clone,
306    Debug,
307    Default,
308    Display,
309    PartialEq,
310    Eq,
311    Hash,
312    AsRefStr,
313    EnumIter,
314    EnumString,
315    Serialize,
316    Deserialize,
317)]
318#[strum(ascii_case_insensitive)]
319pub enum LighterFundingResolution {
320    /// One-hour funding history.
321    #[default]
322    #[serde(rename = "1h")]
323    #[strum(serialize = "1h")]
324    OneHour,
325    /// One-day funding history.
326    #[serde(rename = "1d")]
327    #[strum(serialize = "1d")]
328    OneDay,
329}
330
331impl LighterFundingResolution {
332    /// Returns the funding interval in minutes.
333    #[must_use]
334    pub const fn interval_minutes(self) -> u16 {
335        match self {
336            Self::OneHour => 60,
337            Self::OneDay => 24 * 60,
338        }
339    }
340
341    /// Returns the funding interval in milliseconds.
342    #[must_use]
343    pub const fn interval_millis(self) -> i64 {
344        match self {
345            Self::OneHour => 60 * 60_000,
346            Self::OneDay => 24 * 60 * 60_000,
347        }
348    }
349}
350
351/// Filter accepted by Lighter market metadata endpoints.
352#[derive(
353    Copy,
354    Clone,
355    Debug,
356    Default,
357    Display,
358    PartialEq,
359    Eq,
360    Hash,
361    AsRefStr,
362    EnumIter,
363    EnumString,
364    Serialize,
365    Deserialize,
366)]
367#[serde(rename_all = "lowercase")]
368#[strum(ascii_case_insensitive, serialize_all = "lowercase")]
369pub enum LighterOrderBookFilter {
370    /// Return all markets.
371    #[default]
372    All,
373    /// Return perpetual markets only.
374    Perp,
375    /// Return spot markets only.
376    Spot,
377}
378
379/// Status for Lighter market metadata.
380#[derive(
381    Copy,
382    Clone,
383    Debug,
384    Display,
385    PartialEq,
386    Eq,
387    Hash,
388    AsRefStr,
389    EnumIter,
390    EnumString,
391    Serialize,
392    Deserialize,
393)]
394#[serde(rename_all = "kebab-case")]
395#[strum(ascii_case_insensitive, serialize_all = "kebab-case")]
396pub enum LighterMarketStatus {
397    /// Market is not available for trading.
398    Inactive,
399    /// Market is available for trading.
400    Active,
401    /// Market is being settled.
402    InSettlement,
403    /// Market is waiting for settlement.
404    WaitingForSettlement,
405    /// Market is settled.
406    Settled,
407    /// Forward-compatible fallback for any status the venue adds later.
408    #[serde(other)]
409    Unknown,
410}
411
412/// Numeric transaction status returned by Lighter transaction queries.
413#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]
414#[repr(i64)]
415pub enum LighterTxStatus {
416    Failed = 0,
417    Pending = 1,
418    Executed = 2,
419    PendingFinal = 3,
420}
421
422/// String order type used by REST and WebSocket order payloads.
423#[derive(
424    Copy,
425    Clone,
426    Debug,
427    Display,
428    PartialEq,
429    Eq,
430    Hash,
431    AsRefStr,
432    EnumIter,
433    EnumString,
434    Serialize,
435    Deserialize,
436)]
437#[serde(rename_all = "kebab-case")]
438#[strum(ascii_case_insensitive, serialize_all = "kebab-case")]
439pub enum LighterOrderKind {
440    Limit,
441    Market,
442    StopLoss,
443    StopLossLimit,
444    TakeProfit,
445    TakeProfitLimit,
446    Twap,
447    TwapSub,
448    Liquidation,
449    /// Forward-compatible fallback for any order type the venue adds later.
450    #[serde(other)]
451    Other,
452}
453
454/// String time-in-force used by REST and WebSocket order payloads.
455#[derive(
456    Copy,
457    Clone,
458    Debug,
459    Display,
460    PartialEq,
461    Eq,
462    Hash,
463    AsRefStr,
464    EnumIter,
465    EnumString,
466    Serialize,
467    Deserialize,
468)]
469#[serde(rename_all = "kebab-case")]
470#[strum(ascii_case_insensitive, serialize_all = "kebab-case")]
471pub enum LighterOrderTimeInForce {
472    GoodTillTime,
473    ImmediateOrCancel,
474    PostOnly,
475    /// The venue's literal `Unknown` value and any value the venue adds later.
476    #[serde(other, rename = "Unknown")]
477    #[strum(serialize = "Unknown")]
478    Unknown,
479}
480
481/// String order status used by REST and WebSocket order payloads.
482#[derive(
483    Copy,
484    Clone,
485    Debug,
486    Display,
487    PartialEq,
488    Eq,
489    Hash,
490    AsRefStr,
491    EnumIter,
492    EnumString,
493    Serialize,
494    Deserialize,
495)]
496#[serde(rename_all = "kebab-case")]
497#[strum(ascii_case_insensitive, serialize_all = "kebab-case")]
498pub enum LighterOrderStatus {
499    InProgress,
500    Pending,
501    Open,
502    Filled,
503    Canceled,
504    CanceledPostOnly,
505    CanceledReduceOnly,
506    CanceledPositionNotAllowed,
507    CanceledMarginNotAllowed,
508    CanceledTooMuchSlippage,
509    CanceledNotEnoughLiquidity,
510    CanceledSelfTrade,
511    CanceledExpired,
512    CanceledOco,
513    CanceledChild,
514    CanceledLiquidation,
515    CanceledInvalidBalance,
516    /// Forward-compatible fallback for any status the venue adds later.
517    #[serde(other)]
518    Unknown,
519}
520
521impl LighterOrderStatus {
522    /// Short kebab-case label describing a cancellation cause, suitable for
523    /// [`nautilus_model::reports::OrderStatusReport::with_cancel_reason`].
524    ///
525    /// Returns `None` for non-cancelled statuses and for the unqualified
526    /// [`Canceled`](Self::Canceled) / [`CanceledExpired`](Self::CanceledExpired)
527    /// variants, which carry their meaning via the Nautilus order status itself.
528    #[must_use]
529    pub fn as_cancel_reason(self) -> Option<&'static str> {
530        match self {
531            Self::CanceledPostOnly => Some("post-only"),
532            Self::CanceledReduceOnly => Some("reduce-only"),
533            Self::CanceledPositionNotAllowed => Some("position-not-allowed"),
534            Self::CanceledMarginNotAllowed => Some("margin-not-allowed"),
535            Self::CanceledTooMuchSlippage => Some("too-much-slippage"),
536            Self::CanceledNotEnoughLiquidity => Some("not-enough-liquidity"),
537            Self::CanceledSelfTrade => Some("self-trade"),
538            Self::CanceledOco => Some("oco"),
539            Self::CanceledChild => Some("child"),
540            Self::CanceledLiquidation => Some("liquidation"),
541            Self::CanceledInvalidBalance => Some("invalid-balance"),
542            _ => None,
543        }
544    }
545
546    // An unknown status is not known to be terminal, so order tracking stays in place
547    pub(crate) fn is_terminal(self) -> bool {
548        !matches!(
549            self,
550            Self::InProgress | Self::Pending | Self::Open | Self::Unknown
551        )
552    }
553}
554
555/// Side string used by REST and WebSocket order payloads.
556#[derive(
557    Copy,
558    Clone,
559    Debug,
560    Display,
561    PartialEq,
562    Eq,
563    Hash,
564    AsRefStr,
565    EnumIter,
566    EnumString,
567    Serialize,
568    Deserialize,
569)]
570#[serde(rename_all = "lowercase")]
571#[strum(ascii_case_insensitive, serialize_all = "lowercase")]
572pub enum LighterOrderSide {
573    Buy,
574    Sell,
575}
576
577/// Trigger status used by conditional order payloads.
578#[derive(
579    Copy,
580    Clone,
581    Debug,
582    Display,
583    PartialEq,
584    Eq,
585    Hash,
586    AsRefStr,
587    EnumIter,
588    EnumString,
589    Serialize,
590    Deserialize,
591)]
592#[serde(rename_all = "kebab-case")]
593#[strum(ascii_case_insensitive, serialize_all = "kebab-case")]
594pub enum LighterTriggerStatus {
595    Na,
596    Ready,
597    MarkPrice,
598    Twap,
599    ParentOrder,
600    /// Forward-compatible fallback for any status the venue adds later.
601    #[serde(other)]
602    Unknown,
603}
604
605/// Trade type used by REST and WebSocket trade payloads.
606#[derive(
607    Copy,
608    Clone,
609    Debug,
610    Display,
611    PartialEq,
612    Eq,
613    Hash,
614    AsRefStr,
615    EnumIter,
616    EnumString,
617    Serialize,
618    Deserialize,
619)]
620#[serde(rename_all = "kebab-case")]
621#[strum(ascii_case_insensitive, serialize_all = "kebab-case")]
622pub enum LighterTradeType {
623    Trade,
624    Liquidation,
625    Deleverage,
626    MarketSettlement,
627    /// Forward-compatible fallback for any trade type the venue adds later.
628    #[serde(other)]
629    Other,
630}
631
632/// Lighter order type as encoded in the venue's binary order payload.
633///
634/// Numeric values are part of the wire format and must match the venue spec.
635#[derive(
636    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
637)]
638#[repr(u8)]
639pub enum LighterOrderType {
640    Limit = 0,
641    Market = 1,
642    StopLoss = 2,
643    StopLossLimit = 3,
644    TakeProfit = 4,
645    TakeProfitLimit = 5,
646    Twap = 6,
647    TwapSub = 7,
648    Liquidation = 8,
649}
650
651impl LighterOrderType {
652    /// Returns the Nautilus [`OrderType`] that this Lighter order type maps to.
653    ///
654    /// `StopLoss` / `StopLossLimit` map to Nautilus stop-on-the-loss-side
655    /// triggers (`StopMarket` / `StopLimit`), while `TakeProfit` /
656    /// `TakeProfitLimit` map to "if-touched" triggers
657    /// (`MarketIfTouched` / `LimitIfTouched`) which fire when price reaches
658    /// a target rather than crosses a stop.
659    ///
660    /// # Errors
661    ///
662    /// Returns an error if a venue-internal or algorithmic order type does not map to a single
663    /// Nautilus order type.
664    pub fn as_nautilus(self) -> anyhow::Result<OrderType> {
665        match self {
666            Self::Limit => Ok(OrderType::Limit),
667            Self::Market => Ok(OrderType::Market),
668            Self::StopLoss => Ok(OrderType::StopMarket),
669            Self::StopLossLimit => Ok(OrderType::StopLimit),
670            Self::TakeProfit => Ok(OrderType::MarketIfTouched),
671            Self::TakeProfitLimit => Ok(OrderType::LimitIfTouched),
672            Self::Twap | Self::TwapSub | Self::Liquidation => Err(anyhow::anyhow!(
673                "Lighter `{self:?}` has no Nautilus order-type equivalent",
674            )),
675        }
676    }
677}
678
679impl TryFrom<OrderType> for LighterOrderType {
680    type Error = anyhow::Error;
681
682    fn try_from(value: OrderType) -> Result<Self, Self::Error> {
683        match value {
684            OrderType::Limit => Ok(Self::Limit),
685            OrderType::Market => Ok(Self::Market),
686            OrderType::StopMarket => Ok(Self::StopLoss),
687            OrderType::StopLimit => Ok(Self::StopLossLimit),
688            OrderType::MarketIfTouched => Ok(Self::TakeProfit),
689            OrderType::LimitIfTouched => Ok(Self::TakeProfitLimit),
690            other => Err(anyhow::anyhow!(
691                "Nautilus `{other:?}` has no Lighter order-type equivalent",
692            )),
693        }
694    }
695}
696
697/// Lighter time-in-force as encoded in the venue's binary order payload.
698#[derive(
699    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
700)]
701#[repr(u8)]
702pub enum LighterTimeInForce {
703    /// Immediate-or-cancel.
704    ImmediateOrCancel = 0,
705    /// Good-till-time.
706    GoodTillTime = 1,
707    /// Post-only.
708    PostOnly = 2,
709}
710
711/// Lighter grouped-order relationship type.
712#[derive(
713    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
714)]
715#[repr(u8)]
716pub enum LighterGroupingType {
717    None = 0,
718    OneTriggersTheOther = 1,
719    OneCancelsTheOther = 2,
720    OneTriggersOneCancelsTheOther = 3,
721}
722
723/// Lighter's action when an order would self-trade.
724#[derive(
725    Copy,
726    Clone,
727    Debug,
728    Default,
729    Display,
730    PartialEq,
731    Eq,
732    Hash,
733    AsRefStr,
734    EnumString,
735    Serialize_repr,
736    Deserialize_repr,
737)]
738#[repr(u8)]
739#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
740pub enum LighterSelfTradeBehaviorMode {
741    #[default]
742    ExpireMaker = 0,
743    ExpireTaker = 1,
744    CancelBoth = 2,
745    Reduce = 3,
746}
747
748/// Lighter's account scope for self-trade prevention.
749#[derive(
750    Copy,
751    Clone,
752    Debug,
753    Default,
754    Display,
755    PartialEq,
756    Eq,
757    Hash,
758    AsRefStr,
759    EnumString,
760    Serialize_repr,
761    Deserialize_repr,
762)]
763#[repr(u8)]
764#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
765pub enum LighterSelfTradeEqualityMode {
766    #[default]
767    AccountIndex = 0,
768    MasterAccountIndex = 1,
769}
770
771/// Lighter cancel-all-orders time-in-force.
772#[derive(
773    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
774)]
775#[repr(u8)]
776pub enum LighterCancelAllTimeInForce {
777    Immediate = 0,
778    Scheduled = 1,
779    AbortScheduled = 2,
780}
781
782/// Lighter asset margin mode.
783#[derive(
784    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
785)]
786#[repr(u8)]
787pub enum LighterAssetMarginMode {
788    Disabled = 0,
789    Enabled = 1,
790}
791
792/// Lighter asset route type.
793#[derive(
794    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
795)]
796#[repr(u8)]
797pub enum LighterAssetRouteType {
798    Perps = 0,
799    Spot = 1,
800}
801
802/// Lighter position margin mode.
803#[derive(
804    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
805)]
806#[repr(u8)]
807pub enum LighterPositionMarginMode {
808    Cross = 0,
809    Isolated = 1,
810}
811
812/// Lighter isolated-margin update direction.
813#[derive(
814    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
815)]
816#[repr(u8)]
817pub enum LighterMarginUpdateDirection {
818    RemoveFromIsolated = 0,
819    AddToIsolated = 1,
820}
821
822/// Lighter account tier, classified from the venue `account_type` code.
823///
824/// The code `0` is confirmed to be the standard tier. Codes for the higher
825/// tiers are not published in the venue schema, so they are mapped on a
826/// best-effort basis and any unrecognized code is preserved as
827/// [`Self::Unknown`] rather than silently misclassified. This type is a
828/// classification of the raw `account_type` byte, not a wire representation, so
829/// it is not serialized.
830#[derive(Copy, Clone, Debug, PartialEq, Eq)]
831pub enum LighterAccountTier {
832    Standard,
833    Premium,
834    Plus,
835    Builder,
836    Unknown(u8),
837}
838
839impl LighterAccountTier {
840    /// Classifies a venue `account_type` code into a tier.
841    #[must_use]
842    pub const fn from_code(code: u8) -> Self {
843        match code {
844            0 => Self::Standard,
845            1 => Self::Premium,
846            2 => Self::Plus,
847            3 => Self::Builder,
848            other => Self::Unknown(other),
849        }
850    }
851
852    /// Returns the documented REST weighted limit (requests per minute) for the
853    /// tier, or `None` when the tier is unrecognized.
854    ///
855    /// This drives log hints only. The adapter never sets the active quota from
856    /// this value, because the higher limits require registering the caller IP
857    /// with the venue and so are not guaranteed by the tier alone.
858    #[must_use]
859    pub const fn documented_rest_quota_per_min(self) -> Option<u32> {
860        match self {
861            Self::Standard => Some(60),
862            Self::Premium => Some(24_000),
863            Self::Plus => Some(24_000),
864            Self::Builder => Some(240_000),
865            Self::Unknown(_) => None,
866        }
867    }
868}
869
870impl Display for LighterAccountTier {
871    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
872        match self {
873            Self::Standard => f.write_str("Standard"),
874            Self::Premium => f.write_str("Premium"),
875            Self::Plus => f.write_str("Plus"),
876            Self::Builder => f.write_str("Builder"),
877            Self::Unknown(code) => write!(f, "Unknown({code})"),
878        }
879    }
880}
881
882// Conversions between `LighterTimeInForce` and Nautilus `TimeInForce` are
883// intentionally not provided here. `GoodTillTime` is ambiguous in isolation:
884// the venue uses it for both true GTD (paired with a positive `order_expiry`
885// timestamp) and venue-default lifetime (paired with `order_expiry = -1`).
886// The mapping must happen at the parse / order-build call site where the
887// `order_expiry` value is also in scope.
888
889/// Converts a Nautilus [`OrderSide`] to the venue's `is_ask` boolean.
890///
891/// Lighter's tx body encodes the side as `is_ask`: `false` for a bid (buy)
892/// and `true` for an ask (sell).
893pub fn is_ask_from_order_side(side: OrderSide) -> bool {
894    match side {
895        OrderSide::Buy => false,
896        OrderSide::Sell => true,
897    }
898}
899
900/// Converts the venue's `is_ask` boolean to a Nautilus [`OrderSide`].
901#[must_use]
902pub fn order_side_from_is_ask(is_ask: bool) -> OrderSide {
903    if is_ask {
904        OrderSide::Sell
905    } else {
906        OrderSide::Buy
907    }
908}
909
910/// Lighter L2 transaction-type discriminants.
911///
912/// These are the `tx_type` values the venue accepts on `sendTx` / `sendTxBatch`.
913/// Numeric values are wire-format and must match the venue spec.
914#[derive(
915    Copy, Clone, Debug, Display, PartialEq, Eq, Hash, AsRefStr, Serialize_repr, Deserialize_repr,
916)]
917#[repr(u8)]
918pub enum LighterTxType {
919    Empty = 0,
920    L1Deposit = 1,
921    L1ChangePubKey = 2,
922    L1CreateMarket = 3,
923    L1UpdateMarket = 4,
924    L1CancelAllOrders = 5,
925    L1Withdraw = 6,
926    L1CreateOrder = 7,
927    ChangePubKey = 8,
928    CreateSubAccount = 9,
929    CreatePublicPool = 10,
930    UpdatePublicPool = 11,
931    Transfer = 12,
932    Withdraw = 13,
933    CreateOrder = 14,
934    CancelOrder = 15,
935    CancelAllOrders = 16,
936    ModifyOrder = 17,
937    MintShares = 18,
938    BurnShares = 19,
939    UpdateLeverage = 20,
940    InternalClaimOrder = 21,
941    InternalCancelOrder = 22,
942    InternalDeleverage = 23,
943    InternalExitPosition = 24,
944    InternalCancelAllOrders = 25,
945    InternalLiquidatePosition = 26,
946    InternalCreateOrder = 27,
947    CreateGroupedOrders = 28,
948    UpdateMargin = 29,
949    L1BurnShares = 30,
950    L1RegisterAsset = 31,
951    L1UpdateAsset = 32,
952    CreateStakingPool = 33,
953    StakeAssets = 35,
954    UnstakeAssets = 36,
955    L1UnstakeAssets = 37,
956    L1SetSystemConfig = 38,
957    ForceBurnShares = 40,
958    UpdateAccountConfig = 41,
959    StrategyTransfer = 43,
960    UpdateMarketConfig = 44,
961    ApproveIntegrator = 45,
962}
963
964#[cfg(test)]
965mod tests {
966    use std::str::FromStr;
967
968    use nautilus_model::{
969        data::{BarSpecification, BarType},
970        identifiers::InstrumentId,
971    };
972    use rstest::rstest;
973    use serde_json;
974
975    use super::*;
976
977    #[rstest]
978    fn test_environment_default_is_mainnet() {
979        assert_eq!(LighterEnvironment::default(), LighterEnvironment::Mainnet);
980    }
981
982    #[rstest]
983    fn test_product_type_serde_uses_wire_values() {
984        assert_eq!(
985            serde_json::to_string(&LighterProductType::Perp).unwrap(),
986            r#""perp""#,
987        );
988        assert_eq!(
989            serde_json::from_str::<LighterProductType>(r#""spot""#).unwrap(),
990            LighterProductType::Spot,
991        );
992    }
993
994    #[rstest]
995    #[case::perp("perp", LighterProductType::Perp)]
996    #[case::spot("spot", LighterProductType::Spot)]
997    #[case::binary_options("binary_options", LighterProductType::BinaryOptions)]
998    #[case::unfamiliar("future_kind", LighterProductType::Other)]
999    fn test_product_type_deserializes_wire_values(
1000        #[case] wire: &str,
1001        #[case] expected: LighterProductType,
1002    ) {
1003        assert_eq!(
1004            serde_json::from_value::<LighterProductType>(serde_json::json!(wire)).unwrap(),
1005            expected,
1006        );
1007    }
1008
1009    #[rstest]
1010    #[case::perp(LighterProductType::Perp, true)]
1011    #[case::spot(LighterProductType::Spot, true)]
1012    #[case::binary_options(LighterProductType::BinaryOptions, false)]
1013    #[case::other(LighterProductType::Other, false)]
1014    fn test_product_type_is_supported(
1015        #[case] product_type: LighterProductType,
1016        #[case] expected: bool,
1017    ) {
1018        assert_eq!(product_type.is_supported(), expected);
1019    }
1020
1021    #[rstest]
1022    #[case::inactive("inactive", LighterMarketStatus::Inactive)]
1023    #[case::active("active", LighterMarketStatus::Active)]
1024    #[case::in_settlement("in-settlement", LighterMarketStatus::InSettlement)]
1025    #[case::waiting_for_settlement(
1026        "waiting-for-settlement",
1027        LighterMarketStatus::WaitingForSettlement
1028    )]
1029    #[case::settled("settled", LighterMarketStatus::Settled)]
1030    #[case::unfamiliar("future-status", LighterMarketStatus::Unknown)]
1031    fn test_market_status_deserializes_wire_values(
1032        #[case] wire: &str,
1033        #[case] expected: LighterMarketStatus,
1034    ) {
1035        assert_eq!(
1036            serde_json::from_value::<LighterMarketStatus>(serde_json::json!(wire)).unwrap(),
1037            expected,
1038        );
1039    }
1040
1041    #[rstest]
1042    fn test_market_status_serializes_wire_values() {
1043        assert_eq!(
1044            serde_json::to_string(&LighterMarketStatus::Inactive).unwrap(),
1045            r#""inactive""#,
1046        );
1047        assert_eq!(
1048            serde_json::to_string(&LighterMarketStatus::WaitingForSettlement).unwrap(),
1049            r#""waiting-for-settlement""#,
1050        );
1051    }
1052
1053    #[rstest]
1054    fn test_order_enums_fall_back_on_unfamiliar_wire_values() {
1055        assert_eq!(
1056            serde_json::from_str::<LighterOrderKind>(r#""future-type""#).unwrap(),
1057            LighterOrderKind::Other,
1058        );
1059        assert_eq!(
1060            serde_json::from_str::<LighterOrderTimeInForce>(r#""future-tif""#).unwrap(),
1061            LighterOrderTimeInForce::Unknown,
1062        );
1063        assert_eq!(
1064            serde_json::from_str::<LighterOrderStatus>(r#""future-status""#).unwrap(),
1065            LighterOrderStatus::Unknown,
1066        );
1067        assert_eq!(
1068            serde_json::from_str::<LighterTriggerStatus>(r#""future-trigger""#).unwrap(),
1069            LighterTriggerStatus::Unknown,
1070        );
1071        assert_eq!(
1072            serde_json::from_str::<LighterTradeType>(r#""future-trade""#).unwrap(),
1073            LighterTradeType::Other,
1074        );
1075    }
1076
1077    #[rstest]
1078    #[case::buy("buy", Some(LighterOrderSide::Buy))]
1079    #[case::sell("sell", Some(LighterOrderSide::Sell))]
1080    #[case::unfamiliar("future-side", None)]
1081    fn test_order_side_stays_closed(
1082        #[case] wire: &str,
1083        #[case] expected: Option<LighterOrderSide>,
1084    ) {
1085        assert_eq!(
1086            serde_json::from_value::<LighterOrderSide>(serde_json::json!(wire)).ok(),
1087            expected,
1088        );
1089    }
1090
1091    #[rstest]
1092    #[case::in_progress(LighterOrderStatus::InProgress, false)]
1093    #[case::pending(LighterOrderStatus::Pending, false)]
1094    #[case::open(LighterOrderStatus::Open, false)]
1095    #[case::unknown(LighterOrderStatus::Unknown, false)]
1096    #[case::filled(LighterOrderStatus::Filled, true)]
1097    #[case::canceled(LighterOrderStatus::Canceled, true)]
1098    #[case::canceled_expired(LighterOrderStatus::CanceledExpired, true)]
1099    fn test_order_status_is_terminal(#[case] status: LighterOrderStatus, #[case] expected: bool) {
1100        assert_eq!(status.is_terminal(), expected);
1101    }
1102
1103    #[rstest]
1104    fn test_string_order_enums_serde() {
1105        assert_eq!(
1106            serde_json::from_str::<LighterOrderKind>(r#""take-profit-limit""#).unwrap(),
1107            LighterOrderKind::TakeProfitLimit,
1108        );
1109        assert_eq!(
1110            serde_json::from_str::<LighterOrderKind>(r#""twap-sub""#).unwrap(),
1111            LighterOrderKind::TwapSub,
1112        );
1113        assert_eq!(
1114            serde_json::from_str::<LighterOrderKind>(r#""liquidation""#).unwrap(),
1115            LighterOrderKind::Liquidation,
1116        );
1117        assert_eq!(
1118            serde_json::from_str::<LighterOrderTimeInForce>(r#""good-till-time""#).unwrap(),
1119            LighterOrderTimeInForce::GoodTillTime,
1120        );
1121        assert_eq!(
1122            serde_json::from_str::<LighterOrderTimeInForce>(r#""Unknown""#).unwrap(),
1123            LighterOrderTimeInForce::Unknown,
1124        );
1125        assert_eq!(
1126            serde_json::from_str::<LighterOrderTimeInForce>(r#""unknown""#).unwrap(),
1127            LighterOrderTimeInForce::Unknown,
1128        );
1129        assert_eq!(
1130            serde_json::to_string(&LighterOrderTimeInForce::Unknown).unwrap(),
1131            r#""Unknown""#,
1132        );
1133        assert_eq!(
1134            serde_json::from_str::<LighterOrderStatus>(r#""canceled-not-enough-liquidity""#)
1135                .unwrap(),
1136            LighterOrderStatus::CanceledNotEnoughLiquidity,
1137        );
1138        assert_eq!(
1139            serde_json::from_str::<LighterTriggerStatus>(r#""parent-order""#).unwrap(),
1140            LighterTriggerStatus::ParentOrder,
1141        );
1142        assert_eq!(
1143            serde_json::from_str::<LighterOrderSide>(r#""sell""#).unwrap(),
1144            LighterOrderSide::Sell,
1145        );
1146    }
1147
1148    #[rstest]
1149    fn test_trade_type_serde() {
1150        assert_eq!(
1151            serde_json::from_str::<LighterTradeType>(r#""market-settlement""#).unwrap(),
1152            LighterTradeType::MarketSettlement,
1153        );
1154    }
1155
1156    #[rstest]
1157    fn test_order_type_repr_serde() {
1158        assert_eq!(
1159            serde_json::to_string(&LighterOrderType::Limit).unwrap(),
1160            "0",
1161        );
1162        assert_eq!(serde_json::to_string(&LighterOrderType::Twap).unwrap(), "6",);
1163        assert_eq!(
1164            serde_json::to_string(&LighterOrderType::TwapSub).unwrap(),
1165            "7",
1166        );
1167        assert_eq!(
1168            serde_json::to_string(&LighterOrderType::Liquidation).unwrap(),
1169            "8",
1170        );
1171        let parsed: LighterOrderType = serde_json::from_str("3").unwrap();
1172        assert_eq!(parsed, LighterOrderType::StopLossLimit);
1173    }
1174
1175    #[rstest]
1176    fn test_numeric_constant_enums_repr_serde() {
1177        assert_eq!(
1178            serde_json::to_string(&LighterGroupingType::OneTriggersOneCancelsTheOther).unwrap(),
1179            "3",
1180        );
1181        assert_eq!(
1182            serde_json::to_string(&LighterCancelAllTimeInForce::AbortScheduled).unwrap(),
1183            "2",
1184        );
1185        assert_eq!(
1186            serde_json::to_string(&LighterPositionMarginMode::Isolated).unwrap(),
1187            "1",
1188        );
1189        assert_eq!(
1190            serde_json::to_string(&LighterMarginUpdateDirection::AddToIsolated).unwrap(),
1191            "1",
1192        );
1193    }
1194
1195    #[rstest]
1196    fn test_time_in_force_repr_serde() {
1197        assert_eq!(
1198            serde_json::to_string(&LighterTimeInForce::ImmediateOrCancel).unwrap(),
1199            "0",
1200        );
1201        assert_eq!(
1202            serde_json::to_string(&LighterTimeInForce::PostOnly).unwrap(),
1203            "2",
1204        );
1205    }
1206
1207    #[rstest]
1208    #[case::one_minute(LighterCandleResolution::OneMinute, "1m")]
1209    #[case::five_minute(LighterCandleResolution::FiveMinute, "5m")]
1210    #[case::fifteen_minute(LighterCandleResolution::FifteenMinute, "15m")]
1211    #[case::thirty_minute(LighterCandleResolution::ThirtyMinute, "30m")]
1212    #[case::one_hour(LighterCandleResolution::OneHour, "1h")]
1213    #[case::four_hour(LighterCandleResolution::FourHour, "4h")]
1214    #[case::twelve_hour(LighterCandleResolution::TwelveHour, "12h")]
1215    #[case::one_day(LighterCandleResolution::OneDay, "1d")]
1216    #[case::one_week(LighterCandleResolution::OneWeek, "1w")]
1217    fn test_candle_resolution_string_round_trip(
1218        #[case] resolution: LighterCandleResolution,
1219        #[case] expected: &str,
1220    ) {
1221        assert_eq!(resolution.as_str(), expected);
1222        assert_eq!(resolution.to_string(), expected);
1223        assert_eq!(
1224            serde_json::to_string(&resolution).unwrap(),
1225            format!("\"{expected}\""),
1226        );
1227        assert_eq!(
1228            serde_json::from_str::<LighterCandleResolution>(&format!("\"{expected}\"")).unwrap(),
1229            resolution,
1230        );
1231        assert_eq!(
1232            LighterCandleResolution::from_str(expected).unwrap(),
1233            resolution
1234        );
1235        assert!(resolution.interval_millis() > 0);
1236    }
1237
1238    #[rstest]
1239    #[case::one_minute(1, BarAggregation::Minute, LighterCandleResolution::OneMinute)]
1240    #[case::five_minute(5, BarAggregation::Minute, LighterCandleResolution::FiveMinute)]
1241    #[case::fifteen_minute(15, BarAggregation::Minute, LighterCandleResolution::FifteenMinute)]
1242    #[case::thirty_minute(30, BarAggregation::Minute, LighterCandleResolution::ThirtyMinute)]
1243    #[case::one_hour(1, BarAggregation::Hour, LighterCandleResolution::OneHour)]
1244    #[case::four_hour(4, BarAggregation::Hour, LighterCandleResolution::FourHour)]
1245    #[case::twelve_hour(12, BarAggregation::Hour, LighterCandleResolution::TwelveHour)]
1246    #[case::one_day(1, BarAggregation::Day, LighterCandleResolution::OneDay)]
1247    #[case::one_week(1, BarAggregation::Week, LighterCandleResolution::OneWeek)]
1248    fn test_candle_resolution_from_bar_type(
1249        #[case] step: usize,
1250        #[case] aggregation: BarAggregation,
1251        #[case] expected: LighterCandleResolution,
1252    ) {
1253        let bar_type = lighter_bar_type(
1254            step,
1255            aggregation,
1256            PriceType::Last,
1257            AggregationSource::External,
1258        );
1259
1260        assert_eq!(
1261            LighterCandleResolution::try_from(&bar_type).unwrap(),
1262            expected
1263        );
1264    }
1265
1266    #[rstest]
1267    #[case::three_minute(3, BarAggregation::Minute, "minute step")]
1268    #[case::two_hour(2, BarAggregation::Hour, "hour step")]
1269    #[case::two_day(2, BarAggregation::Day, "day step")]
1270    #[case::two_week(2, BarAggregation::Week, "week step")]
1271    #[case::one_second(1, BarAggregation::Second, "aggregation")]
1272    fn test_candle_resolution_rejects_unsupported_bars(
1273        #[case] step: usize,
1274        #[case] aggregation: BarAggregation,
1275        #[case] expected: &str,
1276    ) {
1277        let bar_type = lighter_bar_type(
1278            step,
1279            aggregation,
1280            PriceType::Last,
1281            AggregationSource::External,
1282        );
1283
1284        let err = LighterCandleResolution::try_from(&bar_type).unwrap_err();
1285        assert!(err.to_string().contains(expected));
1286    }
1287
1288    #[rstest]
1289    fn test_candle_resolution_rejects_internal_bars() {
1290        let bar_type = lighter_bar_type(
1291            1,
1292            BarAggregation::Minute,
1293            PriceType::Last,
1294            AggregationSource::Internal,
1295        );
1296
1297        let err = LighterCandleResolution::try_from(&bar_type).unwrap_err();
1298        assert!(err.to_string().contains("EXTERNAL aggregation"));
1299    }
1300
1301    #[rstest]
1302    #[case::one_minute(LighterCandleResolution::OneMinute, 1, BarAggregation::Minute)]
1303    #[case::five_minute(LighterCandleResolution::FiveMinute, 5, BarAggregation::Minute)]
1304    #[case::fifteen_minute(LighterCandleResolution::FifteenMinute, 15, BarAggregation::Minute)]
1305    #[case::thirty_minute(LighterCandleResolution::ThirtyMinute, 30, BarAggregation::Minute)]
1306    #[case::one_hour(LighterCandleResolution::OneHour, 1, BarAggregation::Hour)]
1307    #[case::four_hour(LighterCandleResolution::FourHour, 4, BarAggregation::Hour)]
1308    #[case::twelve_hour(LighterCandleResolution::TwelveHour, 12, BarAggregation::Hour)]
1309    #[case::one_day(LighterCandleResolution::OneDay, 1, BarAggregation::Day)]
1310    #[case::one_week(LighterCandleResolution::OneWeek, 1, BarAggregation::Week)]
1311    fn test_candle_resolution_to_bar_spec(
1312        #[case] resolution: LighterCandleResolution,
1313        #[case] step: usize,
1314        #[case] aggregation: BarAggregation,
1315    ) {
1316        let spec = resolution.to_bar_spec();
1317        assert_eq!(spec.step.get(), step);
1318        assert_eq!(spec.aggregation, aggregation);
1319        assert_eq!(spec.price_type, PriceType::Last);
1320    }
1321
1322    #[rstest]
1323    #[case::one_minute(LighterCandleResolution::OneMinute, true)]
1324    #[case::five_minute(LighterCandleResolution::FiveMinute, true)]
1325    #[case::fifteen_minute(LighterCandleResolution::FifteenMinute, true)]
1326    #[case::thirty_minute(LighterCandleResolution::ThirtyMinute, true)]
1327    #[case::one_hour(LighterCandleResolution::OneHour, true)]
1328    #[case::four_hour(LighterCandleResolution::FourHour, true)]
1329    #[case::twelve_hour(LighterCandleResolution::TwelveHour, true)]
1330    #[case::one_day(LighterCandleResolution::OneDay, true)]
1331    #[case::one_week(LighterCandleResolution::OneWeek, false)]
1332    fn test_candle_resolution_is_ws_streamable(
1333        #[case] resolution: LighterCandleResolution,
1334        #[case] expected: bool,
1335    ) {
1336        assert_eq!(resolution.is_ws_streamable(), expected);
1337    }
1338
1339    #[rstest]
1340    fn test_candle_resolution_rejects_non_last_price_type() {
1341        let bar_type = lighter_bar_type(
1342            1,
1343            BarAggregation::Minute,
1344            PriceType::Mark,
1345            AggregationSource::External,
1346        );
1347
1348        let err = LighterCandleResolution::try_from(&bar_type).unwrap_err();
1349        assert!(err.to_string().contains("LAST price type"));
1350    }
1351
1352    #[rstest]
1353    #[case::limit(LighterOrderType::Limit, OrderType::Limit)]
1354    #[case::market(LighterOrderType::Market, OrderType::Market)]
1355    #[case::stop_loss(LighterOrderType::StopLoss, OrderType::StopMarket)]
1356    #[case::stop_loss_limit(LighterOrderType::StopLossLimit, OrderType::StopLimit)]
1357    #[case::take_profit(LighterOrderType::TakeProfit, OrderType::MarketIfTouched)]
1358    #[case::take_profit_limit(LighterOrderType::TakeProfitLimit, OrderType::LimitIfTouched)]
1359    fn test_order_type_round_trip(#[case] lighter: LighterOrderType, #[case] nautilus: OrderType) {
1360        assert_eq!(lighter.as_nautilus().unwrap(), nautilus);
1361        assert_eq!(LighterOrderType::try_from(nautilus).unwrap(), lighter);
1362    }
1363
1364    #[rstest]
1365    #[case::twap(LighterOrderType::Twap)]
1366    #[case::twap_sub(LighterOrderType::TwapSub)]
1367    #[case::liquidation(LighterOrderType::Liquidation)]
1368    fn test_order_type_internal_variants_have_no_nautilus_mapping(
1369        #[case] order_type: LighterOrderType,
1370    ) {
1371        let err = order_type.as_nautilus().unwrap_err();
1372        assert!(
1373            err.to_string()
1374                .contains("no Nautilus order-type equivalent")
1375        );
1376    }
1377
1378    #[rstest]
1379    #[case(OrderType::TrailingStopMarket)]
1380    #[case(OrderType::TrailingStopLimit)]
1381    #[case(OrderType::MarketToLimit)]
1382    fn test_order_type_unsupported_nautilus_variants_error(#[case] nautilus: OrderType) {
1383        let err = LighterOrderType::try_from(nautilus).unwrap_err();
1384        assert!(err.to_string().contains("no Lighter order-type equivalent"));
1385    }
1386
1387    #[rstest]
1388    fn test_is_ask_round_trip() {
1389        assert!(!is_ask_from_order_side(OrderSide::Buy));
1390        assert!(is_ask_from_order_side(OrderSide::Sell));
1391        assert_eq!(order_side_from_is_ask(false), OrderSide::Buy);
1392        assert_eq!(order_side_from_is_ask(true), OrderSide::Sell);
1393    }
1394
1395    #[rstest]
1396    fn test_tx_type_repr_serde() {
1397        assert_eq!(
1398            serde_json::to_string(&LighterTxType::CreateOrder).unwrap(),
1399            "14"
1400        );
1401        assert_eq!(
1402            serde_json::to_string(&LighterTxType::CancelAllOrders).unwrap(),
1403            "16",
1404        );
1405        assert_eq!(
1406            serde_json::to_string(&LighterTxType::ApproveIntegrator).unwrap(),
1407            "45",
1408        );
1409        assert_eq!(
1410            serde_json::to_string(&LighterTxType::CreateGroupedOrders).unwrap(),
1411            "28",
1412        );
1413        assert_eq!(serde_json::to_string(&LighterTxType::Empty).unwrap(), "0");
1414        assert_eq!(
1415            serde_json::to_string(&LighterTxType::L1RegisterAsset).unwrap(),
1416            "31",
1417        );
1418        assert_eq!(
1419            serde_json::to_string(&LighterTxType::ForceBurnShares).unwrap(),
1420            "40",
1421        );
1422        assert_eq!(
1423            serde_json::to_string(&LighterTxType::UpdateMarketConfig).unwrap(),
1424            "44",
1425        );
1426    }
1427
1428    fn lighter_bar_type(
1429        step: usize,
1430        aggregation: BarAggregation,
1431        price_type: PriceType,
1432        aggregation_source: AggregationSource,
1433    ) -> BarType {
1434        BarType::new(
1435            InstrumentId::from("BTC-PERP.LIGHTER"),
1436            BarSpecification::new(step, aggregation, price_type),
1437            aggregation_source,
1438        )
1439    }
1440
1441    #[rstest]
1442    #[case(0, LighterAccountTier::Standard)]
1443    #[case(1, LighterAccountTier::Premium)]
1444    #[case(2, LighterAccountTier::Plus)]
1445    #[case(3, LighterAccountTier::Builder)]
1446    #[case(4, LighterAccountTier::Unknown(4))]
1447    #[case(255, LighterAccountTier::Unknown(255))]
1448    fn test_account_tier_from_code(#[case] code: u8, #[case] expected: LighterAccountTier) {
1449        assert_eq!(LighterAccountTier::from_code(code), expected);
1450    }
1451
1452    #[rstest]
1453    #[case(LighterAccountTier::Standard, Some(60))]
1454    #[case(LighterAccountTier::Premium, Some(24_000))]
1455    #[case(LighterAccountTier::Plus, Some(24_000))]
1456    #[case(LighterAccountTier::Builder, Some(240_000))]
1457    #[case(LighterAccountTier::Unknown(9), None)]
1458    fn test_account_tier_documented_rest_quota(
1459        #[case] tier: LighterAccountTier,
1460        #[case] expected: Option<u32>,
1461    ) {
1462        assert_eq!(tier.documented_rest_quota_per_min(), expected);
1463    }
1464
1465    #[rstest]
1466    #[case(LighterAccountTier::Standard, "Standard")]
1467    #[case(LighterAccountTier::Premium, "Premium")]
1468    #[case(LighterAccountTier::Plus, "Plus")]
1469    #[case(LighterAccountTier::Builder, "Builder")]
1470    #[case(LighterAccountTier::Unknown(7), "Unknown(7)")]
1471    fn test_account_tier_display(#[case] tier: LighterAccountTier, #[case] expected: &str) {
1472        assert_eq!(tier.to_string(), expected);
1473    }
1474}