ApiKeyPair

Struct ApiKeyPair 

Source
pub struct ApiKeyPair { /* private fields */ }

Implementations§

Source§

impl ApiKeyPair

Source

pub fn new(profile_name: String, key: String, secret: String) -> ApiKeyPair

Examples found in repository?
examples/simple_example.rs (line 10)
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
Hide additional examples
examples/account_example.rs (line 15)
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 6)
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 12)
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}
Source

pub fn profile_name(&self) -> &str

Source

pub fn key(&self) -> &str

Source

pub fn secret(&self) -> &str

Trait Implementations§

Source§

impl Clone for ApiKeyPair

Source§

fn clone(&self) -> ApiKeyPair

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ApiKeyPair

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ApiKeyPair

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,