Skip to main content

bybit_rust_api/
lib.rs

1//! # Bybit Rust API
2//!
3//! A comprehensive, type-safe Rust SDK for the [Bybit V5 API](https://bybit-exchange.github.io/docs/v5/guide).
4//!
5//! Covers **all 129 REST endpoints** across 13 modules plus
6//! **full WebSocket support** with 17 streaming channels.
7//!
8//! ## Features
9
10// Bybit API endpoints naturally have many optional parameters;
11// this is an intentional design choice for ergonomic usage.
12#![allow(clippy::too_many_arguments)]
13//!
14//! - **REST API**: 129/129 endpoints (Market, Trade, Account, Position, Asset, User, Broker, etc.)
15//! - **WebSocket Public**: Orderbook (snapshot/delta), Trade, Ticker, Kline, Liquidation
16//! - **WebSocket Private**: Position, Execution, Order, Wallet, Greeks, DCP
17//! - **WebSocket Trade**: Place, amend, cancel orders via WebSocket
18//! - **Auto-reconnect**: Exponential backoff with automatic re-subscription
19//! - **Rate limiting**: Token-bucket limiter for REST and WS
20//! - **Authentication**: HMAC-SHA256 signing (REST + WS)
21//! - **Type-safe**: Full serde types for all request/response structures
22//! - **Error handling**: Structured `BybitError` with all API error codes
23//! - **Async**: Built on tokio, implements `futures::Stream` for WS
24//!
25//! ## Quick Start
26//!
27//! ### REST (public endpoint, no API key)
28//!
29//! ```rust,no_run
30//! use bybit_rust_api::rest::{ApiKeyPair, MarketClient, RestClient};
31//! use bybit_rust_api::{Category, Interval};
32//!
33//! #[tokio::main]
34//! async fn main() -> anyhow::Result<()> {
35//!     let keys = ApiKeyPair::new("public".into(), String::new(), String::new());
36//!     let client = RestClient::new(keys, "https://api.bybit.com".into());
37//!     let market = MarketClient::new(client);
38//!
39//!     let time = market.get_server_time().await?;
40//!     println!("Server time: {}", time.result.time_second);
41//!     Ok(())
42//! }
43//! ```
44//!
45//! ### REST (private endpoint, with API key from env)
46//!
47//! ```rust,no_run
48//! use bybit_rust_api::rest::{ApiKeyPair, OrderClient, RestClient};
49//! use bybit_rust_api::rest::order::dto::PlaceOrderRequest;
50//! use bybit_rust_api::{Category, OrderType, Side};
51//!
52//! #[tokio::main]
53//! async fn main() -> anyhow::Result<()> {
54//!     dotenvy::dotenv().ok();
55//!     let keys = ApiKeyPair::from_env()?;
56//!     let client = RestClient::new(keys, "https://api.bybit.com".into());
57//!     let order = OrderClient::new(client);
58//!
59//!     let req = PlaceOrderRequest {
60//!         category: Category::Spot,
61//!         symbol: "BTCUSDT".into(),
62//!         side: Side::Buy,
63//!         order_type: OrderType::Limit,
64//!         qty: "0.001".into(),
65//!         price: Some("40000".into()),
66//!         ..Default::default()
67//!     };
68//!     let resp = order.place_order(req).await?;
69//!     println!("Order ID: {}", resp.result.order_id);
70//!     Ok(())
71//! }
72//! ```
73//!
74//! ### WebSocket (real-time streaming)
75//!
76//! ```rust,no_run
77//! use bybit_rust_api::ws::{WsClient, topics};
78//! use futures_util::StreamExt;
79//!
80//! #[tokio::main]
81//! async fn main() -> anyhow::Result<()> {
82//!     let mut client = WsClient::connect(
83//!         "wss://stream.bybit.com/v5/public/linear"
84//!     ).await?;
85//!
86//!     client.subscribe(vec![
87//!         topics::orderbook(1, "BTCUSDT"),
88//!         topics::trade("BTCUSDT"),
89//!     ]).await?;
90//!
91//!     while let Some(msg) = client.next().await {
92//!         println!("Topic: {:?}", msg.topic());
93//!     }
94//!     Ok(())
95//! }
96//! ```
97//!
98//! ### CLI
99//!
100//! ```bash
101//! cargo install bybit-rust-api
102//! bybit-cli time
103//! bybit-cli ticker BTCUSDT
104//! bybit-cli kline BTCUSDT 1h 5
105//! bybit-cli orderbook BTCUSDT 5
106//! ```
107//!
108//! ## Environment Variables
109//!
110//! | Variable | Description |
111//! |---|---|
112//! | `BYBIT_API_KEY` | API key for private endpoints |
113//! | `BYBIT_API_SECRET` | API secret for signing |
114//! | `BYBIT_TESTNET_API_KEY` | Testnet API key |
115//! | `BYBIT_TESTNET_API_SECRET` | Testnet API secret |
116//!
117//! ## Module Overview
118//!
119//! | Module | Description |
120//! |---|---|
121//! | `rest` | REST API clients (Market, Order, Account, Position, Asset, etc.) |
122//! | `ws` | WebSocket streams (public, private, trade) |
123//! | `rest::enums` | Type-safe enums (Category, Side, Interval, OrderType, etc.) |
124//! | `rest::errors` | Error types (`BybitError`, `ErrorCodes`) |
125//! | `consts` | API endpoint URLs |
126//! | `utils` | HMAC signing, rate limiter |
127//!
128//! ## Crate Features
129//!
130//! No feature flags — everything is included by default.
131//! TLS is handled via `rustls` (no OpenSSL dependency).
132
133pub mod consts;
134pub mod handlers;
135pub mod rest;
136pub mod utils;
137pub mod ws;
138
139// Re-export commonly used types at the top level
140pub use rest::{
141    AccountClient, AnnouncementsClient, ApiKeyPair, AssetClient, BrokerClient, CryptoLoanClient,
142    InstitutionalLoanClient, MarketClient, OrderClient, PositionClient, PreUpgradeClient,
143    RestClient, ServerResponse, SpotLeverageTokenClient, SpotMarginTradeClient, UserClient,
144};
145
146// Re-export common enums directly
147pub use rest::enums::{CancelType, Category, Interval, OrderStatus, OrderType, Side, TimeInForce};
148
149// Organized sub-modules for easier exploration
150pub mod enums {
151    pub use crate::rest::enums::*;
152}
153
154pub mod dto {
155    pub use crate::rest::account::dto::*;
156    pub use crate::rest::market::dto::*;
157    pub use crate::rest::order::dto::*;
158}