Skip to main content

BybitWebSocketClient

Struct BybitWebSocketClient 

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

Public/market data WebSocket client for Bybit.

Implementations§

Source§

impl BybitWebSocketClient

Source

pub fn new_public(url: Option<String>, heartbeat: u64) -> Self

Creates a new Bybit public WebSocket client.

Source

pub fn set_auth_wait_timeout(&mut self, timeout: Duration)

Sets the timeout for waiting on (re)authentication before failing an authenticated operation. Defaults to AUTH_WAIT_TIMEOUT (5s).

Source

pub fn set_recv_window_ms(&self, recv_window_ms: u64)

Sets the receive window sent with WebSocket trade commands.

Source

pub fn new_public_with( product_type: BybitProductType, environment: BybitEnvironment, url: Option<String>, heartbeat: u64, transport_backend: TransportBackend, proxy_url: Option<String>, ) -> Self

Creates a new Bybit public WebSocket client targeting the specified product/environment.

Source

pub fn with_socket_control(self, control: SocketControl) -> Self

Configures socket state reporting and reconnect control.

Source

pub fn new_private( environment: BybitEnvironment, api_key: Option<String>, api_secret: Option<String>, url: Option<String>, heartbeat: u64, transport_backend: TransportBackend, proxy_url: Option<String>, ) -> Self

Creates a new Bybit private WebSocket client.

If api_key or api_secret are not provided, they will be loaded from environment variables based on the environment:

  • Demo: BYBIT_DEMO_API_KEY, BYBIT_DEMO_API_SECRET
  • Testnet: BYBIT_TESTNET_API_KEY, BYBIT_TESTNET_API_SECRET
  • Mainnet: BYBIT_API_KEY, BYBIT_API_SECRET
Source

pub fn new_trade( environment: BybitEnvironment, api_key: Option<String>, api_secret: Option<String>, url: Option<String>, heartbeat: u64, transport_backend: TransportBackend, proxy_url: Option<String>, ) -> Self

Creates a new Bybit trade WebSocket client for order operations.

If api_key or api_secret are not provided, they will be loaded from environment variables based on the environment:

  • Demo: BYBIT_DEMO_API_KEY, BYBIT_DEMO_API_SECRET
  • Testnet: BYBIT_TESTNET_API_KEY, BYBIT_TESTNET_API_SECRET
  • Mainnet: BYBIT_API_KEY, BYBIT_API_SECRET
Source

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

Establishes the WebSocket connection.

§Errors

Returns an error if the underlying WebSocket connection cannot be established, after retrying multiple times with exponential backoff.

Source

pub async fn close(&mut self) -> BybitWsResult<()>

Disconnects the WebSocket client and stops the background task.

Source

pub fn is_active(&self) -> bool

Returns a value indicating whether the client is active.

Source

pub fn is_closed(&self) -> bool

Returns a value indicating whether the client is closed.

Source

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

Waits until the WebSocket client becomes active or times out.

§Errors

Returns an error if the timeout is exceeded before the client becomes active.

Source

pub async fn subscribe(&self, topics: Vec<String>) -> BybitWsResult<()>

Subscribe to the provided topic strings.

Source

pub async fn unsubscribe(&self, topics: Vec<String>) -> BybitWsResult<()>

Unsubscribe from the provided topics.

Source

pub fn stream(&mut self) -> impl Stream<Item = BybitWsMessage> + use<>

Returns a stream of venue-typed BybitWsMessage items.

§Panics

Panics if called before Self::connect or if the stream has already been taken.

Source

pub fn subscription_count(&self) -> usize

Returns the number of currently registered subscriptions.

Source

pub fn credential(&self) -> Option<&Credential>

Returns the credential associated with this client, if any.

Source

pub fn set_account_id(&mut self, account_id: AccountId)

Sets the account ID for account message parsing.

Source

pub fn set_mm_level(&self, mm_level: u8)

Sets the account market maker level.

Source

pub fn account_id(&self) -> Option<AccountId>

Returns the account ID if set.

Source

pub fn product_type(&self) -> Option<BybitProductType>

Returns the product type for public connections.

Source

pub fn bar_types_cache(&self) -> &Arc<AtomicMap<String, BarType>>

Returns a reference to the bar types cache.

Source

pub fn cache_instrument(&self, instrument: InstrumentAny)

Adds an instrument to the shared instruments cache.

Source

pub fn instruments_snapshot(&self) -> AHashMap<Ustr, InstrumentAny>

Returns a snapshot of the instruments cache keyed by symbol.

Source

pub fn set_bars_timestamp_on_close(&self, value: bool)

Sets whether bar timestamps use the close time.

Source

pub fn bars_timestamp_on_close(&self) -> bool

Returns whether bar timestamps use the close time.

Source

pub fn add_option_greeks_sub(&self, instrument_id: InstrumentId)

Adds an instrument ID to the option greeks subscription set.

Source

pub fn remove_option_greeks_sub(&self, instrument_id: &InstrumentId)

Removes an instrument ID from the option greeks subscription set.

Source

pub fn option_greeks_subs(&self) -> &Arc<AtomicSet<InstrumentId>>

Returns a reference to the option greeks subscription set.

Source

pub fn trade_subs(&self) -> &Arc<AtomicSet<InstrumentId>>

Returns a reference to the trade subscriptions set.

Source

pub fn instruments_cache_ref(&self) -> &Arc<AtomicMap<Ustr, InstrumentAny>>

Returns a reference to the live instruments cache Arc.

Source

pub async fn subscribe_orderbook( &self, instrument_id: InstrumentId, depth: u32, ) -> BybitWsResult<()>

Subscribes to orderbook updates for a specific instrument.

§Errors

Returns an error if the subscription request fails.

§References

https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook

Source

pub async fn unsubscribe_orderbook( &self, instrument_id: InstrumentId, depth: u32, ) -> BybitWsResult<()>

Unsubscribes from orderbook updates for a specific instrument.

Source

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

Subscribes to public trade updates for a specific instrument.

§Errors

Returns an error if the subscription request fails.

§References

https://bybit-exchange.github.io/docs/v5/websocket/public/trade

Source

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

Unsubscribes from public trade updates for a specific instrument.

Source

pub async fn subscribe_ticker( &self, instrument_id: InstrumentId, ) -> BybitWsResult<()>

Subscribes to ticker updates for a specific instrument.

§Errors

Returns an error if the subscription request fails.

§References

https://bybit-exchange.github.io/docs/v5/websocket/public/ticker

Source

pub async fn unsubscribe_ticker( &self, instrument_id: InstrumentId, ) -> BybitWsResult<()>

Unsubscribes from ticker updates for a specific instrument.

Source

pub async fn subscribe_bars(&self, bar_type: BarType) -> BybitWsResult<()>

Subscribes to kline/candlestick updates for a specific instrument.

§Errors

Returns an error if the subscription request fails.

§References

https://bybit-exchange.github.io/docs/v5/websocket/public/kline

Source

pub async fn unsubscribe_bars(&self, bar_type: BarType) -> BybitWsResult<()>

Unsubscribes from kline/candlestick updates for a specific instrument.

Source

pub async fn subscribe_orders(&self) -> BybitWsResult<()>

Subscribes to order updates.

§Errors

Returns an error if the subscription request fails or if not authenticated.

§References

https://bybit-exchange.github.io/docs/v5/websocket/private/order

Source

pub async fn unsubscribe_orders(&self) -> BybitWsResult<()>

Unsubscribes from order updates.

Source

pub async fn subscribe_executions(&self) -> BybitWsResult<()>

Subscribes to execution/fill updates.

§Errors

Returns an error if the subscription request fails or if not authenticated.

§References

https://bybit-exchange.github.io/docs/v5/websocket/private/execution

Source

pub async fn unsubscribe_executions(&self) -> BybitWsResult<()>

Unsubscribes from execution/fill updates.

Source

pub async fn subscribe_executions_fast(&self) -> BybitWsResult<()>

Subscribes to fast execution updates (slim payload, lower latency).

§Errors

Returns an error if the subscription request fails or if not authenticated.

§References

https://bybit-exchange.github.io/docs/v5/websocket/private/fast-execution

Source

pub async fn unsubscribe_executions_fast(&self) -> BybitWsResult<()>

Unsubscribes from fast execution updates.

Source

pub async fn subscribe_positions(&self) -> BybitWsResult<()>

Subscribes to position updates.

§Errors

Returns an error if the subscription request fails or if not authenticated.

§References

https://bybit-exchange.github.io/docs/v5/websocket/private/position

Source

pub async fn unsubscribe_positions(&self) -> BybitWsResult<()>

Unsubscribes from position updates.

Source

pub async fn subscribe_wallet(&self) -> BybitWsResult<()>

Subscribes to wallet/balance updates.

§Errors

Returns an error if the subscription request fails or if not authenticated.

§References

https://bybit-exchange.github.io/docs/v5/websocket/private/wallet

Source

pub async fn unsubscribe_wallet(&self) -> BybitWsResult<()>

Unsubscribes from wallet/balance updates.

Source

pub async fn place_order( &self, params: BybitWsPlaceOrderParams, ) -> BybitWsResult<String>

Places an order via WebSocket, returning the request ID for correlation.

§Errors

Returns an error if the order request fails or if not authenticated.

Source

pub async fn amend_order( &self, params: BybitWsAmendOrderParams, ) -> BybitWsResult<String>

Amends an existing order via WebSocket, returning the request ID for correlation.

§Errors

Returns an error if the amend request fails or if not authenticated.

Source

pub async fn cancel_order( &self, params: BybitWsCancelOrderParams, ) -> BybitWsResult<String>

Cancels an order via WebSocket, returning the request ID for correlation.

§Errors

Returns an error if the cancel request fails or if not authenticated.

Source

pub async fn batch_place_orders( &self, orders: Vec<BybitWsPlaceOrderParams>, ) -> BybitWsResult<Vec<String>>

Batch creates multiple orders via WebSocket, returning the request ID for correlation.

§Errors

Returns an error if the batch request fails or if not authenticated.

Source

pub async fn batch_amend_orders( &self, orders: Vec<BybitWsAmendOrderParams>, ) -> BybitWsResult<Vec<String>>

Batch amends multiple orders via WebSocket.

§Errors

Returns an error if the batch request fails or if not authenticated.

Source

pub async fn batch_cancel_orders( &self, orders: Vec<BybitWsCancelOrderParams>, ) -> BybitWsResult<Vec<String>>

Batch cancels multiple orders via WebSocket, returning the request ID for correlation.

§Errors

Returns an error if the batch request fails or if not authenticated.

Source

pub async fn submit_order( &self, product_type: BybitProductType, instrument_id: InstrumentId, client_order_id: ClientOrderId, order_side: OrderSide, order_type: OrderType, quantity: Quantity, is_quote_quantity: bool, time_in_force: Option<TimeInForce>, price: Option<Price>, trigger_price: Option<Price>, trigger_type: Option<TriggerType>, post_only: Option<bool>, reduce_only: Option<bool>, is_leverage: bool, position_idx: Option<BybitPositionIdx>, bbo_side_type: Option<BybitBboSideType>, bbo_level: Option<String>, ) -> BybitWsResult<String>

Submits an order using Nautilus domain objects.

§Errors

Returns an error if order submission fails or if not authenticated.

Source

pub async fn modify_order( &self, product_type: BybitProductType, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: Option<VenueOrderId>, quantity: Option<Quantity>, price: Option<Price>, ) -> BybitWsResult<String>

Modifies an existing order using Nautilus domain objects.

§Errors

Returns an error if modification fails or if not authenticated.

Source

pub async fn cancel_order_by_id( &self, product_type: BybitProductType, instrument_id: InstrumentId, client_order_id: ClientOrderId, venue_order_id: Option<VenueOrderId>, ) -> BybitWsResult<String>

Cancels an order using Nautilus domain objects.

§Errors

Returns an error if cancellation fails or if not authenticated.

Source

pub fn build_place_order_params( &self, product_type: BybitProductType, instrument_id: InstrumentId, client_order_id: ClientOrderId, order_side: OrderSide, order_type: OrderType, quantity: Quantity, is_quote_quantity: bool, time_in_force: Option<TimeInForce>, price: Option<Price>, trigger_price: Option<Price>, trigger_type: Option<TriggerType>, post_only: Option<bool>, reduce_only: Option<bool>, is_leverage: bool, take_profit: Option<Price>, stop_loss: Option<Price>, position_idx: Option<BybitPositionIdx>, bbo_side_type: Option<BybitBboSideType>, bbo_level: Option<String>, ) -> BybitWsResult<BybitWsPlaceOrderParams>

Builds order params for placing an order.

Source

pub fn build_amend_order_params( &self, product_type: BybitProductType, instrument_id: InstrumentId, venue_order_id: Option<VenueOrderId>, client_order_id: Option<ClientOrderId>, quantity: Option<Quantity>, price: Option<Price>, ) -> BybitWsResult<BybitWsAmendOrderParams>

Builds order params for amending an order.

Source

pub fn build_cancel_order_params( &self, product_type: BybitProductType, instrument_id: InstrumentId, venue_order_id: Option<VenueOrderId>, client_order_id: Option<ClientOrderId>, ) -> BybitWsResult<BybitWsCancelOrderParams>

Builds order params for canceling an order via WebSocket.

§Errors

Returns an error if symbol parsing fails or if neither venue_order_id nor client_order_id is provided.

Trait Implementations§

Source§

impl Clone for BybitWebSocketClient

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 BybitWebSocketClient

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Drop for BybitWebSocketClient

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

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 = !

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