OrderClient

Struct OrderClient 

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

Implementations§

Source§

impl OrderClient

Source

pub fn new(client: RestClient) -> Self

Examples found in repository?
examples/trading_example.rs (line 18)
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 async fn place_order( &self, order: PlaceOrderRequest, ) -> Result<ServerResponse<PlaceOrderResponse>>

Place an order

API: POST /v5/order/create https://bybit-exchange.github.io/docs/v5/order/create-order

Examples found in repository?
examples/trading_example.rs (line 53)
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 async fn batch_place_orders( &self, category: Category, orders: Vec<PlaceOrderRequest>, ) -> Result<ServerResponse<BatchPlaceOrderResponse>>

Batch place orders (Option only)

API: POST /v5/order/create-batch https://bybit-exchange.github.io/docs/v5/order/batch-place

Source

pub async fn amend_order( &self, amend_request: AmendOrderRequest, ) -> Result<ServerResponse<AmendOrderResponse>>

Amend order

API: POST /v5/order/amend https://bybit-exchange.github.io/docs/v5/order/amend-order

Source

pub async fn batch_amend_orders( &self, category: Category, amendments: Vec<AmendOrderRequest>, ) -> Result<ServerResponse<BatchAmendOrderResponse>>

Batch amend orders (Option only)

API: POST /v5/order/amend-batch https://bybit-exchange.github.io/docs/v5/order/batch-amend

Source

pub async fn cancel_order( &self, cancel_request: CancelOrderRequest, ) -> Result<ServerResponse<CancelOrderResponse>>

Cancel order

API: POST /v5/order/cancel https://bybit-exchange.github.io/docs/v5/order/cancel-order

Examples found in repository?
examples/trading_example.rs (line 87)
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 async fn batch_cancel_orders( &self, category: Category, cancellations: Vec<CancelOrderRequest>, ) -> Result<ServerResponse<BatchCancelOrderResponse>>

Batch cancel orders (Option only)

API: POST /v5/order/cancel-batch https://bybit-exchange.github.io/docs/v5/order/batch-cancel

Source

pub async fn cancel_all_orders( &self, category: Category, symbol: Option<&str>, base_coin: Option<&str>, settle_coin: Option<&str>, order_filter: Option<&str>, ) -> Result<ServerResponse<CancelAllOrdersResponse>>

Cancel all orders

API: POST /v5/order/cancel-all https://bybit-exchange.github.io/docs/v5/order/cancel-all

Source

pub async fn get_open_orders( &self, category: Category, symbol: Option<&str>, base_coin: Option<&str>, settle_coin: Option<&str>, order_id: Option<&str>, order_link_id: Option<&str>, open_only: Option<i32>, order_filter: Option<&str>, limit: Option<i32>, cursor: Option<&str>, ) -> Result<ServerResponse<GetOrdersResponse>>

Get open orders

API: GET /v5/order/realtime https://bybit-exchange.github.io/docs/v5/order/open-order

Examples found in repository?
examples/trading_example.rs (lines 62-73)
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 async fn get_order_history( &self, category: Category, symbol: Option<&str>, base_coin: Option<&str>, settle_coin: Option<&str>, order_id: Option<&str>, order_link_id: Option<&str>, order_filter: Option<&str>, order_status: Option<&str>, start_time: Option<i64>, end_time: Option<i64>, limit: Option<i32>, cursor: Option<&str>, ) -> Result<ServerResponse<GetOrdersResponse>>

Get order history

API: GET /v5/order/history https://bybit-exchange.github.io/docs/v5/order/order-list

Examples found in repository?
examples/trading_example.rs (lines 99-112)
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 async fn get_trade_history( &self, category: Category, symbol: Option<&str>, order_id: Option<&str>, order_link_id: Option<&str>, base_coin: Option<&str>, start_time: Option<i64>, end_time: Option<i64>, exec_type: Option<&str>, limit: Option<i32>, cursor: Option<&str>, ) -> Result<ServerResponse<GetTradeHistoryResponse>>

Get trade history

API: GET /v5/execution/list https://bybit-exchange.github.io/docs/v5/order/execution

Source

pub async fn spot_borrow_check( &self, category: &str, symbol: &str, side: &str, ) -> Result<ServerResponse<Value>>

Check spot borrow quota

API: GET /v5/order/spot-borrow-check https://bybit-exchange.github.io/docs/v5/order/spot-borrow-quota

Trait Implementations§

Source§

impl Clone for OrderClient

Source§

fn clone(&self) -> OrderClient

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

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