Expand description
Unofficial Rust SDK for the Bybit V5 API.
The library crate is named bybit (package patisson-bybit-sdk).
http::Client: REST endpoints (market data, trading, positions, account, assets), request signing, optional local rate limiting (http::RateLimiterConfig) and clock synchronization (http::Client::sync_time).ws::Stream: WebSocket driver with automatic reconnects and heartbeat; commands go throughws::Handle, messages and connection state arrive asws::Events.OrderBookState: local order book from snapshots and deltas.AccountState: local copy of open orders, positions and wallet balances from REST snapshots and the private stream.
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(¶ms).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(¶ms).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, itshttp::Config, request parameters and responses. - ret_
code - Frequent Bybit
retCodevalues, as found inError::Api. - ws
- WebSocket streams:
ws::Stream,ws::Handle,ws::Configand the messages.
Structs§
- Account
Scope - What
AccountState::loadandAccountState::reloadfetch. - Account
State - Open orders, positions and wallet balances of one account.
- Order
Book State - Local order book, reconstructed from a depth snapshot and a stream of diffs.
- Order
Key - Identifies an order. Order ids are unique only within a category.
- Position
Key - Identifies a position: one per symbol in one-way mode, two (buy and sell) in hedge mode.
- Sensitive
String - A secret (API key or secret) whose
DebugandDisplayprintREDACTED. - Server
Clock - The Bybit server clock, estimated as the local clock plus an offset.
- Signer
- Signs REST requests (
X-BAPI-SIGN) with HMAC-SHA256.
Enums§
- Account
Type - Account type (
accountType). - AdlRank
Indicator - Auto-deleveraging rank, 0 (lowest priority) to 5 (
adlRankIndicator). - Announcement
Type - Announcement category (
announcementType). - Apply
Outcome - Outcome of
OrderBookState::apply_snapshot,OrderBookState::apply_diffandOrderBookState::apply. - Cancel
Type - Why an order was cancelled (
cancelType). - Category
- Unified Account: spot | linear | inverse | option Classic Account: linear | inverse | spot
- Change
- What
AccountState::applyand friends changed. Updates that were older than the stored data are ignored and not reported. - Contract
Type - Contract type of a derivatives instrument (
contractType). - Convert
Account Type - Account type of a convert (
accountType). - Copy
Trading - Whether a symbol supports copy trading (
copyTrading). - Create
Type - What created the order (
createType). - CurAuction
Phase - Auction phase of a pre-market contract (
curAuctionPhase). - DCPProduct
- Product of Disconnection Cancellation Protection (
product). - Data
Recording Period - Data recording period of long/short ratio data (
period). - DcpFunction
- Product of a DCP topic (
dcp.{function}). - Deposit
Status - Status of a deposit (
depositStatus). - Depth
Level - 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. - Exec
Type - Kind of execution (
execType). - Extra
FeeType - Type of an extra fee (
feeType), charged only on some regional sites. - Extra
SubFee Type - Subtype of an extra fee (
subFeeType). - Interval
- Kline interval (
interval). - Interval
Time - Interval of open interest data (
intervalTime). - Locale
- Language of announcements (
locale). - LtOrder
Status - Status of a leveraged token purchase or redemption order.
- LtOrder
Type - Whether a leveraged token order record is a purchase or a redemption.
- LtStatus
- Status of a leveraged token (
ltStatus). - Maintain
Type - Kind of system maintenance (
maintainType). - Margin
Mode - Margin mode of a unified account (
marginMode). - Margin
Trading - Whether a spot pair supports margin trading (
marginTrading). - OcoTrigger
By - Which leg triggered a spot OCO order (
ocoTriggerBy). - Option
Period - Period of option historical volatility, days (
period). - Option
Type - Option type.
- Order
Status - Order status (
orderStatus). - Order
Type - 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. - Place
Type - How an option order is placed (
placeType). - Position
Idx - Position index: one-way mode or a side of hedge mode (
positionIdx). - Position
Mode - Position mode of a symbol or settle coin (
mode). - Position
Status - Position status (
positionStatus). - Product
- Product affected by a maintenance (
product). - Reject
Reason - Why an order was rejected or cancelled by the matching engine (
rejectReason). - Service
Types - Service affected by a maintenance (
serviceTypes). - Side
- Order or trade side (
side). - Slippage
Tolerance Type - Unit of the slippage tolerance of a market order (
slippageToleranceType). - SmpType
- Self-match prevention type (
smpType). - Spot
Hedging Status - Whether spot hedging is on (
spotHedgingStatus). - Spot
Margin Mode - 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). - Stop
Order Type - Type of a conditional or TP/SL order (
stopOrderType). - Tick
Direction - Direction of the last price change (
tickDirection). - Time
InForce - How long an order stays active (
timeInForce). - Topic
- A WebSocket topic; serialized as Bybit expects, e.g.
tickers.BTCUSDTororder.linear. - Tpsl
Mode - TP/SL mode (
tpslMode). - Trade
Mode - Margin mode of a classic account position (
tradeMode). - Transfer
Status - Status of a transfer (
transferStatus). - Trigger
By - Price used to trigger a conditional order or TP/SL (
triggerBy). - Trigger
Direction - Direction the price must move to trigger a conditional order (
triggerDirection). - Type
- Type of a transaction log entry (
type). - Unified
Margin Status - Account mode (
unifiedMarginStatus). - Unified
Update Status - Outcome of an Upgrade to Unified Account (Pro) request.
- VipLevel
- VIP or PRO level of the account (
vipLevel). - Withdraw
Status - Status of a withdrawal (
withdrawStatus).
Constants§
- BASE_
URL_ API_ DEMO Deprecated - Demo trading REST.
- BASE_
URL_ API_ MAINNET_ 1 Deprecated - Mainnet REST.
- BASE_
URL_ API_ MAINNET_ 2 Deprecated - Alternative mainnet REST domain.
- BASE_
URL_ API_ MAINNET_ 3 Deprecated - For Netherland users.
- BASE_
URL_ API_ MAINNET_ 4 Deprecated - For Hong Kong users.
- BASE_
URL_ API_ MAINNET_ 5 Deprecated - For Turkey users.
- BASE_
URL_ API_ MAINNET_ 6 Deprecated - For Kazakhstan users.
- BASE_
URL_ API_ TESTNET Deprecated - Testnet REST.
- BASE_
URL_ STREAM_ DEMO Deprecated - Demo trading WebSocket (private streams only).
- BASE_
URL_ STREAM_ MAINNET_ 1 Deprecated - Mainnet WebSocket.
- BASE_
URL_ STREAM_ MAINNET_ 2 Deprecated - For Turkey users.
- BASE_
URL_ STREAM_ MAINNET_ 3 Deprecated - For Kazakhstan users.
- BASE_
URL_ STREAM_ TESTNET Deprecated - 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
authmessage valid untilexpires(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.