Skip to main content

LighterWebSocketClient

Struct LighterWebSocketClient 

Source
pub struct LighterWebSocketClient { /* private fields */ }
Expand description

Outer Lighter WebSocket client.

Orchestrates the connection lifecycle and subscription bookkeeping for the Lighter streaming API. The inner feed handler runs on a dedicated tokio task and exclusively owns the underlying [WebSocketClient]; this outer type communicates with it through a command channel and consumes events over an unbounded mpsc.

Authenticated channels store their auth token in subscription_args and replay it verbatim on reconnect. That stored token stays valid because the execution client rotates it on a 6h cadence (inside the venue’s 7h TTL) by re-issuing subscribe_account, so a reconnect never replays a connect-time, potentially-expired token.

Implementations§

Source§

impl LighterWebSocketClient

Source

pub fn new( url: Option<String>, environment: LighterEnvironment, registry: Arc<MarketRegistry>, transport_backend: TransportBackend, proxy_url: Option<String>, ) -> Self

Creates a new client without connecting.

url overrides the resolved environment URL when supplied.

Source

pub fn url(&self) -> &str

Returns the resolved WebSocket URL.

Source

pub fn is_active(&self) -> bool

Returns true when the underlying connection is active.

Source

pub async fn wait_until_active( &self, timeout_secs: f64, ) -> Result<(), LighterWsError>

Waits until the underlying connection reports active, or returns an error after timeout_secs.

Polls Self::is_active every 10ms. Mirrors the documented wait_until_active contract for adapter WebSocket clients in docs/developer_guide/adapters.md.

§Errors

Returns LighterWsError::Client if the connection does not reach the active state within timeout_secs.

Source

pub fn subscription_count(&self) -> usize

Returns the count of confirmed subscriptions.

Source

pub fn instruments_cache(&self) -> Arc<DashMap<i16, InstrumentAny>>

Returns a clone of the shared instrument cache.

Source

pub fn cache_instruments(&self, instruments: Vec<(i16, InstrumentAny)>)

Caches a batch of instruments along with their venue market_index, replaying them to the handler if a connection is already established.

Source

pub fn cache_instrument(&self, market_index: i16, instrument: InstrumentAny)

Caches a single instrument and pushes it to the handler if connected.

Source

pub async fn connect(&mut self) -> Result<()>

Establishes the WebSocket connection and spawns the feed-handler task.

§Errors

Returns an error if the underlying [WebSocketClient::connect] fails or the handler cannot be initialized.

Source

pub async fn disconnect(&mut self) -> Result<(), LighterWsError>

Disconnects gracefully: signals shutdown, drains the handler, then awaits the task handle with a timeout.

§Errors

This function currently completes best-effort shutdown and returns Ok(()).

Source

pub async fn next_event(&mut self) -> Option<NautilusWsMessage>

Receives the next message from the handler, or None if the receiver has been taken or the handler has shut down.

Source

pub fn take_task_handle(&mut self) -> Option<JoinHandle<()>>

Takes the feed-handler task handle, leaving None behind.

Used by callers that connect on a cloned client and want to await the inner handler task on a different instance during disconnect.

Source

pub fn set_task_handle(&mut self, handle: JoinHandle<()>)

Installs a feed-handler task handle previously obtained from Self::take_task_handle.

Source

pub async fn subscribe_book( &self, instrument_id: InstrumentId, ) -> Result<(), LighterWsError>

Subscribe to L2 order-book updates for an instrument.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn unsubscribe_book( &self, instrument_id: InstrumentId, ) -> Result<(), LighterWsError>

Unsubscribe from L2 order-book updates.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn subscribe_book_depth10( &self, instrument_id: InstrumentId, ) -> Result<(), LighterWsError>

Subscribe to depth-10 snapshots derived from the same order_book stream as Self::subscribe_book.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn unsubscribe_book_depth10( &self, instrument_id: InstrumentId, ) -> Result<(), LighterWsError>

Unsubscribe from depth-10 snapshots.

Clears the depth-10 emission flag without tearing down the underlying order_book stream so any active deltas subscriber keeps receiving updates.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn subscribe_quotes( &self, instrument_id: InstrumentId, ) -> Result<(), LighterWsError>

Subscribe to ticker (best bid/offer) updates.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn unsubscribe_quotes( &self, instrument_id: InstrumentId, ) -> Result<(), LighterWsError>

Unsubscribe from ticker updates.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn subscribe_trades( &self, instrument_id: InstrumentId, ) -> Result<(), LighterWsError>

Subscribe to trade updates.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn unsubscribe_trades( &self, instrument_id: InstrumentId, ) -> Result<(), LighterWsError>

Unsubscribe from trade updates.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn subscribe_candles( &self, instrument_id: InstrumentId, resolution: LighterCandleResolution, ) -> Result<(), LighterWsError>

Subscribe to the candle/{market_id}/{resolution} stream for an instrument and resolution.

§Errors

Returns an error if the instrument is not registered, the resolution is not offered on the WebSocket stream, or the command cannot be queued.

Source

pub async fn unsubscribe_candles( &self, instrument_id: InstrumentId, resolution: LighterCandleResolution, ) -> Result<(), LighterWsError>

Unsubscribe from a candle stream.

§Errors

Returns an error if the instrument is not registered or the command cannot be queued.

Source

pub async fn subscribe_market_stats( &self, selection: LighterMarketSelection, ) -> Result<(), LighterWsError>

Subscribe to a market-stats stream covering all markets or a single market index.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn unsubscribe_market_stats( &self, selection: LighterMarketSelection, ) -> Result<(), LighterWsError>

Unsubscribe from a market-stats stream.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn subscribe_spot_market_stats( &self, selection: LighterMarketSelection, ) -> Result<(), LighterWsError>

Subscribe to a spot market-stats stream covering all spot markets or a single spot market index.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn unsubscribe_spot_market_stats( &self, selection: LighterMarketSelection, ) -> Result<(), LighterWsError>

Unsubscribe from a spot market-stats stream.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn subscribe_height(&self) -> Result<(), LighterWsError>

Subscribe to the chain-height stream.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn unsubscribe_height(&self) -> Result<(), LighterWsError>

Unsubscribe from the chain-height stream.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn set_execution_context( &self, account_id: AccountId, account_index: i64, ) -> Result<(), LighterWsError>

Provides the execution context the feed handler stamps onto reports parsed from account_* frames.

Without this context account frames fall back to NautilusWsMessage::Raw; once it is set the handler emits typed crate::websocket::messages::ExecutionReport and crate::websocket::messages::NautilusWsMessage::AccountState messages stamped with account_id. The account_index is used by the fill parser to determine which side of each account-trade frame the configured account took.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn subscribe_account( &self, channel: LighterWsChannel, auth_token: String, ) -> Result<(), LighterWsError>

Subscribe to a private account channel using a venue auth token.

The auth token must be a valid Lighter L2 auth signature; see the signing module for token construction. Re-issuing this with a fresh token (as the execution client’s auth-token rotation does) overwrites the stored reconnect-replay token, keeping it within the venue TTL.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn unsubscribe_account( &self, channel: LighterWsChannel, ) -> Result<(), LighterWsError>

Unsubscribe from a private account channel.

§Errors

Returns an error if the command cannot be queued.

Source

pub async fn send_tx( &self, tx_type: u8, tx_info: Box<RawValue>, ) -> Result<(), LighterWsError>

Dispatch a signed L2 transaction over the WebSocket.

tx_type is the venue’s crate::common::enums::LighterTxType discriminant; tx_info is the JSON body produced by the matching crate::signing::tx::TxInfoJson renderer. The venue confirms acceptance via the account_* streams.

§Errors

Returns an error if the command cannot be queued.

Trait Implementations§

Source§

impl Clone for LighterWebSocketClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for LighterWebSocketClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Custom Debug that redacts the auth token in subscription_args.

Authenticated channel subscriptions store the venue bearer token alongside the channel for reconnect replay; deriving Debug would otherwise print the token verbatim.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Ungil for T
where T: Send,

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more