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.
§REST
use bybit::{
BASE_URL_API_MAINNET_1, Category,
http::{Client, Config, GetTickersParams},
};
let client = Client::new(Config::new(BASE_URL_API_MAINNET_1))?;
let params = GetTickersParams {
category: Category::Linear,
symbol: Some(String::from("BTCUSDT")),
base_coin: None,
exp_date: None,
};
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, BASE_URL_API_DEMO,
http::{Client, Config, GetWalletBalanceParams},
};
let client = Client::new(Config::new(BASE_URL_API_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, but subscriptions (and, on private
streams, authentication) must be sent again after every
ws::Event::Connected:
use bybit::{
BASE_URL_STREAM_MAINNET_1, Path, Topic,
ws::{self, OutgoingMessage},
};
let url = format!("{BASE_URL_STREAM_MAINNET_1}{}", Path::PublicLinear);
let (handle, mut events) = ws::Stream::new(ws::Config::new(url));
handle.connect().await?;
while let Some(event) = events.recv().await {
match event {
ws::Event::Connected => {
let args = vec![Topic::Ticker(String::from("BTCUSDT"))];
let sub = OutgoingMessage::Subscribe { req_id: None, args };
handle.send_command(sub).await?;
}
ws::Event::Message(msg) => println!("{msg:?}"),
ws::Event::Disconnected { .. } => break,
_ => {}
}
}For private streams build the auth message with
ws::create_outgoing_message_auth_at and
http::Client::server_timestamp. 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§
Structs§
- 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 - Signer
Enums§
- Account
Type - AdlRank
Indicator - Announcement
Type - Apply
Outcome - Outcome of
OrderBookState::apply_snapshot,OrderBookState::apply_diffandOrderBookState::apply. - Cancel
Type - 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 - Convert
Account Type - Copy
Trading - Create
Type - CurAuction
Phase - DCPProduct
- Data
Recording Period - DcpFunction
- Deposit
Status - Depth
Level - Env
- Error
- Exec
Type - Extra
FeeType - Extra
SubFee Type - Interval
- Interval
Time - 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
- Maintain
Type - Margin
Mode - Margin
Trading - OcoTrigger
By - Option
Period - Option
Type - Option type.
- Order
Status - Order
Type - Pair
- Path
- Place
Type - Position
Idx - Position
Mode - Position
Status - Product
- Reject
Reason - Service
Types - Side
- Slippage
Tolerance Type - SmpType
- Spot
Hedging Status - Spot
Margin Mode - Whether Spot Margin Trade (UTA) is turned on for the account.
- State
- Status
- Stop
Order Type - Tick
Direction - Time
InForce - Topic
- Tpsl
Mode - Trade
Mode - Transfer
Status - Trigger
By - Trigger
Direction - Type
- Unified
Margin Status - Unified
Update Status - Outcome of an Upgrade to Unified Account (Pro) request.
- VipLevel
- Withdraw
Status
Constants§
- BASE_
URL_ API_ DEMO - BASE_
URL_ API_ MAINNET_ 1 - BASE_
URL_ API_ MAINNET_ 2 - BASE_
URL_ API_ MAINNET_ 3 - For Netherland users.
- BASE_
URL_ API_ MAINNET_ 4 - For Hong Kong users.
- BASE_
URL_ API_ MAINNET_ 5 - For Turkey users.
- BASE_
URL_ API_ MAINNET_ 6 - For Kazakhstan users.
- BASE_
URL_ API_ TESTNET - BASE_
URL_ STREAM_ DEMO - BASE_
URL_ STREAM_ MAINNET_ 1 - BASE_
URL_ STREAM_ MAINNET_ 2 - For Turkey users.
- BASE_
URL_ STREAM_ MAINNET_ 3 - For Kazakhstan users.
- BASE_
URL_ STREAM_ TESTNET - 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 - hmac_
sha256 - Generates HMAC using the given key and message.
- spot_
fee_ currency - timestamp
- Return milliseconds.