pub struct RestClient { /* private fields */ }Implementations§
Source§impl RestClient
impl RestClient
Sourcepub fn new(api_key_pair: ApiKeyPair, base_url: String) -> RestClient
pub fn new(api_key_pair: ApiKeyPair, base_url: String) -> RestClient
Examples found in repository?
examples/simple_example.rs (line 12)
5async fn main() -> anyhow::Result<()> {
6 println!("Bybit Rust API - Simple Example");
7 println!("{}", "=".repeat(50));
8
9 // Public endpoints (no API key required)
10 let api_key_pair = ApiKeyPair::new("public".to_string(), "".to_string(), "".to_string());
11
12 let rest_client = RestClient::new(api_key_pair, "https://api.bybit.com".to_string());
13
14 let market_client = MarketClient::new(rest_client);
15
16 // Get server time
17 println!("\n📍 Server Time:");
18 match market_client.get_server_time().await {
19 Ok(response) => {
20 println!(" Time: {}", response.result.time_second);
21 }
22 Err(e) => println!(" Error: {}", e),
23 }
24
25 // Get tickers
26 println!("\n📊 Market Tickers:");
27 match market_client
28 .get_tickers(Category::Spot, None, None, None)
29 .await
30 {
31 Ok(response) => {
32 // The response is already deserialized, just print it
33 println!(" Response received successfully: {:#?}", response);
34 }
35 Err(e) => println!(" Error: {}", e),
36 }
37
38 Ok(())
39}More examples
examples/account_example.rs (line 16)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8 let api_key = env::var("BYBIT_API_KEY").unwrap_or_else(|_| "YOUR_API_KEY".to_string());
9 let api_secret = env::var("BYBIT_API_SECRET").unwrap_or_else(|_| "YOUR_API_SECRET".to_string());
10
11 // Using testnet by default
12 let base_url = "https://api-testnet.bybit.com".to_string();
13
14 // ApiKeyPair takes (profile_name, key, secret)
15 let key_pair = ApiKeyPair::new("account_demo".to_string(), api_key, api_secret);
16 let client = RestClient::new(key_pair, base_url);
17
18 // AccountClient takes ownership of RestClient
19 let account_client = AccountClient::new(client);
20
21 println!("--- Testing get_wallet_balance ---");
22 let params = GetWalletBalanceParams {
23 account_type: AccountType::UNIFIED,
24 coin: None,
25 };
26
27 match account_client.get_wallet_balance(params).await {
28 Ok(response) => println!("Success: {:?}", response),
29 Err(e) => println!("Error: {:?}", e),
30 }
31
32 println!("\n--- Testing get_fee_rate ---");
33 match account_client.get_fee_rate("spot", None, None).await {
34 Ok(response) => println!("Success: {:?}", response),
35 Err(e) => println!("Error: {:?}", e),
36 }
37
38 Ok(())
39}examples/market_example.rs (line 9)
4async fn main() -> anyhow::Result<()> {
5 // Create API key pair (for public endpoints, you can use empty strings)
6 let api_key_pair = ApiKeyPair::new("default".to_string(), "".to_string(), "".to_string());
7
8 // Create REST client
9 let rest_client = RestClient::new(api_key_pair, "https://api.bybit.com".to_string());
10
11 // Create Market client
12 let market_client = MarketClient::new(rest_client);
13
14 // Get server time
15 println!("Getting server time...");
16 let server_time = market_client.get_server_time().await?;
17 println!("Server time: {:?}", server_time.result);
18
19 // Get BTC/USDT kline data for spot market
20 println!("\nGetting BTC/USDT kline data...");
21 let kline_data = market_client
22 .get_kline(
23 Category::Spot,
24 "BTCUSDT",
25 Interval::OneHour,
26 None,
27 None,
28 Some(10),
29 )
30 .await?;
31 println!("Kline data count: {}", kline_data.result.list.len());
32
33 // Get orderbook
34 println!("\nGetting BTC/USDT orderbook...");
35 let orderbook = market_client
36 .get_orderbook(Category::Spot, "BTCUSDT", Some(5))
37 .await?;
38 println!("Orderbook: {:?}", orderbook.result);
39
40 // Get tickers
41 println!("\nGetting tickers...");
42 let tickers = market_client
43 .get_tickers(Category::Spot, Some("BTCUSDT"), None, None)
44 .await?;
45 println!("Tickers: {:?}", tickers.result);
46
47 Ok(())
48}examples/trading_example.rs (line 15)
6async fn main() -> anyhow::Result<()> {
7 // Get API credentials from environment variables
8 let api_key = env::var("BYBIT_API_KEY").expect("BYBIT_API_KEY not set");
9 let api_secret = env::var("BYBIT_API_SECRET").expect("BYBIT_API_SECRET not set");
10
11 // Create API key pair
12 let api_key_pair = ApiKeyPair::new("trading".to_string(), api_key, api_secret);
13
14 // Create REST client for testnet
15 let rest_client = RestClient::new(api_key_pair, "https://api-testnet.bybit.com".to_string());
16
17 // Create Order client
18 let order_client = OrderClient::new(rest_client);
19
20 // Place a limit order
21 println!("Placing a limit order...");
22 let place_order_request = PlaceOrderRequest {
23 category: Category::Spot,
24 symbol: "BTCUSDT".to_string(),
25 side: Side::Buy,
26 order_type: OrderType::Limit,
27 qty: "0.001".to_string(),
28 price: Some("40000".to_string()),
29 time_in_force: Some(TimeInForce::GTC),
30 order_link_id: Some(format!("rust_sdk_test_{}", chrono::Utc::now().timestamp())),
31 is_leverage: None,
32 trigger_price: None,
33 trigger_direction: None,
34 trigger_by: None,
35 order_filter: None,
36 order_iv: None,
37 position_idx: None,
38 take_profit: None,
39 stop_loss: None,
40 tp_trigger_by: None,
41 sl_trigger_by: None,
42 reduce_only: None,
43 close_on_trigger: None,
44 smp_type: None,
45 mmp: None,
46 tpsl_mode: None,
47 tp_limit_price: None,
48 sl_limit_price: None,
49 tp_order_type: None,
50 sl_order_type: None,
51 };
52
53 match order_client.place_order(place_order_request).await {
54 Ok(response) => {
55 println!("Order placed successfully!");
56 println!("Order ID: {}", response.result.order_id);
57 println!("Order Link ID: {}", response.result.order_link_id);
58
59 // Get open orders
60 println!("\nGetting open orders...");
61 let open_orders = order_client
62 .get_open_orders(
63 Category::Spot,
64 Some("BTCUSDT"),
65 None,
66 None,
67 None,
68 None,
69 None,
70 None,
71 Some(10),
72 None,
73 )
74 .await?;
75 println!("Open orders count: {}", open_orders.result.list.len());
76
77 // Cancel the order
78 println!("\nCancelling the order...");
79 let cancel_request = CancelOrderRequest {
80 category: Category::Spot,
81 symbol: "BTCUSDT".to_string(),
82 order_id: Some(response.result.order_id.clone()),
83 order_link_id: None,
84 order_filter: None,
85 };
86
87 let cancel_response = order_client.cancel_order(cancel_request).await?;
88 println!("Order cancelled successfully!");
89 println!("Cancelled Order ID: {}", cancel_response.result.order_id);
90 }
91 Err(e) => {
92 eprintln!("Failed to place order: {}", e);
93 }
94 }
95
96 // Get order history
97 println!("\nGetting order history...");
98 let order_history = order_client
99 .get_order_history(
100 Category::Spot,
101 Some("BTCUSDT"),
102 None,
103 None,
104 None,
105 None,
106 None,
107 None,
108 None,
109 None,
110 Some(10),
111 None,
112 )
113 .await?;
114 println!("Order history count: {}", order_history.result.list.len());
115
116 Ok(())
117}pub fn with_recv_window(self, recv_window: impl Into<String>) -> Self
pub async fn get<A: DeserializeOwned>( &self, endpoint: &str, query: Value, sec_type: SecType, ) -> BybitResult<ServerResponse<A>>
pub async fn post<A: DeserializeOwned>( &self, endpoint: &str, body: Value, sec_type: SecType, ) -> BybitResult<ServerResponse<A>>
Trait Implementations§
Source§impl Clone for RestClient
impl Clone for RestClient
Source§fn clone(&self) -> RestClient
fn clone(&self) -> RestClient
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreAuto Trait Implementations§
impl Freeze for RestClient
impl !RefUnwindSafe for RestClient
impl Send for RestClient
impl Sync for RestClient
impl Unpin for RestClient
impl !UnwindSafe for RestClient
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more