Skip to main content

Bybit

Struct Bybit 

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

A Bybit client over an injected HTTP transport.

Implementations§

Source§

impl Bybit

Source

pub fn sync_time(&mut self) -> Result<i64, Error>

Learn the offset between this machine’s clock and the venue’s, from GET /v5/market/time.

Explicit rather than automatic: it costs a request, and a client should not make one the caller did not ask for. Call it once after connecting, and again if the process runs long enough for drift to matter.

Returns the new offset in milliseconds (server - local).

§Errors

Returns an Error if the request fails or the response cannot be parsed.

Source

pub fn with_ws(self, ws: Box<dyn WsTransport>) -> Bybit

Attach a WebSocket transport, enabling the streaming subscriptions.

Source

pub fn with_http( http: Box<dyn HttpTransport>, options: &ExchangeOptions, ) -> Bybit

Build a public Bybit client over the given transport and options.

Source

pub fn with_credentials( http: Box<dyn HttpTransport>, options: &ExchangeOptions, credentials: Credentials, ) -> Bybit

Build an authenticated Bybit client for signed endpoints.

Source

pub fn with_clock(self, now_ms: Box<dyn Fn() -> i64 + Send + Sync>) -> Bybit

Override the timestamp source (used for deterministic signing in tests).

Source

pub fn category(&self) -> &'static str

The Bybit product category this client targets (spot/linear/inverse).

Source

pub fn wire_symbol(symbol: &Symbol) -> String

The Bybit wire symbol for a canonical Symbol (BTC/USDT -> BTCUSDT).

Source

pub fn ticker(&self, symbol: &Symbol) -> Result<Ticker, Error>

A ticker for symbol.

§Errors

Returns an Error if the request fails or the symbol is unknown.

Source

pub fn klines( &self, symbol: &Symbol, interval: &str, limit: u32, ) -> Result<Vec<Candle>, Error>

Up to limit candles for symbol at interval (unified, e.g. "1m", "1h", "1d"). Bybit returns newest-first; the result is chronological.

§Errors

Returns an Error if the request fails or a row cannot be parsed.

Source

pub fn order_book( &self, symbol: &Symbol, depth: u32, ) -> Result<OrderBookSnapshot, Error>

A depth snapshot of symbol up to depth levels per side.

§Errors

Returns an Error if the request fails or the response cannot be parsed.

Source

pub fn subscribe_trades(&mut self, symbol: &Symbol) -> Result<(), Error>

Subscribe to the public trade stream for symbol.

§Errors

Returns Error::NotConnected if no WebSocket transport is configured, or a transport error if the connection or subscription fails.

Source

pub fn subscribe_book(&mut self, symbol: &Symbol) -> Result<(), Error>

Subscribe to the order-book stream for symbol.

§Errors

See subscribe_trades.

Source

pub fn subscribe_ticker(&mut self, symbol: &Symbol) -> Result<(), Error>

Subscribe to the ticker stream for symbol.

§Errors

See subscribe_trades.

Source

pub fn subscribe_derivatives( &mut self, symbol: &Symbol, channel: DerivativesChannel, ) -> Result<(), Error>

Subscribe to a pushed derivatives channel.

Bybit publishes funding, mark and index on the same tickers stream that carries the ordinary ticker – one topic answering four questions – so both channels resolve to it and the parser emits whichever the caller subscribed to. Liquidations are allLiquidation, which reports the taker side of the forced order rather than the side of the position that was closed; that is the side this crate’s Liquidation carries, so it maps straight through.

These streams exist only on the linear (futures) venue.

§Errors

Returns an Error on a spot client, or if the subscription fails.

Source

pub fn open_interest(&self, symbol: &Symbol) -> Result<OpenInterest, Error>

The current open interest (GET /v5/market/open-interest), most recent point.

Bybit does push open interest, on the tickers stream – but only as one field among many, and only when it changes. Reading it is what gives a caller a figure at a known moment rather than whenever the venue last happened to include it.

§Errors

Returns an Error on a spot client, if the request fails, or if the venue returns no data point.

Source

pub fn long_short_ratio(&self, symbol: &Symbol) -> Result<LongShortRatio, Error>

The current long/short account ratio (GET /v5/market/account-ratio), most recent point.

Reported as account proportions summing to one, carried through as given.

§Errors

Returns an Error on a spot client, if the request fails, or if the venue returns no data point.

Source

pub fn poll_events(&mut self) -> Vec<Event>

Drain all stream events available since the last call. Non-blocking; frames that fail to parse are skipped.

Source

pub fn subscribe_user_data(&mut self) -> Result<(), Error>

Open the private user-data stream (wss://.../v5/private). Authenticates with an op:auth frame (signature = HMAC-SHA256 over GET/realtime<expires>), then subscribes to the order and wallet topics. Afterwards poll_events also surfaces the account’s own Event::OrderUpdate and Event::BalanceUpdate.

A dropped private stream is re-subscribed automatically on the next poll_events; call keepalive_user_data periodically to keep it from being dropped for inactivity.

§Errors

Returns Error::InvalidCredentials without credentials, Error::NotConnected without a WebSocket transport, or another Error if the request fails.

Source

pub fn keepalive_user_data(&mut self) -> Result<(), Error>

Send an application-level heartbeat (op:ping) on the private stream so it is not dropped for inactivity. A no-op before subscribe_user_data.

§Errors

Returns an Error if the ping cannot be sent.

Source

pub fn place_order(&self, request: &OrderRequest) -> Result<Order, Error>

Place an order. Validated locally, then sent signed. Bybit’s create endpoint returns only the ids, so the resulting Order carries the request’s own fields with the venue order id and a New status.

§Errors

Returns an Error if the order is invalid, credentials are missing, or the venue rejects it.

Source

pub fn cancel_order(&self, symbol: &Symbol, order_id: &str) -> Result<(), Error>

Cancel an open order by venue id.

§Errors

Returns an Error if credentials are missing or the venue rejects it.

Source

pub fn place_order_ws(&mut self, request: &OrderRequest) -> Result<Order, Error>

Place an order over the Bybit WebSocket trade API (order.create). Builds the same args as the REST path and exchanges them on the lazily-opened, authenticated /v5/trade connection. Bybit returns only the ids, so the resulting Order carries the request’s fields with a New status.

§Errors

Returns Error::NotConnected without a WebSocket transport, or another Error if the order is invalid or rejected.

Source

pub fn cancel_order_ws( &mut self, symbol: &Symbol, order_id: &str, ) -> Result<(), Error>

Cancel an order over the Bybit WebSocket trade API (order.cancel).

§Errors

Returns Error::NotConnected without a WebSocket transport, or another Error if the order is unknown or the request fails.

Source

pub fn query_order( &self, symbol: &Symbol, order_id: &str, ) -> Result<Order, Error>

Query a single order by venue id.

§Errors

Returns an Error if credentials are missing or the order is unknown.

Source

pub fn open_orders(&self, symbol: Option<&Symbol>) -> Result<Vec<Order>, Error>

All open orders, optionally filtered to one symbol. When unfiltered, the venue’s wire symbol is mapped back to a canonical Symbol.

§Errors

Returns an Error if credentials are missing or the request fails.

Source

pub fn balances(&self) -> Result<Vec<Balance>, Error>

Unified-account balances (assets are reported as the venue lists them).

§Errors

Returns an Error if credentials are missing or the request fails.

Source§

impl Bybit

This impl block contains no public items.

The Bybit product category for a market type.

Source§

impl Bybit

Source

pub fn positions(&self, symbol: Option<&Symbol>) -> Result<Vec<Position>, Error>

Open positions (/v5/position/list). Without a symbol filter, linear positions are queried by settle coin (USDT).

§Errors

Returns an Error if credentials are missing or the request fails.

Source

pub fn set_leverage(&self, symbol: &Symbol, leverage: u32) -> Result<(), Error>

Set the leverage for symbol (/v5/position/set-leverage).

§Errors

Returns an Error if the leverage is rejected or the request fails.

Source

pub fn set_margin_mode( &self, symbol: &Symbol, mode: MarginMode, ) -> Result<(), Error>

Set the margin mode for symbol (/v5/position/switch-isolated). Bybit couples the mode with the leverage, so the current leverage is preserved.

§Errors

Returns an Error if the change is rejected or the request fails.

Source

pub fn close_position(&self, symbol: &Symbol) -> Result<Order, Error>

Flatten the open position in symbol with a reduce-only market order.

§Errors

Returns Error::NotFound if there is no open position, or another Error if the request fails.

Source

pub fn amend_order( &self, symbol: &Symbol, order_id: &str, new_price: Option<Decimal>, new_quantity: Option<Decimal>, ) -> Result<Order, Error>

Amend a resting order’s price and/or quantity in place (/v5/order/amend), then return the refreshed order.

§Errors

Returns an Error if the order is unknown or the amend is rejected.

Source

pub fn place_batch( &self, requests: &[OrderRequest], ) -> Result<Vec<Result<Order, Error>>, Error>

Place several orders in one request (/v5/order/create-batch). Each element’s outcome is preserved: an empty returned orderId marks a rejected leg.

§Errors

Returns an Error if the batch request itself fails.

Source

pub fn cancel_batch( &self, symbol: &Symbol, order_ids: &[String], ) -> Result<(), Error>

Cancel several orders on one symbol in a single request (/v5/order/cancel-batch).

§Errors

Returns an Error if the request fails.

Trait Implementations§

Source§

impl AdvancedOrders for Bybit

Source§

fn place_oco(&mut self, _request: &OcoRequest) -> Result<Vec<Order>, Error>

Bybit has no standalone one-cancels-other order-list (take-profit/stop are attached to a position/order via takeProfit/stopLoss), so this returns an Error::Exchange.

Source§

fn amend_order( &mut self, symbol: &Symbol, order_id: &str, new_price: Option<Decimal>, new_quantity: Option<Decimal>, ) -> Result<Order, Error>

Amend a resting order’s price and/or quantity in place, returning the order as the venue reports it afterwards. None leaves that field unchanged. Venues without a native amend emulate it as cancel-replace. Read more
Source§

fn place_batch( &mut self, requests: &[OrderRequest], ) -> Result<Vec<Result<Order, Error>>, Error>

Place several orders in one request. The outer Result covers a transport/auth failure; each inner Result is that order’s own outcome, so a partially-accepted batch still returns the successes. Read more
Source§

fn cancel_batch( &mut self, symbol: &Symbol, order_ids: &[String], ) -> Result<(), Error>

Cancel several orders on one symbol in a single request. Read more
Source§

impl Debug for Bybit

Hand-written: the client holds Box<dyn HttpTransport>, Box<dyn WsTransport> and a Box<dyn Fn() -> i64> clock, none of which a derive can reach. The transports are shown by whether a connection is open rather than by value, and the credentials only by whether they are set – printing them would put secret material into every log line that formats a client.

Source§

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

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

impl Derivatives for Bybit

Source§

fn positions(&mut self, symbol: Option<&Symbol>) -> Result<Vec<Position>, Error>

Open positions, optionally filtered to one symbol; flat positions are omitted. Read more
Source§

fn set_leverage(&mut self, symbol: &Symbol, leverage: u32) -> Result<(), Error>

Set the account leverage for symbol. Read more
Source§

fn set_margin_mode( &mut self, symbol: &Symbol, mode: MarginMode, ) -> Result<(), Error>

Set the margin mode (cross / isolated) for symbol. Read more
Source§

fn close_position(&mut self, symbol: &Symbol) -> Result<Order, Error>

Flatten the open position in symbol with a reduce-only market order. Read more
Source§

impl DerivativesStream for Bybit

Source§

fn subscribe_derivatives( &mut self, symbol: &Symbol, channel: DerivativesChannel, ) -> Result<(), Error>

Subscribe to a pushed derivatives channel. Frames arrive through poll_events as Event::Derivatives. Read more
Source§

fn open_interest(&mut self, symbol: &Symbol) -> Result<OpenInterest, Error>

Read the current open interest. Polled, not pushed. Read more
Source§

fn long_short_ratio(&mut self, symbol: &Symbol) -> Result<LongShortRatio, Error>

Read the current long/short positioning ratio. Polled, not pushed. Read more
Source§

impl Exchange for Bybit

Source§

fn name(&self) -> &'static str

The venue’s lowercase identifier (e.g. "binance").
Source§

impl Execution for Bybit

Source§

fn place_order(&mut self, request: &OrderRequest) -> Result<Order, Error>

Place an order and return it as accepted by the venue. Read more
Source§

fn cancel_order(&mut self, symbol: &Symbol, order_id: &str) -> Result<(), Error>

Cancel an open order by venue id. Read more
Source§

fn query_order( &mut self, symbol: &Symbol, order_id: &str, ) -> Result<Order, Error>

Query a single order by venue id. Read more
Source§

fn open_orders(&mut self, symbol: Option<&Symbol>) -> Result<Vec<Order>, Error>

All open orders, optionally filtered to one symbol. Read more
Source§

fn balances(&mut self) -> Result<Vec<Balance>, Error>

Current account balances. Read more
Source§

impl MarketData for Bybit

Source§

fn ticker(&mut self, symbol: &Symbol) -> Result<Ticker, Error>

A point-in-time ticker for symbol. Read more
Source§

fn klines( &mut self, symbol: &Symbol, interval: &str, limit: u32, ) -> Result<Vec<Candle>, Error>

Up to limit historical candles for symbol at the given interval (e.g. "1m", "1h"). Returns wickra_core::Candles so the result feeds the indicator core directly. Read more
Source§

fn order_book( &mut self, symbol: &Symbol, depth: u32, ) -> Result<OrderBookSnapshot, Error>

A depth snapshot of symbol up to depth levels per side. Read more
Source§

fn subscribe_trades(&mut self, symbol: &Symbol) -> Result<(), Error>

Subscribe to the public trade stream for symbol. Read more
Source§

fn subscribe_book(&mut self, symbol: &Symbol) -> Result<(), Error>

Subscribe to the order-book stream for symbol. Read more
Source§

fn subscribe_ticker(&mut self, symbol: &Symbol) -> Result<(), Error>

Subscribe to the ticker stream for symbol. Read more
Source§

fn poll_events(&mut self) -> Vec<Event>

Drain all events buffered since the last call. Non-blocking: returns an empty vector when nothing is pending.
Source§

impl WsExecution for Bybit

Source§

fn place_order_ws(&mut self, request: &OrderRequest) -> Result<Order, Error>

Place an order over the WebSocket API and return it as the venue reports it. Read more
Source§

fn cancel_order_ws( &mut self, symbol: &Symbol, order_id: &str, ) -> Result<(), Error>

Cancel an order over the WebSocket API by venue id. Read more
Source§

impl WsUserData for Bybit

Source§

fn subscribe_user_data(&mut self) -> Result<(), Error>

Open the private user-data stream. After it returns, poll_events on the same client also drains the user’s order and balance events alongside the public market-data stream. Read more
Source§

fn keepalive_user_data(&mut self) -> Result<(), Error>

Keep the private user-data stream alive: refresh the venue’s session so it is not dropped for inactivity. The consumer calls this periodically (e.g. on a timer). Venues that need a REST keepalive refresh their listen key; venues that need an application-level heartbeat send a ping frame. The default is a no-op for venues that need neither. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Bybit

§

impl !Sync for Bybit

§

impl !UnwindSafe for Bybit

§

impl Freeze for Bybit

§

impl Send for Bybit

§

impl Unpin for Bybit

§

impl UnsafeUnpin for Bybit

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
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

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

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

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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

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
Source§

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
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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, !>

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.
Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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