Skip to main content

Crate bybit

Crate bybit 

Source
Expand description

Unofficial Rust SDK for the Bybit V5 API.

The library crate is named bybit (package patisson-bybit-sdk).

Everything is async and runs on Tokio.

§TLS

REST and WebSocket use the same TLS backend, chosen with a Cargo feature (enable exactly one): rustls (default; aws-lc-rs and the operating system’s root certificates, no OpenSSL) or native-tls (OpenSSL, Schannel or Security.framework).

§REST

use bybit::{
    Category, Environment,
    http::{Client, Config, GetTickersParams},
};

let client = Client::new(Config::for_env(Environment::Mainnet))?;
let params = GetTickersParams::new(Category::Linear).with_symbol("BTCUSDT");
let tickers = client.get_tickers(&params).await?;
println!("{:?}", tickers.result);

Private endpoints need credentials. Call http::Client::sync_time once so that signed requests use the server clock even if the local clock is off:

use bybit::{
    AccountType, Environment,
    http::{Client, Config, GetWalletBalanceParams},
};

let client = Client::new(Config::for_env(Environment::Demo).credentials("API_KEY", "API_SECRET"))?;
client.sync_time().await?;
let params = GetWalletBalanceParams {
    account_type: AccountType::UNIFIED,
    coin: None,
};
let wallet = client.get_wallet_balance(&params).await?;

§WebSocket

The driver reconnects by itself and restores the topics subscribed with ws::Handle::subscribe. With ws::Config::credentials it also sends auth on every connection (using ServerClock, shared with http::Client::clock) and subscribes once it succeeded:

use bybit::{
    Environment, Topic,
    http::{Client, Config},
    ws,
};

let client = Client::new(Config::for_env(Environment::Demo))?;
client.sync_time().await?;

let config = ws::Config::private(Environment::Demo)
    .credentials("API_KEY", "API_SECRET")
    .server_clock(client.clock());
let (handle, mut events) = ws::Stream::new(config);
handle.subscribe(vec![Topic::OrderAllCategory, Topic::Wallet]).await?;
handle.connect().await?;

while let Some(event) = events.recv().await {
    match event {
        ws::Event::Message(msg) => println!("{msg:?}"),
        ws::Event::AuthFailed { .. } | ws::Event::Disconnected { .. } => break,
        _ => {}
    }
}

Public streams work the same way without credentials (ws::Config::public). See the examples, in particular account-state for AccountState and stream-orderbook for OrderBookState.

§Versioning

There are no stability guarantees yet: treat every version change as breaking and pin an exact version (patisson-bybit-sdk = "=x.y.z").

Modules§

http
REST API: http::Client, its http::Config, request parameters and responses.
ret_code
Frequent Bybit retCode values, as found in Error::Api.
ws
WebSocket streams: ws::Stream, ws::Handle, ws::Config and the messages.

Structs§

AccountScope
What AccountState::load and AccountState::reload fetch.
AccountState
Open orders, positions and wallet balances of one account.
OrderBookState
Local order book, reconstructed from a depth snapshot and a stream of diffs.
OrderKey
Identifies an order. Order ids are unique only within a category.
PositionKey
Identifies a position: one per symbol in one-way mode, two (buy and sell) in hedge mode.
SensitiveString
A secret (API key or secret) whose Debug and Display print REDACTED.
ServerClock
The Bybit server clock, estimated as the local clock plus an offset.
Signer
Signs REST requests (X-BAPI-SIGN) with HMAC-SHA256.

Enums§

AccountType
Account type (accountType).
AdlRankIndicator
Auto-deleveraging rank, 0 (lowest priority) to 5 (adlRankIndicator).
AnnouncementType
Announcement category (announcementType).
ApplyOutcome
Outcome of OrderBookState::apply_snapshot, OrderBookState::apply_diff and OrderBookState::apply.
CancelType
Why an order was cancelled (cancelType).
Category
Unified Account: spot | linear | inverse | option Classic Account: linear | inverse | spot
Change
What AccountState::apply and friends changed. Updates that were older than the stored data are ignored and not reported.
ContractType
Contract type of a derivatives instrument (contractType).
ConvertAccountType
Account type of a convert (accountType).
CopyTrading
Whether a symbol supports copy trading (copyTrading).
CreateType
What created the order (createType).
CurAuctionPhase
Auction phase of a pre-market contract (curAuctionPhase).
DCPProduct
Product of Disconnection Cancellation Protection (product).
DataRecordingPeriod
Data recording period of long/short ratio data (period).
DcpFunction
Product of a DCP topic (dcp.{function}).
DepositStatus
Status of a deposit (depositStatus).
DepthLevel
Depth of the order book stream (orderbook.{depth}.{symbol}).
Env
Environment affected by a maintenance (env).
Environment
A Bybit deployment: where to send REST requests and open WebSocket streams.
Error
Errors returned by http::Client.
ExecType
Kind of execution (execType).
ExtraFeeType
Type of an extra fee (feeType), charged only on some regional sites.
ExtraSubFeeType
Subtype of an extra fee (subFeeType).
Interval
Kline interval (interval).
IntervalTime
Interval of open interest data (intervalTime).
Locale
Language of announcements (locale).
LtOrderStatus
Status of a leveraged token purchase or redemption order.
LtOrderType
Whether a leveraged token order record is a purchase or a redemption.
LtStatus
Status of a leveraged token (ltStatus).
MaintainType
Kind of system maintenance (maintainType).
MarginMode
Margin mode of a unified account (marginMode).
MarginTrading
Whether a spot pair supports margin trading (marginTrading).
OcoTriggerBy
Which leg triggered a spot OCO order (ocoTriggerBy).
OptionPeriod
Period of option historical volatility, days (period).
OptionType
Option type.
OrderStatus
Order status (orderStatus).
OrderType
Order type (orderType).
Pair
Coin of a spot pair in which a fee is charged (see spot_fee_currency).
Path
Path of a Bybit REST endpoint or WebSocket stream, appended to the base URL of an Environment.
PlaceType
How an option order is placed (placeType).
PositionIdx
Position index: one-way mode or a side of hedge mode (positionIdx).
PositionMode
Position mode of a symbol or settle coin (mode).
PositionStatus
Position status (positionStatus).
Product
Product affected by a maintenance (product).
RejectReason
Why an order was rejected or cancelled by the matching engine (rejectReason).
ServiceTypes
Service affected by a maintenance (serviceTypes).
Side
Order or trade side (side).
SlippageToleranceType
Unit of the slippage tolerance of a market order (slippageToleranceType).
SmpType
Self-match prevention type (smpType).
SpotHedgingStatus
Whether spot hedging is on (spotHedgingStatus).
SpotMarginMode
Whether Spot Margin Trade (UTA) is turned on for the account.
State
State of a system maintenance (state).
Status
Trading status of an instrument (status).
StopOrderType
Type of a conditional or TP/SL order (stopOrderType).
TickDirection
Direction of the last price change (tickDirection).
TimeInForce
How long an order stays active (timeInForce).
Topic
A WebSocket topic; serialized as Bybit expects, e.g. tickers.BTCUSDT or order.linear.
TpslMode
TP/SL mode (tpslMode).
TradeMode
Margin mode of a classic account position (tradeMode).
TransferStatus
Status of a transfer (transferStatus).
TriggerBy
Price used to trigger a conditional order or TP/SL (triggerBy).
TriggerDirection
Direction the price must move to trigger a conditional order (triggerDirection).
Type
Type of a transaction log entry (type).
UnifiedMarginStatus
Account mode (unifiedMarginStatus).
UnifiedUpdateStatus
Outcome of an Upgrade to Unified Account (Pro) request.
VipLevel
VIP or PRO level of the account (vipLevel).
WithdrawStatus
Status of a withdrawal (withdrawStatus).

Constants§

BASE_URL_API_DEMODeprecated
Demo trading REST.
BASE_URL_API_MAINNET_1Deprecated
Mainnet REST.
BASE_URL_API_MAINNET_2Deprecated
Alternative mainnet REST domain.
BASE_URL_API_MAINNET_3Deprecated
For Netherland users.
BASE_URL_API_MAINNET_4Deprecated
For Hong Kong users.
BASE_URL_API_MAINNET_5Deprecated
For Turkey users.
BASE_URL_API_MAINNET_6Deprecated
For Kazakhstan users.
BASE_URL_API_TESTNETDeprecated
Testnet REST.
BASE_URL_STREAM_DEMODeprecated
Demo trading WebSocket (private streams only).
BASE_URL_STREAM_MAINNET_1Deprecated
Mainnet WebSocket.
BASE_URL_STREAM_MAINNET_2Deprecated
For Turkey users.
BASE_URL_STREAM_MAINNET_3Deprecated
For Kazakhstan users.
BASE_URL_STREAM_TESTNETDeprecated
Testnet WebSocket.
DEFAULT_MAX_BUFFERED_DIFFS
Default for OrderBookState::with_max_buffered.
MAX_CLOSED_ORDERS
Maximum number of closed orders remembered to reject late stream updates and stale snapshot entries for them.

Functions§

create_stream_signature
Signature of the WebSocket auth message valid until expires (milliseconds).
hmac_sha256
Generates HMAC using the given key and message.
spot_fee_currency
Coin in which the fee of a spot trade is charged: normally the coin received; with a negative maker fee rate (rebate), a maker receives the rebate in the coin paid.
timestamp
Return milliseconds.

Type Aliases§

Second
Seconds.
Timestamp
Milliseconds since the Unix epoch (Bybit timestamps).