1use std::{
21 cmp::Reverse,
22 collections::HashMap,
23 fmt::{Debug, Display},
24 num::NonZeroU32,
25 sync::{
26 Arc, LazyLock,
27 atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
28 },
29 time::Duration,
30};
31
32use ahash::{AHashMap, AHashSet};
33use anyhow::Context;
34use arc_swap::ArcSwap;
35use jiff::Timestamp;
36use nautilus_common::{cache::InstrumentLookupError, live::get_runtime};
37use nautilus_core::{
38 AtomicMap, AtomicTime, env::get_or_env_var_opt, nanos::UnixNanos,
39 time::get_atomic_clock_realtime,
40};
41use nautilus_model::{
42 data::{Bar, BarType, FundingRateUpdate, OrderBookDeltas, TradeTick},
43 enums::{MarketStatusAction, OrderSide, OrderType, PositionSide, TimeInForce},
44 events::account::state::AccountState,
45 identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, VenueOrderId},
46 instruments::{Instrument, InstrumentAny},
47 reports::{FillReport, OrderStatusReport, PositionStatusReport},
48 types::{Price, Quantity},
49};
50use nautilus_network::{
51 http::{HttpClient, HttpRedirectPolicy, Method, create_standard_nautilus_headers},
52 ratelimiter::quota::Quota,
53 retry::{RetryConfig, RetryError, RetryManager},
54};
55use rust_decimal::Decimal;
56use serde::{Serialize, de::DeserializeOwned};
57use tokio_util::sync::CancellationToken;
58use ustr::Ustr;
59
60use super::{
61 error::{BybitCancelOrderError, BybitHttpError, BybitModifyOrderError, BybitSubmitOrderError},
62 models::{
63 BybitAccountDetailsResponse, BybitAccountInfoResponse, BybitBorrowResponse,
64 BybitEscrowSubMembersResponse, BybitFeeRate, BybitFeeRateResponse, BybitFundingResponse,
65 BybitInstrumentInverse, BybitInstrumentInverseResponse, BybitInstrumentLinear,
66 BybitInstrumentLinearResponse, BybitInstrumentOption, BybitInstrumentOptionResponse,
67 BybitInstrumentSpot, BybitInstrumentSpotResponse, BybitKlinesResponse,
68 BybitNoConvertRepayResponse, BybitOpenOrdersResponse, BybitOrder,
69 BybitOrderHistoryResponse, BybitOrderbookResponse, BybitPlaceOrderResponse,
70 BybitPositionListResponse, BybitRepayResponse, BybitServerTimeResponse,
71 BybitSetLeverageResponse, BybitSetMarginModeResponse, BybitSetTradingStopResponse,
72 BybitSubApiKeyInfo, BybitSubApiKeysResponse, BybitSubMember, BybitSubMembersPagedResponse,
73 BybitSubMembersResponse, BybitSwitchModeResponse, BybitTickerData, BybitTickerOption,
74 BybitTickersOptionResponse, BybitTradeHistoryResponse, BybitTradesResponse,
75 BybitUpdateMasterApiResponse, BybitUpdateSubApiResponse, BybitWalletBalanceResponse,
76 BybitWithdrawResponse, BybitWithdrawalRecord, BybitWithdrawalRecordsResponse,
77 },
78 query::{
79 BybitAmendOrderParamsBuilder, BybitBatchAmendOrderEntryBuilder,
80 BybitBatchCancelOrderEntryBuilder, BybitBatchCancelOrderParamsBuilder,
81 BybitBatchPlaceOrderEntryBuilder, BybitBorrowParamsBuilder,
82 BybitCancelAllOrdersParamsBuilder, BybitCancelOrderParamsBuilder, BybitFeeRateParams,
83 BybitFundingParams, BybitFundingParamsBuilder, BybitInstrumentsInfoParams,
84 BybitKlinesParams, BybitKlinesParamsBuilder, BybitNativeTpSlParams,
85 BybitNoConvertRepayParamsBuilder, BybitOpenOrdersParamsBuilder,
86 BybitOrderHistoryParamsBuilder, BybitOrderbookParams, BybitOrderbookParamsBuilder,
87 BybitPlaceOrderParamsBuilder, BybitPositionListParams, BybitRepayParamsBuilder,
88 BybitSetLeverageParamsBuilder, BybitSetMarginModeParamsBuilder, BybitSetTradingStopParams,
89 BybitSubApiKeysParams, BybitSubMembersPageParams, BybitSwitchModeParamsBuilder,
90 BybitTickersParams, BybitTradeHistoryParams, BybitTradesParams, BybitTradesParamsBuilder,
91 BybitUpdateMasterApiParams, BybitUpdateSubApiParams, BybitWalletBalanceParams,
92 BybitWithdrawParams, BybitWithdrawalRecordsParams,
93 },
94 reconciliation::{ReportRead, instrument_in_scope, millis_in_window},
95};
96use crate::common::{
97 consts::{BYBIT_NAUTILUS_BROKER_ID, BYBIT_VENUE},
98 credential::{Credential, credential_env_vars},
99 enums::{
100 BybitAccountType, BybitBboSideType, BybitContractType, BybitEnvironment, BybitExecType,
101 BybitMarginMode, BybitOpenOnly, BybitOrderFilter, BybitOrderSide, BybitOrderSmpType,
102 BybitOrderStatus, BybitOrderType, BybitPositionIdx, BybitPositionMode, BybitProductType,
103 BybitRepayStatus, BybitTpSlMode,
104 },
105 models::{BybitCursorListResponse, BybitErrorCheck, BybitResponseCheck},
106 parse::{
107 bar_spec_to_bybit_interval, bybit_rejection_due_post_only, make_bybit_symbol,
108 map_time_in_force, parse_account_state, parse_fill_report, parse_funding_rate,
109 parse_inverse_instrument, parse_kline_bar, parse_linear_instrument,
110 parse_option_instrument, parse_order_status_report, parse_orderbook,
111 parse_position_status_report, parse_spot_instrument, parse_trade_tick, spot_leverage,
112 spot_market_unit, trigger_direction,
113 },
114 rate_limit::{
115 BYBIT_RATE_LIMIT_HEADER, BYBIT_RATE_LIMIT_RESET_HEADER, BYBIT_RATE_LIMIT_STATUS_HEADER,
116 BybitRateLimiter, batch_call_limit, batch_endpoint_limit, batch_send_limit, batch_weight,
117 category_from_payload,
118 },
119 retry::should_retry_http,
120 symbol::BybitSymbol,
121 urls::bybit_http_base_url,
122};
123
124const DEFAULT_RECV_WINDOW_MS: u64 = 5_000;
125
126trait BuilderResultExt<T> {
127 fn build_anyhow(self) -> anyhow::Result<T>;
128}
129
130impl<T, E: Display> BuilderResultExt<T> for Result<T, E> {
131 fn build_anyhow(self) -> anyhow::Result<T> {
132 self.map_err(|e| anyhow::anyhow!("{e}"))
133 }
134}
135
136const BYBIT_INSTRUMENTS_INFO: &str = "/v5/market/instruments-info";
137const BYBIT_ORDER_REALTIME: &str = "/v5/order/realtime";
138const BYBIT_ORDER_HISTORY: &str = "/v5/order/history";
139const BYBIT_EXECUTION_LIST: &str = "/v5/execution/list";
140const BYBIT_POSITION_LIST: &str = "/v5/position/list";
141
142#[derive(Debug, Default)]
154struct CursorWalk {
155 followed: AHashSet<String>,
156 last: Option<String>,
157}
158
159impl CursorWalk {
160 fn advance(
168 &mut self,
169 endpoint: &str,
170 cursor: Option<String>,
171 ) -> anyhow::Result<Option<String>> {
172 let Some(cursor) = cursor.filter(|cursor| !cursor.is_empty()) else {
173 return Ok(None);
174 };
175
176 anyhow::ensure!(
177 self.last.as_deref() != Some(cursor.as_str()),
178 "{endpoint} pagination cursor did not advance from {cursor:?}",
179 );
180 anyhow::ensure!(
181 self.followed.insert(cursor.clone()),
182 "{endpoint} pagination repeated cursor {cursor:?}",
183 );
184
185 self.last = Some(cursor.clone());
186
187 Ok(Some(cursor))
188 }
189}
190
191pub static BYBIT_REST_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
193 Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant")
194});
195
196pub static BYBIT_REPAY_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
198 Quota::per_second(NonZeroU32::new(1).expect("non-zero")).expect("valid constant")
199});
200
201#[cfg_attr(
206 feature = "python",
207 pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
208)]
209#[cfg_attr(
210 feature = "python",
211 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
212)]
213#[derive(Clone)]
214pub struct BybitRawHttpClient {
215 base_url: String,
216 client: Arc<ArcSwap<HttpClient>>,
217 rate_limiter: BybitRateLimiter,
218 credential: Option<Credential>,
219 mm_level: Arc<AtomicU8>,
220 mm_detection: Arc<AtomicBool>,
221 recv_window_ms: u64,
222 timeout_secs: u64,
223 proxy_url: Option<String>,
224 session_generation: Arc<AtomicU64>,
225 retry_manager: RetryManager<BybitHttpError>,
226 cancellation_token: Arc<parking_lot::Mutex<CancellationToken>>,
227}
228
229impl Default for BybitRawHttpClient {
230 fn default() -> Self {
231 Self::new(None, 60, 3, 1000, 10_000, DEFAULT_RECV_WINDOW_MS, None)
232 .expect("Failed to create default BybitRawHttpClient")
233 }
234}
235
236impl Debug for BybitRawHttpClient {
237 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
238 f.debug_struct(stringify!(BybitRawHttpClient))
239 .field("base_url", &self.base_url)
240 .field("has_credentials", &self.credential.is_some())
241 .field("recv_window_ms", &self.recv_window_ms)
242 .finish()
243 }
244}
245
246impl BybitRawHttpClient {
247 pub fn cancel_all_requests(&self) {
249 self.cancellation_token.lock().cancel();
250 }
251
252 pub fn reset_cancellation_token(&self) {
255 let mut guard = self.cancellation_token.lock();
256 *guard = CancellationToken::new();
257 }
258
259 pub fn cancellation_token(&self) -> CancellationToken {
261 self.cancellation_token.lock().clone()
262 }
263
264 pub fn new(
270 base_url: Option<String>,
271 timeout_secs: u64,
272 max_retries: u32,
273 retry_delay_ms: u64,
274 retry_delay_max_ms: u64,
275 recv_window_ms: u64,
276 proxy_url: Option<String>,
277 ) -> Result<Self, BybitHttpError> {
278 let retry_config = RetryConfig {
279 max_retries,
280 initial_delay_ms: retry_delay_ms,
281 max_delay_ms: retry_delay_max_ms,
282 backoff_factor: 2.0,
283 jitter_ms: 1000,
284 operation_timeout_ms: Some(60_000),
285 immediate_first: false,
286 max_elapsed_ms: Some(180_000),
287 };
288
289 let retry_manager = RetryManager::new(retry_config);
290 let base_url =
291 base_url.unwrap_or_else(|| bybit_http_base_url(BybitEnvironment::Mainnet).to_string());
292 let rate_limiter = BybitRateLimiter::for_http(&base_url, None, proxy_url.as_deref());
293 let client = Self::build_http_client(timeout_secs, proxy_url.clone())?;
294 let session_generation = rate_limiter.http_session_generation();
295
296 Ok(Self {
297 base_url,
298 client: Arc::new(ArcSwap::from_pointee(client)),
299 rate_limiter,
300 credential: None,
301 mm_level: Arc::new(AtomicU8::new(0)),
302 mm_detection: Arc::new(AtomicBool::new(false)),
303 recv_window_ms,
304 timeout_secs,
305 proxy_url,
306 session_generation: Arc::new(AtomicU64::new(session_generation)),
307 retry_manager,
308 cancellation_token: Arc::new(parking_lot::Mutex::new(CancellationToken::new())),
309 })
310 }
311
312 #[expect(clippy::too_many_arguments)]
318 pub fn with_credentials(
319 api_key: String,
320 api_secret: String,
321 base_url: Option<String>,
322 timeout_secs: u64,
323 max_retries: u32,
324 retry_delay_ms: u64,
325 retry_delay_max_ms: u64,
326 recv_window_ms: u64,
327 proxy_url: Option<String>,
328 ) -> Result<Self, BybitHttpError> {
329 let retry_config = RetryConfig {
330 max_retries,
331 initial_delay_ms: retry_delay_ms,
332 max_delay_ms: retry_delay_max_ms,
333 backoff_factor: 2.0,
334 jitter_ms: 1000,
335 operation_timeout_ms: Some(60_000),
336 immediate_first: false,
337 max_elapsed_ms: Some(180_000),
338 };
339
340 let retry_manager = RetryManager::new(retry_config);
341 let base_url =
342 base_url.unwrap_or_else(|| bybit_http_base_url(BybitEnvironment::Mainnet).to_string());
343 let credential = Credential::new(api_key, api_secret);
344 let rate_limiter =
345 BybitRateLimiter::for_http(&base_url, Some(credential.api_key()), proxy_url.as_deref());
346 let client = Self::build_http_client(timeout_secs, proxy_url.clone())?;
347 let session_generation = rate_limiter.http_session_generation();
348
349 Ok(Self {
350 base_url,
351 client: Arc::new(ArcSwap::from_pointee(client)),
352 rate_limiter,
353 credential: Some(credential),
354 mm_level: Arc::new(AtomicU8::new(0)),
355 mm_detection: Arc::new(AtomicBool::new(false)),
356 recv_window_ms,
357 timeout_secs,
358 proxy_url,
359 session_generation: Arc::new(AtomicU64::new(session_generation)),
360 retry_manager,
361 cancellation_token: Arc::new(parking_lot::Mutex::new(CancellationToken::new())),
362 })
363 }
364
365 #[expect(clippy::too_many_arguments)]
377 pub fn new_with_env(
378 api_key: Option<String>,
379 api_secret: Option<String>,
380 base_url: Option<String>,
381 demo: bool,
382 testnet: bool,
383 timeout_secs: u64,
384 max_retries: u32,
385 retry_delay_ms: u64,
386 retry_delay_max_ms: u64,
387 recv_window_ms: u64,
388 proxy_url: Option<String>,
389 ) -> Result<Self, BybitHttpError> {
390 let environment = if demo {
391 BybitEnvironment::Demo
392 } else if testnet {
393 BybitEnvironment::Testnet
394 } else {
395 BybitEnvironment::Mainnet
396 };
397 let base_url =
398 Some(base_url.unwrap_or_else(|| bybit_http_base_url(environment).to_string()));
399 let (key_var, secret_var) = credential_env_vars(environment);
400 let key = get_or_env_var_opt(api_key, key_var);
401 let secret = get_or_env_var_opt(api_secret, secret_var);
402
403 if let (Some(k), Some(s)) = (key, secret) {
404 Self::with_credentials(
405 k,
406 s,
407 base_url,
408 timeout_secs,
409 max_retries,
410 retry_delay_ms,
411 retry_delay_max_ms,
412 recv_window_ms,
413 proxy_url,
414 )
415 } else {
416 Self::new(
417 base_url,
418 timeout_secs,
419 max_retries,
420 retry_delay_ms,
421 retry_delay_max_ms,
422 recv_window_ms,
423 proxy_url,
424 )
425 }
426 }
427
428 fn default_headers() -> HashMap<String, String> {
429 let mut headers: HashMap<String, String> =
430 create_standard_nautilus_headers().into_iter().collect();
431 headers.insert(
432 "X-Referer".to_string(),
433 BYBIT_NAUTILUS_BROKER_ID.to_string(),
434 );
435 headers
436 }
437
438 fn build_http_client(
439 timeout_secs: u64,
440 proxy_url: Option<String>,
441 ) -> Result<HttpClient, BybitHttpError> {
442 HttpClient::builder()
443 .redirect_policy(HttpRedirectPolicy::Reject)
444 .headers(
445 create_standard_nautilus_headers()
446 .into_iter()
447 .collect::<HashMap<_, _>>(),
448 )
449 .header_keys(vec![
450 BYBIT_RATE_LIMIT_HEADER.to_string(),
451 BYBIT_RATE_LIMIT_STATUS_HEADER.to_string(),
452 BYBIT_RATE_LIMIT_RESET_HEADER.to_string(),
453 ])
454 .timeout_secs(timeout_secs)
455 .maybe_proxy_url(proxy_url)
456 .rate_limiters(Vec::new())
457 .build()
458 .map_err(|e| BybitHttpError::NetworkError(format!("Failed to create HTTP client: {e}")))
459 }
460
461 fn refresh_http_session(&self, generation: u64) -> Result<(), BybitHttpError> {
462 let current = self.session_generation.load(Ordering::Acquire);
463 if current == generation {
464 return Ok(());
465 }
466
467 let client = Self::build_http_client(self.timeout_secs, self.proxy_url.clone())?;
468 self.client.store(Arc::new(client));
469 self.session_generation.store(generation, Ordering::Release);
470 Ok(())
471 }
472
473 fn request_rate_limit(
474 endpoint: &str,
475 payload: Option<&str>,
476 ) -> (Option<BybitProductType>, u32) {
477 let category = category_from_payload(payload);
478 let weight = if endpoint.ends_with("-batch") {
479 let order_count = payload
480 .and_then(|payload| serde_json::from_str::<serde_json::Value>(payload).ok())
481 .and_then(|value| value.get("request")?.as_array().map(Vec::len))
482 .unwrap_or(1);
483 category.map_or(1, |category| batch_weight(category, order_count))
484 } else {
485 1
486 };
487 (category, weight)
488 }
489
490 fn observe_rate_limit_headers(
491 &self,
492 endpoint: &str,
493 category: Option<BybitProductType>,
494 headers: &HashMap<String, String>,
495 ) {
496 let Some(limit) = headers
497 .get(BYBIT_RATE_LIMIT_HEADER)
498 .and_then(|value| value.parse::<u32>().ok())
499 else {
500 return;
501 };
502 let Some(remaining) = headers
503 .get(BYBIT_RATE_LIMIT_STATUS_HEADER)
504 .and_then(|value| value.parse::<u32>().ok())
505 else {
506 return;
507 };
508 let reset_timestamp_ms = headers
509 .get(BYBIT_RATE_LIMIT_RESET_HEADER)
510 .and_then(|value| value.parse::<i64>().ok());
511 self.rate_limiter
512 .observe_account(endpoint, category, limit, remaining, reset_timestamp_ms);
513 }
514
515 fn is_rate_limit_403(status: u16, body: &str) -> bool {
516 status == 403 && body.to_ascii_lowercase().contains("access too frequent")
517 }
518
519 fn sign_request(
520 &self,
521 timestamp: &str,
522 params: Option<&str>,
523 ) -> Result<HashMap<String, String>, BybitHttpError> {
524 let credential = self
525 .credential
526 .as_ref()
527 .ok_or(BybitHttpError::MissingCredentials)?;
528
529 let signature = credential.sign_with_payload(timestamp, self.recv_window_ms, params);
530
531 let mut headers = HashMap::new();
532 headers.insert(
533 "X-BAPI-API-KEY".to_string(),
534 credential.api_key().to_string(),
535 );
536 headers.insert("X-BAPI-TIMESTAMP".to_string(), timestamp.to_string());
537 headers.insert("X-BAPI-SIGN".to_string(), signature);
538 headers.insert(
539 "X-BAPI-RECV-WINDOW".to_string(),
540 self.recv_window_ms.to_string(),
541 );
542
543 Ok(headers)
544 }
545
546 async fn send_request<T: DeserializeOwned + BybitResponseCheck, P: Serialize>(
547 &self,
548 method: Method,
549 endpoint: &str,
550 params: Option<&P>,
551 body: Option<Vec<u8>>,
552 authenticate: bool,
553 ) -> Result<T, BybitHttpError> {
554 self.dispatch(method, endpoint, params, body, authenticate, true)
555 .await
556 }
557
558 async fn send_request_once<T: DeserializeOwned + BybitResponseCheck, P: Serialize>(
559 &self,
560 method: Method,
561 endpoint: &str,
562 params: Option<&P>,
563 body: Option<Vec<u8>>,
564 authenticate: bool,
565 ) -> Result<T, BybitHttpError> {
566 self.dispatch(method, endpoint, params, body, authenticate, false)
567 .await
568 }
569
570 async fn dispatch<T: DeserializeOwned + BybitResponseCheck, P: Serialize>(
571 &self,
572 method: Method,
573 endpoint: &str,
574 params: Option<&P>,
575 body: Option<Vec<u8>>,
576 authenticate: bool,
577 retry: bool,
578 ) -> Result<T, BybitHttpError> {
579 let endpoint = endpoint.to_string();
580 let url = format!("{}{endpoint}", self.base_url);
581 let method_clone = method.clone();
582 let body_clone = body.clone();
583
584 let params_str = if method == Method::GET {
586 params
587 .map(serde_urlencoded::to_string)
588 .transpose()
589 .map_err(|e| {
590 BybitHttpError::JsonError(format!("Failed to serialize params: {e}"))
591 })?
592 } else {
593 None
594 };
595
596 let operation = || {
597 let url = url.clone();
598 let method = method_clone.clone();
599 let body = body_clone.clone();
600 let endpoint = endpoint.clone();
601 let params_str = params_str.clone();
602
603 async move {
604 let full_url = if let Some(ref query) = params_str {
605 if query.is_empty() {
606 url
607 } else {
608 format!("{url}?{query}")
609 }
610 } else {
611 url
612 };
613
614 let sign_payload = if method == Method::GET {
615 params_str.as_deref()
616 } else {
617 body.as_ref()
618 .and_then(|body| std::str::from_utf8(body).ok())
619 };
620 let (category, weight) = Self::request_rate_limit(&endpoint, sign_payload);
621
622 let generation = self.rate_limiter.http_session_generation();
623 self.refresh_http_session(generation)?;
624 self.rate_limiter
625 .acquire_http(&endpoint, category, weight, authenticate)
626 .await
627 .map_err(BybitHttpError::ValidationError)?;
628 let generation = self.rate_limiter.http_session_generation();
629 self.refresh_http_session(generation)?;
630
631 let mut headers = Self::default_headers();
632
633 if endpoint == "/v5/order/create" {
634 self.start_mm_detection();
635 let mm_level = self.mm_level();
636 if mm_level > 0
637 && body.as_ref().is_some_and(|body| {
638 serde_json::from_slice::<serde_json::Value>(body).is_ok_and(|value| {
639 value["timeInForce"].as_str() == Some("PostOnly")
640 })
641 })
642 {
643 headers.remove("X-Referer");
644 }
645 }
646
647 if authenticate {
648 let timestamp = get_atomic_clock_realtime().get_time_ms().to_string();
649 let auth_headers = self.sign_request(×tamp, sign_payload)?;
650 headers.extend(auth_headers);
651 }
652
653 if method == Method::POST || method == Method::PUT {
654 headers.insert("Content-Type".to_string(), "application/json".to_string());
655 }
656
657 let response = self
658 .client
659 .load()
660 .request(method, full_url, None, Some(headers), body, None, None)
661 .await?;
662
663 self.observe_rate_limit_headers(&endpoint, category, &response.headers);
664
665 if response.status.as_u16() >= 400 {
666 let body = String::from_utf8_lossy(&response.body).to_string();
667 if Self::is_rate_limit_403(response.status.as_u16(), &body) {
668 let generation = self.rate_limiter.reset_http_sessions();
669 self.refresh_http_session(generation)?;
670 }
671 return Err(BybitHttpError::UnexpectedStatus {
672 status: response.status.as_u16(),
673 body,
674 });
675 }
676
677 match serde_json::from_slice::<T>(&response.body) {
679 Ok(result) => {
680 if result.ret_code() != 0 {
682 return Err(BybitHttpError::BybitError {
683 error_code: result.ret_code() as i32,
684 message: result.ret_msg().to_string(),
685 });
686 }
687 Ok(result)
688 }
689 Err(json_err) => {
690 if let Ok(error_check) =
693 serde_json::from_slice::<BybitErrorCheck>(&response.body)
694 && error_check.ret_code != 0
695 {
696 return Err(BybitHttpError::BybitError {
697 error_code: error_check.ret_code as i32,
698 message: error_check.ret_msg,
699 });
700 }
701 Err(json_err.into())
703 }
704 }
705 }
706 };
707
708 let retry = retry && Self::method_may_retry(&method);
711 let should_retry = |e: &BybitHttpError| retry && should_retry_http(e);
712
713 let create_error = |error: RetryError| -> BybitHttpError {
714 match error {
715 RetryError::Canceled => {
716 BybitHttpError::Canceled("Adapter disconnecting or shutting down".to_string())
717 }
718 error => BybitHttpError::NetworkError(error.to_string()),
719 }
720 };
721
722 let token = self.cancellation_token();
723
724 self.retry_manager
725 .invocation(endpoint.as_str(), operation, should_retry, create_error)
726 .cancellation_token(&token)
727 .execute()
728 .await
729 }
730
731 fn method_may_retry(method: &Method) -> bool {
732 matches!(method, &Method::GET | &Method::HEAD)
733 }
734
735 #[cfg(test)]
736 fn build_path<S: Serialize>(base: &str, params: &S) -> Result<String, BybitHttpError> {
737 let query = serde_urlencoded::to_string(params)
738 .map_err(|e| BybitHttpError::JsonError(e.to_string()))?;
739
740 if query.is_empty() {
741 Ok(base.to_owned())
742 } else {
743 Ok(format!("{base}?{query}"))
744 }
745 }
746
747 pub async fn get_server_time(&self) -> Result<BybitServerTimeResponse, BybitHttpError> {
757 self.send_request::<_, ()>(Method::GET, "/v5/market/time", None, None, false)
758 .await
759 }
760
761 pub async fn get_instruments<T: DeserializeOwned + BybitResponseCheck>(
771 &self,
772 params: &BybitInstrumentsInfoParams,
773 ) -> Result<T, BybitHttpError> {
774 self.send_request(
775 Method::GET,
776 BYBIT_INSTRUMENTS_INFO,
777 Some(params),
778 None,
779 false,
780 )
781 .await
782 }
783
784 pub async fn get_instruments_spot(
794 &self,
795 params: &BybitInstrumentsInfoParams,
796 ) -> Result<BybitInstrumentSpotResponse, BybitHttpError> {
797 self.get_instruments(params).await
798 }
799
800 pub async fn get_instruments_linear(
810 &self,
811 params: &BybitInstrumentsInfoParams,
812 ) -> Result<BybitInstrumentLinearResponse, BybitHttpError> {
813 self.get_instruments(params).await
814 }
815
816 pub async fn get_instruments_inverse(
826 &self,
827 params: &BybitInstrumentsInfoParams,
828 ) -> Result<BybitInstrumentInverseResponse, BybitHttpError> {
829 self.get_instruments(params).await
830 }
831
832 pub async fn get_instruments_option(
842 &self,
843 params: &BybitInstrumentsInfoParams,
844 ) -> Result<BybitInstrumentOptionResponse, BybitHttpError> {
845 self.get_instruments(params).await
846 }
847
848 pub async fn get_klines(
858 &self,
859 params: &BybitKlinesParams,
860 ) -> Result<BybitKlinesResponse, BybitHttpError> {
861 self.send_request(Method::GET, "/v5/market/kline", Some(params), None, false)
862 .await
863 }
864
865 pub async fn get_recent_trades(
875 &self,
876 params: &BybitTradesParams,
877 ) -> Result<BybitTradesResponse, BybitHttpError> {
878 self.send_request(
879 Method::GET,
880 "/v5/market/recent-trade",
881 Some(params),
882 None,
883 false,
884 )
885 .await
886 }
887
888 pub async fn get_funding_history(
898 &self,
899 params: &BybitFundingParams,
900 ) -> Result<BybitFundingResponse, BybitHttpError> {
901 self.send_request(
902 Method::GET,
903 "/v5/market/funding/history",
904 Some(params),
905 None,
906 false,
907 )
908 .await
909 }
910
911 pub async fn get_orderbook(
921 &self,
922 params: &BybitOrderbookParams,
923 ) -> Result<BybitOrderbookResponse, BybitHttpError> {
924 self.send_request(
925 Method::GET,
926 "/v5/market/orderbook",
927 Some(params),
928 None,
929 false,
930 )
931 .await
932 }
933
934 #[expect(clippy::too_many_arguments)]
948 pub async fn get_open_orders(
949 &self,
950 category: BybitProductType,
951 symbol: Option<String>,
952 base_coin: Option<String>,
953 settle_coin: Option<String>,
954 order_id: Option<String>,
955 order_link_id: Option<String>,
956 open_only: Option<BybitOpenOnly>,
957 order_filter: Option<BybitOrderFilter>,
958 limit: Option<u32>,
959 cursor: Option<String>,
960 ) -> Result<BybitOpenOrdersResponse, BybitHttpError> {
961 let mut builder = BybitOpenOrdersParamsBuilder::default();
962 builder.category(category);
963
964 if let Some(s) = symbol {
965 builder.symbol(s);
966 }
967
968 if let Some(bc) = base_coin {
969 builder.base_coin(bc);
970 }
971
972 if let Some(sc) = settle_coin {
973 builder.settle_coin(sc);
974 }
975
976 if let Some(oi) = order_id {
977 builder.order_id(oi);
978 }
979
980 if let Some(ol) = order_link_id {
981 builder.order_link_id(ol);
982 }
983
984 if let Some(oo) = open_only {
985 builder.open_only(oo);
986 }
987
988 if let Some(of) = order_filter {
989 builder.order_filter(of);
990 }
991
992 if let Some(l) = limit {
993 builder.limit(l);
994 }
995
996 if let Some(c) = cursor {
997 builder.cursor(c);
998 }
999
1000 let params = builder
1001 .build()
1002 .expect("Failed to build BybitOpenOrdersParams");
1003
1004 self.send_request(Method::GET, BYBIT_ORDER_REALTIME, Some(¶ms), None, true)
1005 .await
1006 }
1007
1008 pub async fn place_order(
1018 &self,
1019 request: &serde_json::Value,
1020 ) -> Result<BybitPlaceOrderResponse, BybitHttpError> {
1021 let body = serde_json::to_vec(request)?;
1022 self.send_request::<_, ()>(Method::POST, "/v5/order/create", None, Some(body), true)
1023 .await
1024 }
1025
1026 pub async fn get_wallet_balance(
1036 &self,
1037 params: &BybitWalletBalanceParams,
1038 ) -> Result<BybitWalletBalanceResponse, BybitHttpError> {
1039 self.send_request(
1040 Method::GET,
1041 "/v5/account/wallet-balance",
1042 Some(params),
1043 None,
1044 true,
1045 )
1046 .await
1047 }
1048
1049 pub async fn get_account_info(&self) -> Result<BybitAccountInfoResponse, BybitHttpError> {
1059 self.send_request::<_, ()>(Method::GET, "/v5/account/info", None, None, true)
1060 .await
1061 }
1062
1063 pub async fn get_account_details(&self) -> Result<BybitAccountDetailsResponse, BybitHttpError> {
1073 let response: BybitAccountDetailsResponse = self
1074 .send_request::<_, ()>(Method::GET, "/v5/user/query-api", None, None, true)
1075 .await?;
1076 self.mm_level
1077 .store(response.result.mkt_maker_level, Ordering::Release);
1078 self.mm_detection.store(true, Ordering::Release);
1079 Ok(response)
1080 }
1081
1082 fn start_mm_detection(&self) {
1083 if self
1084 .mm_detection
1085 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
1086 .is_ok()
1087 {
1088 let client = self.clone();
1089 get_runtime().spawn(async move {
1090 if let Err(e) = client.get_account_details().await {
1091 log::debug!(
1092 "Failed to detect market-maker level; retaining broker attribution: {e}"
1093 );
1094 }
1095 });
1096 }
1097 }
1098
1099 fn mm_level(&self) -> u8 {
1100 self.mm_level.load(Ordering::Acquire)
1101 }
1102
1103 pub async fn update_sub_api_key(
1113 &self,
1114 params: &BybitUpdateSubApiParams,
1115 ) -> Result<BybitUpdateSubApiResponse, BybitHttpError> {
1116 let body = serde_json::to_vec(params)?;
1117 self.send_request::<_, ()>(
1118 Method::POST,
1119 "/v5/user/update-sub-api",
1120 None,
1121 Some(body),
1122 true,
1123 )
1124 .await
1125 }
1126
1127 pub async fn update_master_api_key(
1137 &self,
1138 params: &BybitUpdateMasterApiParams,
1139 ) -> Result<BybitUpdateMasterApiResponse, BybitHttpError> {
1140 let body = serde_json::to_vec(params)?;
1141 self.send_request::<_, ()>(Method::POST, "/v5/user/update-api", None, Some(body), true)
1142 .await
1143 }
1144
1145 pub async fn get_sub_members(&self) -> Result<BybitSubMembersResponse, BybitHttpError> {
1155 self.send_request::<_, ()>(Method::GET, "/v5/user/query-sub-members", None, None, true)
1156 .await
1157 }
1158
1159 pub async fn get_sub_members_paged(
1169 &self,
1170 params: &BybitSubMembersPageParams,
1171 ) -> Result<BybitSubMembersPagedResponse, BybitHttpError> {
1172 self.send_request(Method::GET, "/v5/user/submembers", Some(params), None, true)
1173 .await
1174 }
1175
1176 pub async fn get_escrow_sub_members(
1186 &self,
1187 params: &BybitSubMembersPageParams,
1188 ) -> Result<BybitEscrowSubMembersResponse, BybitHttpError> {
1189 self.send_request(
1190 Method::GET,
1191 "/v5/user/escrow_sub_members",
1192 Some(params),
1193 None,
1194 true,
1195 )
1196 .await
1197 }
1198
1199 pub async fn get_sub_api_keys(
1209 &self,
1210 params: &BybitSubApiKeysParams,
1211 ) -> Result<BybitSubApiKeysResponse, BybitHttpError> {
1212 self.send_request(
1213 Method::GET,
1214 "/v5/user/sub-apikeys",
1215 Some(params),
1216 None,
1217 true,
1218 )
1219 .await
1220 }
1221
1222 pub async fn fetch_all_sub_members_paged(
1229 &self,
1230 page_size: Option<u32>,
1231 ) -> Result<Vec<BybitSubMember>, BybitHttpError> {
1232 let mut members = Vec::new();
1233 let mut cursor: Option<String> = None;
1234
1235 loop {
1236 let params = BybitSubMembersPageParams {
1237 page_size,
1238 next_cursor: cursor.take(),
1239 };
1240 let mut page = self.get_sub_members_paged(¶ms).await?;
1241 let next = page.result.continuation_cursor().map(str::to_owned);
1242 members.append(&mut page.result.sub_members);
1243
1244 match next {
1245 Some(c) => cursor = Some(c),
1246 None => break,
1247 }
1248 }
1249
1250 Ok(members)
1251 }
1252
1253 pub async fn fetch_all_escrow_sub_members(
1261 &self,
1262 page_size: Option<u32>,
1263 ) -> Result<Vec<BybitSubMember>, BybitHttpError> {
1264 let mut members = Vec::new();
1265 let mut cursor: Option<String> = None;
1266
1267 loop {
1268 let params = BybitSubMembersPageParams {
1269 page_size,
1270 next_cursor: cursor.take(),
1271 };
1272 let mut page = self.get_escrow_sub_members(¶ms).await?;
1273 let next = page.result.continuation_cursor().map(str::to_owned);
1274 members.append(&mut page.result.sub_members);
1275
1276 match next {
1277 Some(c) => cursor = Some(c),
1278 None => break,
1279 }
1280 }
1281
1282 Ok(members)
1283 }
1284
1285 pub async fn fetch_all_sub_api_keys(
1293 &self,
1294 sub_member_id: impl Into<String>,
1295 limit: Option<u32>,
1296 ) -> Result<Vec<BybitSubApiKeyInfo>, BybitHttpError> {
1297 let sub_member_id = sub_member_id.into();
1298 let mut keys = Vec::new();
1299 let mut cursor: Option<String> = None;
1300
1301 loop {
1302 let params = BybitSubApiKeysParams {
1303 sub_member_id: sub_member_id.clone(),
1304 limit,
1305 cursor: cursor.take(),
1306 };
1307 let mut page = self.get_sub_api_keys(¶ms).await?;
1308 let next = page.result.continuation_cursor().map(str::to_owned);
1309 keys.append(&mut page.result.keys);
1310
1311 match next {
1312 Some(c) => cursor = Some(c),
1313 None => break,
1314 }
1315 }
1316
1317 Ok(keys)
1318 }
1319
1320 pub async fn get_fee_rate(
1330 &self,
1331 params: &BybitFeeRateParams,
1332 ) -> Result<BybitFeeRateResponse, BybitHttpError> {
1333 self.send_request(
1334 Method::GET,
1335 "/v5/account/fee-rate",
1336 Some(params),
1337 None,
1338 true,
1339 )
1340 .await
1341 }
1342
1343 pub async fn set_margin_mode(
1360 &self,
1361 margin_mode: BybitMarginMode,
1362 ) -> Result<BybitSetMarginModeResponse, BybitHttpError> {
1363 let params = BybitSetMarginModeParamsBuilder::default()
1364 .set_margin_mode(margin_mode)
1365 .build()
1366 .expect("Failed to build BybitSetMarginModeParams");
1367
1368 let body = serde_json::to_vec(¶ms)?;
1369 self.send_request::<_, ()>(
1370 Method::POST,
1371 "/v5/account/set-margin-mode",
1372 None,
1373 Some(body),
1374 true,
1375 )
1376 .await
1377 }
1378
1379 pub async fn set_leverage(
1396 &self,
1397 product_type: BybitProductType,
1398 symbol: &str,
1399 buy_leverage: &str,
1400 sell_leverage: &str,
1401 ) -> Result<BybitSetLeverageResponse, BybitHttpError> {
1402 let params = BybitSetLeverageParamsBuilder::default()
1403 .category(product_type)
1404 .symbol(symbol.to_string())
1405 .buy_leverage(buy_leverage.to_string())
1406 .sell_leverage(sell_leverage.to_string())
1407 .build()
1408 .expect("Failed to build BybitSetLeverageParams");
1409
1410 let body = serde_json::to_vec(¶ms)?;
1411 self.send_request::<_, ()>(
1412 Method::POST,
1413 "/v5/position/set-leverage",
1414 None,
1415 Some(body),
1416 true,
1417 )
1418 .await
1419 }
1420
1421 pub async fn switch_mode(
1438 &self,
1439 product_type: BybitProductType,
1440 mode: BybitPositionMode,
1441 symbol: Option<String>,
1442 coin: Option<String>,
1443 ) -> Result<BybitSwitchModeResponse, BybitHttpError> {
1444 let mut builder = BybitSwitchModeParamsBuilder::default();
1445 builder.category(product_type);
1446 builder.mode(mode);
1447
1448 if let Some(s) = symbol {
1449 builder.symbol(s);
1450 }
1451
1452 if let Some(c) = coin {
1453 builder.coin(c);
1454 }
1455
1456 let params = builder
1457 .build()
1458 .expect("Failed to build BybitSwitchModeParams");
1459
1460 let body = serde_json::to_vec(¶ms)?;
1461 self.send_request::<_, ()>(
1462 Method::POST,
1463 "/v5/position/switch-mode",
1464 None,
1465 Some(body),
1466 true,
1467 )
1468 .await
1469 }
1470
1471 pub async fn set_trading_stop(
1484 &self,
1485 params: &BybitSetTradingStopParams,
1486 ) -> Result<BybitSetTradingStopResponse, BybitHttpError> {
1487 let body = serde_json::to_vec(params)?;
1488 self.send_request::<_, ()>(
1489 Method::POST,
1490 "/v5/position/trading-stop",
1491 None,
1492 Some(body),
1493 true,
1494 )
1495 .await
1496 }
1497
1498 pub async fn borrow(
1515 &self,
1516 coin: &str,
1517 amount: &str,
1518 ) -> Result<BybitBorrowResponse, BybitHttpError> {
1519 let params = BybitBorrowParamsBuilder::default()
1520 .coin(coin.to_string())
1521 .amount(amount.to_string())
1522 .build()
1523 .expect("Failed to build BybitBorrowParams");
1524
1525 let body = serde_json::to_vec(¶ms)?;
1526 self.send_request::<_, ()>(Method::POST, "/v5/account/borrow", None, Some(body), true)
1527 .await
1528 }
1529
1530 pub async fn no_convert_repay(
1548 &self,
1549 coin: &str,
1550 amount: Option<&str>,
1551 ) -> Result<BybitNoConvertRepayResponse, BybitHttpError> {
1552 let mut builder = BybitNoConvertRepayParamsBuilder::default();
1553 builder.coin(coin.to_string());
1554
1555 if let Some(amt) = amount {
1556 builder.amount(amt.to_string());
1557 }
1558
1559 let params = builder
1560 .build()
1561 .expect("Failed to build BybitNoConvertRepayParams");
1562
1563 if let Ok(params_json) = serde_json::to_string(¶ms) {
1564 log::debug!("Repay request params: {params_json}");
1565 }
1566
1567 let body = serde_json::to_vec(¶ms)?;
1568 let result = self
1569 .send_request::<_, ()>(
1570 Method::POST,
1571 "/v5/account/no-convert-repay",
1572 None,
1573 Some(body),
1574 true,
1575 )
1576 .await;
1577
1578 if let Err(ref e) = result
1579 && let Ok(params_json) = serde_json::to_string(¶ms)
1580 {
1581 log::debug!("Repay request failed with params {params_json}: {e}");
1582 }
1583
1584 result
1585 }
1586
1587 pub async fn repay(
1605 &self,
1606 coin: Option<&str>,
1607 amount: Option<&str>,
1608 ) -> Result<BybitRepayResponse, BybitHttpError> {
1609 let mut builder = BybitRepayParamsBuilder::default();
1610
1611 if let Some(coin) = coin {
1612 builder.coin(coin.to_string());
1613 }
1614
1615 if let Some(amt) = amount {
1616 builder.amount(amt.to_string());
1617 }
1618
1619 let params = builder.build().expect("Failed to build BybitRepayParams");
1620
1621 if let Ok(params_json) = serde_json::to_string(¶ms) {
1622 log::debug!("Repay request params: {params_json}");
1623 }
1624
1625 let body = serde_json::to_vec(¶ms)?;
1626 let result = self
1627 .send_request::<_, ()>(Method::POST, "/v5/account/repay", None, Some(body), true)
1628 .await;
1629
1630 if let Err(ref e) = result
1631 && let Ok(params_json) = serde_json::to_string(¶ms)
1632 {
1633 log::debug!("Repay request failed with params {params_json}: {e}");
1634 }
1635
1636 result
1637 }
1638
1639 pub async fn withdraw(
1656 &self,
1657 params: &BybitWithdrawParams,
1658 ) -> Result<BybitWithdrawResponse, BybitHttpError> {
1659 let body = serde_json::to_vec(params)?;
1660 self.send_request_once::<_, ()>(
1661 Method::POST,
1662 "/v5/asset/withdraw/create",
1663 None,
1664 Some(body),
1665 true,
1666 )
1667 .await
1668 }
1669
1670 pub async fn get_withdrawal_records(
1683 &self,
1684 params: &BybitWithdrawalRecordsParams,
1685 ) -> Result<BybitWithdrawalRecordsResponse, BybitHttpError> {
1686 self.send_request(
1687 Method::GET,
1688 "/v5/asset/withdraw/query-record",
1689 Some(params),
1690 None,
1691 true,
1692 )
1693 .await
1694 }
1695
1696 pub async fn fetch_all_withdrawal_records(
1703 &self,
1704 params: &BybitWithdrawalRecordsParams,
1705 ) -> Result<Vec<BybitWithdrawalRecord>, BybitHttpError> {
1706 let mut params = params.clone();
1707 let mut records = Vec::new();
1708 let mut cursor_walk = CursorWalk::default();
1709
1710 loop {
1711 let mut page = self.get_withdrawal_records(¶ms).await?;
1712 records.append(&mut page.result.rows);
1713
1714 let next = cursor_walk
1715 .advance(
1716 "/v5/asset/withdraw/query-record",
1717 page.result.next_page_cursor.take(),
1718 )
1719 .map_err(|e| BybitHttpError::ValidationError(e.to_string()))?;
1720
1721 match next {
1722 Some(c) => params.cursor = Some(c),
1723 None => break,
1724 }
1725 }
1726
1727 Ok(records)
1728 }
1729
1730 pub async fn get_tickers<T: DeserializeOwned + BybitResponseCheck>(
1740 &self,
1741 params: &BybitTickersParams,
1742 ) -> Result<T, BybitHttpError> {
1743 self.send_request(Method::GET, "/v5/market/tickers", Some(params), None, false)
1744 .await
1745 }
1746
1747 pub async fn get_trade_history(
1757 &self,
1758 params: &BybitTradeHistoryParams,
1759 ) -> Result<BybitTradeHistoryResponse, BybitHttpError> {
1760 self.send_request(Method::GET, BYBIT_EXECUTION_LIST, Some(params), None, true)
1761 .await
1762 }
1763
1764 pub async fn get_positions(
1777 &self,
1778 params: &BybitPositionListParams,
1779 ) -> Result<BybitPositionListResponse, BybitHttpError> {
1780 self.send_request(Method::GET, BYBIT_POSITION_LIST, Some(params), None, true)
1781 .await
1782 }
1783
1784 #[must_use]
1786 pub fn base_url(&self) -> &str {
1787 &self.base_url
1788 }
1789
1790 #[must_use]
1792 pub fn recv_window_ms(&self) -> u64 {
1793 self.recv_window_ms
1794 }
1795
1796 #[must_use]
1798 pub fn credential(&self) -> Option<&Credential> {
1799 self.credential.as_ref()
1800 }
1801}
1802
1803#[cfg_attr(
1805 feature = "python",
1806 pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
1807)]
1808#[cfg_attr(
1809 feature = "python",
1810 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
1811)]
1812pub struct BybitHttpClient {
1817 pub(crate) inner: Arc<BybitRawHttpClient>,
1818 pub(crate) instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
1819 clock: &'static AtomicTime,
1820 cache_initialized: Arc<AtomicBool>,
1821 use_spot_position_reports: Arc<AtomicBool>,
1822}
1823
1824impl Clone for BybitHttpClient {
1825 fn clone(&self) -> Self {
1826 Self {
1827 inner: self.inner.clone(),
1828 instruments_cache: self.instruments_cache.clone(),
1829 cache_initialized: self.cache_initialized.clone(),
1830 use_spot_position_reports: self.use_spot_position_reports.clone(),
1831 clock: self.clock,
1832 }
1833 }
1834}
1835
1836impl Default for BybitHttpClient {
1837 fn default() -> Self {
1838 Self::new(None, 60, 3, 1000, 10_000, DEFAULT_RECV_WINDOW_MS, None)
1839 .expect("Failed to create default BybitHttpClient")
1840 }
1841}
1842
1843impl Debug for BybitHttpClient {
1844 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1845 f.debug_struct(stringify!(BybitHttpClient))
1846 .field("inner", &self.inner)
1847 .finish()
1848 }
1849}
1850
1851impl BybitHttpClient {
1852 pub(crate) fn start_mm_detection(&self) {
1853 self.inner.start_mm_detection();
1854 }
1855
1856 pub(crate) fn mm_level(&self) -> u8 {
1857 self.inner.mm_level()
1858 }
1859
1860 pub fn new(
1866 base_url: Option<String>,
1867 timeout_secs: u64,
1868 max_retries: u32,
1869 retry_delay_ms: u64,
1870 retry_delay_max_ms: u64,
1871 recv_window_ms: u64,
1872 proxy_url: Option<String>,
1873 ) -> Result<Self, BybitHttpError> {
1874 Ok(Self {
1875 inner: Arc::new(BybitRawHttpClient::new(
1876 base_url,
1877 timeout_secs,
1878 max_retries,
1879 retry_delay_ms,
1880 retry_delay_max_ms,
1881 recv_window_ms,
1882 proxy_url,
1883 )?),
1884 instruments_cache: Arc::new(AtomicMap::new()),
1885 cache_initialized: Arc::new(AtomicBool::new(false)),
1886 use_spot_position_reports: Arc::new(AtomicBool::new(false)),
1887 clock: get_atomic_clock_realtime(),
1888 })
1889 }
1890
1891 #[expect(clippy::too_many_arguments)]
1897 pub fn with_credentials(
1898 api_key: String,
1899 api_secret: String,
1900 base_url: Option<String>,
1901 timeout_secs: u64,
1902 max_retries: u32,
1903 retry_delay_ms: u64,
1904 retry_delay_max_ms: u64,
1905 recv_window_ms: u64,
1906 proxy_url: Option<String>,
1907 ) -> Result<Self, BybitHttpError> {
1908 Ok(Self {
1909 inner: Arc::new(BybitRawHttpClient::with_credentials(
1910 api_key,
1911 api_secret,
1912 base_url,
1913 timeout_secs,
1914 max_retries,
1915 retry_delay_ms,
1916 retry_delay_max_ms,
1917 recv_window_ms,
1918 proxy_url,
1919 )?),
1920 instruments_cache: Arc::new(AtomicMap::new()),
1921 cache_initialized: Arc::new(AtomicBool::new(false)),
1922 use_spot_position_reports: Arc::new(AtomicBool::new(false)),
1923 clock: get_atomic_clock_realtime(),
1924 })
1925 }
1926
1927 #[expect(clippy::too_many_arguments)]
1940 pub fn new_with_env(
1941 api_key: Option<String>,
1942 api_secret: Option<String>,
1943 base_url: Option<String>,
1944 demo: bool,
1945 testnet: bool,
1946 timeout_secs: u64,
1947 max_retries: u32,
1948 retry_delay_ms: u64,
1949 retry_delay_max_ms: u64,
1950 recv_window_ms: u64,
1951 proxy_url: Option<String>,
1952 ) -> Result<Self, BybitHttpError> {
1953 Ok(Self {
1954 inner: Arc::new(BybitRawHttpClient::new_with_env(
1955 api_key,
1956 api_secret,
1957 base_url,
1958 demo,
1959 testnet,
1960 timeout_secs,
1961 max_retries,
1962 retry_delay_ms,
1963 retry_delay_max_ms,
1964 recv_window_ms,
1965 proxy_url,
1966 )?),
1967 instruments_cache: Arc::new(AtomicMap::new()),
1968 cache_initialized: Arc::new(AtomicBool::new(false)),
1969 use_spot_position_reports: Arc::new(AtomicBool::new(false)),
1970 clock: get_atomic_clock_realtime(),
1971 })
1972 }
1973
1974 #[must_use]
1975 pub fn base_url(&self) -> &str {
1976 self.inner.base_url()
1977 }
1978
1979 #[must_use]
1980 pub fn recv_window_ms(&self) -> u64 {
1981 self.inner.recv_window_ms()
1982 }
1983
1984 #[must_use]
1985 pub fn credential(&self) -> Option<&Credential> {
1986 self.inner.credential()
1987 }
1988
1989 pub fn set_use_spot_position_reports(&self, use_spot_position_reports: bool) {
1990 self.use_spot_position_reports
1991 .store(use_spot_position_reports, Ordering::Relaxed);
1992 }
1993
1994 pub fn cancel_all_requests(&self) {
1995 self.inner.cancel_all_requests();
1996 }
1997
1998 pub fn reset_cancellation_token(&self) {
1999 self.inner.reset_cancellation_token();
2000 }
2001
2002 pub fn cancellation_token(&self) -> CancellationToken {
2003 self.inner.cancellation_token()
2004 }
2005
2006 pub fn cache_instrument(&self, instrument: InstrumentAny) {
2008 self.instruments_cache
2009 .insert(instrument.symbol().inner(), instrument);
2010 self.cache_initialized.store(true, Ordering::Release);
2011 }
2012
2013 pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
2015 self.instruments_cache.rcu(|m| {
2016 for instrument in instruments {
2017 m.insert(instrument.symbol().inner(), instrument.clone());
2018 }
2019 });
2020 self.cache_initialized.store(true, Ordering::Release);
2021 }
2022
2023 pub fn get_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
2024 self.instruments_cache.get_cloned(symbol)
2025 }
2026
2027 fn instrument_from_cache(&self, symbol: &Symbol) -> anyhow::Result<InstrumentAny> {
2028 self.get_instrument(&symbol.inner()).ok_or_else(|| {
2029 anyhow::anyhow!(
2030 "Instrument {symbol} not found in cache, ensure instruments loaded first"
2031 )
2032 })
2033 }
2034
2035 #[must_use]
2036 fn generate_ts_init(&self) -> UnixNanos {
2037 self.clock.get_time_ns()
2038 }
2039
2040 pub async fn get_server_time(&self) -> Result<BybitServerTimeResponse, BybitHttpError> {
2052 self.inner.get_server_time().await
2053 }
2054
2055 pub async fn get_instruments<T: DeserializeOwned + BybitResponseCheck>(
2067 &self,
2068 params: &BybitInstrumentsInfoParams,
2069 ) -> Result<T, BybitHttpError> {
2070 self.inner.get_instruments(params).await
2071 }
2072
2073 pub async fn get_instruments_spot(
2085 &self,
2086 params: &BybitInstrumentsInfoParams,
2087 ) -> Result<BybitInstrumentSpotResponse, BybitHttpError> {
2088 self.inner.get_instruments_spot(params).await
2089 }
2090
2091 pub async fn get_instruments_linear(
2103 &self,
2104 params: &BybitInstrumentsInfoParams,
2105 ) -> Result<BybitInstrumentLinearResponse, BybitHttpError> {
2106 self.inner.get_instruments_linear(params).await
2107 }
2108
2109 pub async fn get_instruments_inverse(
2121 &self,
2122 params: &BybitInstrumentsInfoParams,
2123 ) -> Result<BybitInstrumentInverseResponse, BybitHttpError> {
2124 self.inner.get_instruments_inverse(params).await
2125 }
2126
2127 pub async fn get_instruments_option(
2139 &self,
2140 params: &BybitInstrumentsInfoParams,
2141 ) -> Result<BybitInstrumentOptionResponse, BybitHttpError> {
2142 self.inner.get_instruments_option(params).await
2143 }
2144
2145 pub async fn get_klines(
2157 &self,
2158 params: &BybitKlinesParams,
2159 ) -> Result<BybitKlinesResponse, BybitHttpError> {
2160 self.inner.get_klines(params).await
2161 }
2162
2163 pub async fn get_recent_trades(
2175 &self,
2176 params: &BybitTradesParams,
2177 ) -> Result<BybitTradesResponse, BybitHttpError> {
2178 self.inner.get_recent_trades(params).await
2179 }
2180
2181 #[expect(clippy::too_many_arguments)]
2193 pub async fn get_open_orders(
2194 &self,
2195 category: BybitProductType,
2196 symbol: Option<String>,
2197 base_coin: Option<String>,
2198 settle_coin: Option<String>,
2199 order_id: Option<String>,
2200 order_link_id: Option<String>,
2201 open_only: Option<BybitOpenOnly>,
2202 order_filter: Option<BybitOrderFilter>,
2203 limit: Option<u32>,
2204 cursor: Option<String>,
2205 ) -> Result<BybitOpenOrdersResponse, BybitHttpError> {
2206 self.inner
2207 .get_open_orders(
2208 category,
2209 symbol,
2210 base_coin,
2211 settle_coin,
2212 order_id,
2213 order_link_id,
2214 open_only,
2215 order_filter,
2216 limit,
2217 cursor,
2218 )
2219 .await
2220 }
2221
2222 pub async fn place_order(
2234 &self,
2235 request: &serde_json::Value,
2236 ) -> Result<BybitPlaceOrderResponse, BybitHttpError> {
2237 self.inner.place_order(request).await
2238 }
2239
2240 pub async fn get_wallet_balance(
2252 &self,
2253 params: &BybitWalletBalanceParams,
2254 ) -> Result<BybitWalletBalanceResponse, BybitHttpError> {
2255 self.inner.get_wallet_balance(params).await
2256 }
2257
2258 pub async fn get_account_info(&self) -> Result<BybitAccountInfoResponse, BybitHttpError> {
2270 self.inner.get_account_info().await
2271 }
2272
2273 pub async fn get_account_details(&self) -> Result<BybitAccountDetailsResponse, BybitHttpError> {
2285 self.inner.get_account_details().await
2286 }
2287
2288 pub async fn update_sub_api_key(
2300 &self,
2301 params: &BybitUpdateSubApiParams,
2302 ) -> Result<BybitUpdateSubApiResponse, BybitHttpError> {
2303 self.inner.update_sub_api_key(params).await
2304 }
2305
2306 pub async fn update_master_api_key(
2318 &self,
2319 params: &BybitUpdateMasterApiParams,
2320 ) -> Result<BybitUpdateMasterApiResponse, BybitHttpError> {
2321 self.inner.update_master_api_key(params).await
2322 }
2323
2324 pub async fn get_sub_members(&self) -> Result<BybitSubMembersResponse, BybitHttpError> {
2336 self.inner.get_sub_members().await
2337 }
2338
2339 pub async fn get_sub_members_paged(
2351 &self,
2352 params: &BybitSubMembersPageParams,
2353 ) -> Result<BybitSubMembersPagedResponse, BybitHttpError> {
2354 self.inner.get_sub_members_paged(params).await
2355 }
2356
2357 pub async fn get_escrow_sub_members(
2369 &self,
2370 params: &BybitSubMembersPageParams,
2371 ) -> Result<BybitEscrowSubMembersResponse, BybitHttpError> {
2372 self.inner.get_escrow_sub_members(params).await
2373 }
2374
2375 pub async fn get_sub_api_keys(
2387 &self,
2388 params: &BybitSubApiKeysParams,
2389 ) -> Result<BybitSubApiKeysResponse, BybitHttpError> {
2390 self.inner.get_sub_api_keys(params).await
2391 }
2392
2393 pub async fn get_positions(
2406 &self,
2407 params: &BybitPositionListParams,
2408 ) -> Result<BybitPositionListResponse, BybitHttpError> {
2409 self.inner.get_positions(params).await
2410 }
2411
2412 pub async fn get_fee_rate(
2425 &self,
2426 params: &BybitFeeRateParams,
2427 ) -> Result<BybitFeeRateResponse, BybitHttpError> {
2428 self.inner.get_fee_rate(params).await
2429 }
2430
2431 pub async fn set_margin_mode(
2444 &self,
2445 margin_mode: BybitMarginMode,
2446 ) -> Result<BybitSetMarginModeResponse, BybitHttpError> {
2447 self.inner.set_margin_mode(margin_mode).await
2448 }
2449
2450 pub async fn set_leverage(
2463 &self,
2464 product_type: BybitProductType,
2465 symbol: &str,
2466 buy_leverage: &str,
2467 sell_leverage: &str,
2468 ) -> Result<BybitSetLeverageResponse, BybitHttpError> {
2469 self.inner
2470 .set_leverage(product_type, symbol, buy_leverage, sell_leverage)
2471 .await
2472 }
2473
2474 pub async fn switch_mode(
2487 &self,
2488 product_type: BybitProductType,
2489 mode: BybitPositionMode,
2490 symbol: Option<String>,
2491 coin: Option<String>,
2492 ) -> Result<BybitSwitchModeResponse, BybitHttpError> {
2493 self.inner
2494 .switch_mode(product_type, mode, symbol, coin)
2495 .await
2496 }
2497
2498 pub async fn set_trading_stop(
2511 &self,
2512 params: &BybitSetTradingStopParams,
2513 ) -> Result<BybitSetTradingStopResponse, BybitHttpError> {
2514 self.inner.set_trading_stop(params).await
2515 }
2516
2517 pub async fn get_spot_borrow_amount(&self, coin: &str) -> anyhow::Result<Decimal> {
2532 let params = BybitWalletBalanceParams {
2533 account_type: BybitAccountType::Unified,
2534 coin: Some(coin.to_string()),
2535 };
2536
2537 let response = self.inner.get_wallet_balance(¶ms).await?;
2538
2539 let borrow_amount = response
2540 .result
2541 .list
2542 .first()
2543 .and_then(|wallet| wallet.coin.iter().find(|c| c.coin == coin))
2544 .map_or(Decimal::ZERO, |balance| balance.spot_borrow);
2545
2546 Ok(borrow_amount)
2547 }
2548
2549 pub async fn borrow_spot(
2565 &self,
2566 coin: &str,
2567 amount: Quantity,
2568 ) -> anyhow::Result<BybitBorrowResponse> {
2569 let amount_str = amount.to_string();
2570 self.inner
2571 .borrow(coin, &amount_str)
2572 .await
2573 .map_err(|e| anyhow::anyhow!("Failed to borrow {amount} {coin}: {e}"))
2574 }
2575
2576 pub async fn repay_spot_borrow(
2593 &self,
2594 coin: &str,
2595 amount: Option<Quantity>,
2596 ) -> anyhow::Result<BybitNoConvertRepayResponse> {
2597 let amount_str = amount.as_ref().map(|q| q.to_string());
2598 let response = self
2599 .inner
2600 .no_convert_repay(coin, amount_str.as_deref())
2601 .await
2602 .map_err(|e| anyhow::anyhow!("Failed to repay spot borrow for {coin}: {e}"))?;
2603 Self::ensure_repay_accepted(coin, response.result.result_status)?;
2604 Ok(response)
2605 }
2606
2607 pub async fn repay_spot_borrow_with_conversion(
2625 &self,
2626 coin: &str,
2627 amount: Option<Quantity>,
2628 ) -> anyhow::Result<BybitRepayResponse> {
2629 let amount_str = amount.as_ref().map(|q| q.to_string());
2630 let response = self
2631 .inner
2632 .repay(Some(coin), amount_str.as_deref())
2633 .await
2634 .map_err(|e| {
2635 anyhow::anyhow!("Failed to repay spot borrow (with conversion) for {coin}: {e}")
2636 })?;
2637 Self::ensure_repay_accepted(coin, response.result.result_status)?;
2638 Ok(response)
2639 }
2640
2641 fn ensure_repay_accepted(coin: &str, status: BybitRepayStatus) -> anyhow::Result<()> {
2642 anyhow::ensure!(
2643 status != BybitRepayStatus::Failed,
2644 "Bybit repay for {coin} returned result status {status}"
2645 );
2646 Ok(())
2647 }
2648
2649 async fn generate_spot_position_reports_from_wallet(
2657 &self,
2658 account_id: AccountId,
2659 instrument_id: InstrumentId,
2660 ) -> anyhow::Result<Vec<PositionStatusReport>> {
2661 let params = BybitWalletBalanceParams {
2662 account_type: BybitAccountType::Unified,
2663 coin: None,
2664 };
2665
2666 let response = self.inner.get_wallet_balance(¶ms).await?;
2667 let ts_init = self.generate_ts_init();
2668
2669 let mut wallet_by_coin: HashMap<Ustr, Decimal> = HashMap::new();
2670
2671 for wallet in &response.result.list {
2672 for coin_balance in &wallet.coin {
2673 let balance = coin_balance.wallet_balance - coin_balance.spot_borrow;
2674 *wallet_by_coin
2675 .entry(coin_balance.coin)
2676 .or_insert(Decimal::ZERO) += balance;
2677 }
2678 }
2679
2680 let mut reports = Vec::new();
2681
2682 if let Some(instrument) = self
2683 .instruments_cache
2684 .get_cloned(&instrument_id.symbol.inner())
2685 {
2686 let base_currency = instrument
2687 .base_currency()
2688 .expect("SPOT instrument should have base currency");
2689 let coin = base_currency.code;
2690 let wallet_balance = wallet_by_coin.get(&coin).copied().unwrap_or(Decimal::ZERO);
2691
2692 let side = if wallet_balance > Decimal::ZERO {
2693 PositionSide::Long
2694 } else if wallet_balance < Decimal::ZERO {
2695 PositionSide::Short
2696 } else {
2697 PositionSide::Flat
2698 };
2699
2700 let abs_balance = wallet_balance.abs();
2701 let quantity = Quantity::from_decimal_dp(abs_balance, instrument.size_precision())?;
2702
2703 let report = PositionStatusReport::new(
2704 account_id,
2705 instrument_id,
2706 side,
2707 quantity,
2708 ts_init,
2709 ts_init,
2710 None,
2711 None,
2712 None,
2713 );
2714
2715 reports.push(report);
2716 }
2717
2718 Ok(reports)
2719 }
2720
2721 #[expect(clippy::too_many_arguments)]
2732 pub async fn submit_order(
2733 &self,
2734 account_id: AccountId,
2735 product_type: BybitProductType,
2736 instrument_id: InstrumentId,
2737 client_order_id: ClientOrderId,
2738 order_side: OrderSide,
2739 order_type: OrderType,
2740 quantity: Quantity,
2741 time_in_force: Option<TimeInForce>,
2742 price: Option<Price>,
2743 trigger_price: Option<Price>,
2744 post_only: Option<bool>,
2745 reduce_only: bool,
2746 is_quote_quantity: bool,
2747 is_leverage: bool,
2748 position_idx: Option<BybitPositionIdx>,
2749 bbo_side_type: Option<BybitBboSideType>,
2750 bbo_level: Option<String>,
2751 smp_type: Option<BybitOrderSmpType>,
2752 native_tp_sl: Option<&BybitNativeTpSlParams>,
2753 ) -> anyhow::Result<OrderStatusReport> {
2754 let instrument = self.instrument_from_cache(&instrument_id.symbol)?;
2755 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
2756
2757 let bybit_side = match order_side {
2758 OrderSide::Buy => BybitOrderSide::Buy,
2759 OrderSide::Sell => BybitOrderSide::Sell,
2760 };
2761
2762 let (bybit_order_type, is_stop_order) = match order_type {
2764 OrderType::Market => (BybitOrderType::Market, false),
2765 OrderType::Limit => (BybitOrderType::Limit, false),
2766 OrderType::StopMarket | OrderType::MarketIfTouched => (BybitOrderType::Market, true),
2767 OrderType::StopLimit | OrderType::LimitIfTouched => (BybitOrderType::Limit, true),
2768 _ => anyhow::bail!("Unsupported order type: {order_type:?}"),
2769 };
2770
2771 let bybit_tif = map_time_in_force(bybit_order_type, time_in_force, post_only)
2772 .map_err(|tif| anyhow::anyhow!("Unsupported time in force: {tif:?}"))?;
2773 let market_unit = spot_market_unit(product_type, bybit_order_type, is_quote_quantity);
2774 let trigger_dir = trigger_direction(order_type, order_side, is_stop_order);
2775
2776 let mut order_entry = BybitBatchPlaceOrderEntryBuilder::default();
2777 order_entry.symbol(bybit_symbol.raw_symbol().to_string());
2778 order_entry.side(bybit_side);
2779 order_entry.order_type(bybit_order_type);
2780 order_entry.qty(quantity.to_string());
2781 order_entry.time_in_force(bybit_tif);
2782 order_entry.order_link_id(client_order_id.to_string());
2783 order_entry.market_unit(market_unit);
2784 order_entry.trigger_direction(trigger_dir);
2785
2786 if bbo_side_type.is_none()
2787 && let Some(price) = price
2788 {
2789 order_entry.price(Some(price.to_string()));
2790 }
2791
2792 if let Some(trigger_price) = trigger_price {
2793 order_entry.trigger_price(Some(trigger_price.to_string()));
2794 }
2795
2796 if reduce_only {
2797 order_entry.reduce_only(Some(true));
2798 }
2799
2800 order_entry.is_leverage(spot_leverage(product_type, is_leverage));
2801
2802 if let Some(idx) = position_idx {
2803 order_entry.position_idx(Some(idx));
2804 }
2805
2806 order_entry.bbo_side_type(bbo_side_type);
2807 order_entry.bbo_level(bbo_level);
2808 order_entry.smp_type(smp_type);
2809
2810 if let Some(tp_sl) = native_tp_sl {
2811 if let Some(ref tp) = tp_sl.take_profit {
2812 order_entry.take_profit(Some(tp.clone()));
2813 }
2814
2815 if let Some(ref sl) = tp_sl.stop_loss {
2816 order_entry.stop_loss(Some(sl.clone()));
2817 }
2818
2819 if let Some(tp_trigger) = tp_sl.tp_trigger_by {
2820 order_entry.tp_trigger_by(Some(tp_trigger));
2821 }
2822
2823 if let Some(sl_trigger) = tp_sl.sl_trigger_by {
2824 order_entry.sl_trigger_by(Some(sl_trigger));
2825 }
2826
2827 if let Some(tp_ot) = tp_sl.tp_order_type {
2828 order_entry.tp_order_type(Some(tp_ot));
2829 }
2830
2831 if let Some(sl_ot) = tp_sl.sl_order_type {
2832 order_entry.sl_order_type(Some(sl_ot));
2833 }
2834
2835 if let Some(ref tp_lp) = tp_sl.tp_limit_price {
2836 order_entry.tp_limit_price(Some(tp_lp.clone()));
2837 }
2838
2839 if let Some(ref sl_lp) = tp_sl.sl_limit_price {
2840 order_entry.sl_limit_price(Some(sl_lp.clone()));
2841 }
2842
2843 let mode = tp_sl.tpsl_mode.or_else(|| {
2846 (tp_sl.take_profit.is_some() || tp_sl.stop_loss.is_some())
2847 .then_some(BybitTpSlMode::Full)
2848 });
2849
2850 if let Some(m) = mode {
2851 order_entry.tpsl_mode(Some(m));
2852 }
2853
2854 if let Some(close) = tp_sl.close_on_trigger {
2855 order_entry.close_on_trigger(Some(close));
2856 }
2857
2858 if let Some(ref iv) = tp_sl.order_iv {
2859 order_entry.order_iv(Some(iv.clone()));
2860 }
2861
2862 if let Some(mmp) = tp_sl.mmp {
2863 order_entry.mmp(Some(mmp));
2864 }
2865 }
2866
2867 let order_entry = order_entry.build().build_anyhow()?;
2868
2869 let mut params = BybitPlaceOrderParamsBuilder::default();
2870 params.category(product_type);
2871 params.order(order_entry);
2872
2873 let params = params.build().build_anyhow()?;
2874
2875 let body = serde_json::to_value(¶ms)?;
2876 let response = self.inner.place_order(&body).await?;
2877
2878 let order_id = response
2879 .result
2880 .order_id
2881 .ok_or(BybitSubmitOrderError::MissingOrderId)?;
2882
2883 let order = self
2884 .query_order_by_id(
2885 product_type,
2886 order_id.as_str(),
2887 BYBIT_ORDER_REALTIME,
2888 "after submission",
2889 )
2890 .await
2891 .map_err(|source| BybitSubmitOrderError::PostSubmitLookup { source })?;
2892
2893 let is_rejection = order.order_status == crate::common::enums::BybitOrderStatus::Rejected
2898 || (order.order_status == crate::common::enums::BybitOrderStatus::Canceled
2899 && bybit_rejection_due_post_only(order.reject_reason.as_str()));
2900 if is_rejection && (order.cum_exec_qty.as_str() == "0" || order.cum_exec_qty.is_empty()) {
2901 return Err(BybitSubmitOrderError::Rejected {
2902 reason: order.reject_reason.to_string(),
2903 }
2904 .into());
2905 }
2906
2907 let ts_init = self.generate_ts_init();
2908
2909 parse_order_status_report(&order, &instrument, account_id, ts_init)
2910 }
2911
2912 pub async fn cancel_order(
2925 &self,
2926 account_id: AccountId,
2927 product_type: BybitProductType,
2928 instrument_id: InstrumentId,
2929 client_order_id: Option<ClientOrderId>,
2930 venue_order_id: Option<VenueOrderId>,
2931 ) -> anyhow::Result<OrderStatusReport> {
2932 self.instrument_from_cache(&instrument_id.symbol)?;
2933 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
2934
2935 let mut cancel_entry = BybitBatchCancelOrderEntryBuilder::default();
2936 cancel_entry.symbol(bybit_symbol.raw_symbol().to_string());
2937
2938 if let Some(venue_order_id) = venue_order_id {
2939 cancel_entry.order_id(venue_order_id.to_string());
2940 } else if let Some(client_order_id) = client_order_id {
2941 cancel_entry.order_link_id(client_order_id.to_string());
2942 } else {
2943 anyhow::bail!("Either client_order_id or venue_order_id must be provided");
2944 }
2945
2946 let cancel_entry = cancel_entry.build().build_anyhow()?;
2947
2948 let mut params = BybitCancelOrderParamsBuilder::default();
2949 params.category(product_type);
2950 params.order(cancel_entry);
2951
2952 let params = params.build().build_anyhow()?;
2953 let body = serde_json::to_vec(¶ms)?;
2954
2955 let response: BybitPlaceOrderResponse = self
2956 .inner
2957 .send_request::<_, ()>(Method::POST, "/v5/order/cancel", None, Some(body), true)
2958 .await?;
2959
2960 let order_id = response
2961 .result
2962 .order_id
2963 .ok_or(BybitCancelOrderError::MissingOrderId)?;
2964
2965 let venue_order_id = VenueOrderId::from(order_id.as_str());
2966
2967 let confirmation = async {
2968 loop {
2969 if let Some(report) = self
2970 .query_order(
2971 account_id,
2972 product_type,
2973 instrument_id,
2974 client_order_id,
2975 Some(venue_order_id),
2976 )
2977 .await?
2978 && report.order_status.is_closed()
2979 {
2980 return Ok(report);
2981 }
2982
2983 tokio::time::sleep(Duration::from_millis(100)).await;
2984 }
2985 };
2986
2987 tokio::time::timeout(Duration::from_secs(self.inner.timeout_secs), confirmation)
2988 .await
2989 .context("timed out confirming Bybit order cancellation")
2990 .and_then(|result| result)
2991 .map_err(|source| BybitCancelOrderError::PostCancelLookup { source }.into())
2992 }
2993
2994 pub async fn batch_cancel_orders(
3004 &self,
3005 account_id: AccountId,
3006 product_type: BybitProductType,
3007 instrument_ids: Vec<InstrumentId>,
3008 client_order_ids: Vec<Option<ClientOrderId>>,
3009 venue_order_ids: Vec<Option<VenueOrderId>>,
3010 ) -> anyhow::Result<Vec<OrderStatusReport>> {
3011 if instrument_ids.len() != client_order_ids.len()
3012 || instrument_ids.len() != venue_order_ids.len()
3013 {
3014 anyhow::bail!(
3015 "instrument_ids, client_order_ids, and venue_order_ids must have the same length"
3016 );
3017 }
3018
3019 if instrument_ids.is_empty() {
3020 return Ok(Vec::new());
3021 }
3022
3023 let call_limit = batch_call_limit(product_type);
3024 if instrument_ids.len() > call_limit {
3025 anyhow::bail!(
3026 "Batch cancel limit is {call_limit} orders for {}",
3027 product_type.as_str()
3028 );
3029 }
3030
3031 let mut cancel_entries = Vec::new();
3032
3033 for ((instrument_id, client_order_id), venue_order_id) in instrument_ids
3034 .iter()
3035 .zip(client_order_ids.iter())
3036 .zip(venue_order_ids.iter())
3037 {
3038 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3039 let mut cancel_entry = BybitBatchCancelOrderEntryBuilder::default();
3040 cancel_entry.symbol(bybit_symbol.raw_symbol().to_string());
3041
3042 if let Some(venue_order_id) = venue_order_id {
3043 cancel_entry.order_id(venue_order_id.to_string());
3044 } else if let Some(client_order_id) = client_order_id {
3045 cancel_entry.order_link_id(client_order_id.to_string());
3046 } else {
3047 anyhow::bail!(
3048 "Either client_order_id or venue_order_id must be provided for each order"
3049 );
3050 }
3051
3052 cancel_entries.push(cancel_entry.build().build_anyhow()?);
3053 }
3054
3055 let chunk_limit = batch_endpoint_limit(product_type).min(batch_send_limit(product_type));
3056 for chunk in cancel_entries.chunks(chunk_limit) {
3057 let mut params = BybitBatchCancelOrderParamsBuilder::default();
3058 params.category(product_type);
3059 params.request(chunk.to_vec());
3060
3061 let params = params.build().build_anyhow()?;
3062 let body = serde_json::to_vec(¶ms)?;
3063
3064 let _response: BybitPlaceOrderResponse = self
3065 .inner
3066 .send_request::<_, ()>(
3067 Method::POST,
3068 "/v5/order/cancel-batch",
3069 None,
3070 Some(body),
3071 true,
3072 )
3073 .await?;
3074 }
3075
3076 let mut reports = Vec::new();
3078
3079 for (instrument_id, (client_order_id, venue_order_id)) in instrument_ids
3080 .iter()
3081 .zip(client_order_ids.iter().zip(venue_order_ids.iter()))
3082 {
3083 let Ok(instrument) = self.instrument_from_cache(&instrument_id.symbol) else {
3084 log::debug!(
3085 "Skipping cancelled order report for instrument not in cache: symbol={}",
3086 instrument_id.symbol
3087 );
3088 continue;
3089 };
3090
3091 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3092
3093 let mut query_params = BybitOpenOrdersParamsBuilder::default();
3094 query_params.category(product_type);
3095 query_params.symbol(bybit_symbol.raw_symbol().to_string());
3096
3097 if let Some(venue_order_id) = venue_order_id {
3098 query_params.order_id(venue_order_id.to_string());
3099 } else if let Some(client_order_id) = client_order_id {
3100 query_params.order_link_id(client_order_id.to_string());
3101 }
3102
3103 let query_params = query_params.build().build_anyhow()?;
3104 let order_response: BybitOrderHistoryResponse = self
3105 .inner
3106 .send_request(
3107 Method::GET,
3108 BYBIT_ORDER_HISTORY,
3109 Some(&query_params),
3110 None,
3111 true,
3112 )
3113 .await?;
3114
3115 if let Some(order) = order_response.result.list.into_iter().next() {
3116 let ts_init = self.generate_ts_init();
3117 let report = parse_order_status_report(&order, &instrument, account_id, ts_init)?;
3118 reports.push(report);
3119 }
3120 }
3121
3122 Ok(reports)
3123 }
3124
3125 pub async fn cancel_all_orders(
3134 &self,
3135 account_id: AccountId,
3136 product_type: BybitProductType,
3137 instrument_id: InstrumentId,
3138 ) -> anyhow::Result<Vec<OrderStatusReport>> {
3139 let instrument = self.instrument_from_cache(&instrument_id.symbol)?;
3140 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3141
3142 let mut params = BybitCancelAllOrdersParamsBuilder::default();
3143 params.category(product_type);
3144 params.symbol(bybit_symbol.raw_symbol().to_string());
3145
3146 let params = params.build().build_anyhow()?;
3147 let body = serde_json::to_vec(¶ms)?;
3148
3149 let _response: crate::common::models::BybitListResponse<serde_json::Value> = self
3150 .inner
3151 .send_request::<_, ()>(Method::POST, "/v5/order/cancel-all", None, Some(body), true)
3152 .await?;
3153
3154 let mut query_params = BybitOrderHistoryParamsBuilder::default();
3156 query_params.category(product_type);
3157 query_params.symbol(bybit_symbol.raw_symbol().to_string());
3158 query_params.limit(50u32);
3159
3160 let query_params = query_params.build().build_anyhow()?;
3161 let order_response: BybitOrderHistoryResponse = self
3162 .inner
3163 .send_request(
3164 Method::GET,
3165 BYBIT_ORDER_HISTORY,
3166 Some(&query_params),
3167 None,
3168 true,
3169 )
3170 .await?;
3171
3172 let ts_init = self.generate_ts_init();
3173
3174 let mut reports = Vec::new();
3175
3176 for order in order_response.result.list {
3177 if let Ok(report) = parse_order_status_report(&order, &instrument, account_id, ts_init)
3178 {
3179 reports.push(report);
3180 }
3181 }
3182
3183 Ok(reports)
3184 }
3185
3186 #[expect(clippy::too_many_arguments)]
3197 pub async fn modify_order(
3198 &self,
3199 account_id: AccountId,
3200 product_type: BybitProductType,
3201 instrument_id: InstrumentId,
3202 client_order_id: Option<ClientOrderId>,
3203 venue_order_id: Option<VenueOrderId>,
3204 quantity: Option<Quantity>,
3205 price: Option<Price>,
3206 trigger_price: Option<Price>,
3207 ) -> anyhow::Result<OrderStatusReport> {
3208 let instrument = self.instrument_from_cache(&instrument_id.symbol)?;
3209 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3210
3211 let mut amend_entry = BybitBatchAmendOrderEntryBuilder::default();
3212 amend_entry.symbol(bybit_symbol.raw_symbol().to_string());
3213
3214 if let Some(venue_order_id) = venue_order_id {
3215 amend_entry.order_id(venue_order_id.to_string());
3216 } else if let Some(client_order_id) = client_order_id {
3217 amend_entry.order_link_id(client_order_id.to_string());
3218 } else {
3219 anyhow::bail!("Either client_order_id or venue_order_id must be provided");
3220 }
3221
3222 if let Some(quantity) = quantity {
3223 amend_entry.qty(Some(quantity.to_string()));
3224 }
3225
3226 if let Some(price) = price {
3227 amend_entry.price(Some(price.to_string()));
3228 }
3229
3230 if let Some(trigger_price) = trigger_price {
3231 amend_entry.trigger_price(Some(trigger_price.to_string()));
3232 }
3233
3234 let amend_entry = amend_entry.build().build_anyhow()?;
3235
3236 let mut params = BybitAmendOrderParamsBuilder::default();
3237 params.category(product_type);
3238 params.order(amend_entry);
3239
3240 let params = params.build().build_anyhow()?;
3241 let body = serde_json::to_vec(¶ms)?;
3242
3243 let response: BybitPlaceOrderResponse = self
3244 .inner
3245 .send_request::<_, ()>(Method::POST, "/v5/order/amend", None, Some(body), true)
3246 .await?;
3247
3248 let order_id = response
3249 .result
3250 .order_id
3251 .ok_or(BybitModifyOrderError::MissingOrderId)?;
3252
3253 let order = self
3254 .query_order_by_id(
3255 product_type,
3256 order_id.as_str(),
3257 BYBIT_ORDER_REALTIME,
3258 "after amendment",
3259 )
3260 .await
3261 .map_err(|source| BybitModifyOrderError::PostModifyLookup { source })?;
3262
3263 let ts_init = self.generate_ts_init();
3264
3265 parse_order_status_report(&order, &instrument, account_id, ts_init)
3266 }
3267
3268 pub async fn query_order(
3277 &self,
3278 account_id: AccountId,
3279 product_type: BybitProductType,
3280 instrument_id: InstrumentId,
3281 client_order_id: Option<ClientOrderId>,
3282 venue_order_id: Option<VenueOrderId>,
3283 ) -> anyhow::Result<Option<OrderStatusReport>> {
3284 log::debug!(
3285 "query_order: instrument_id={instrument_id}, client_order_id={client_order_id:?}, venue_order_id={venue_order_id:?}"
3286 );
3287
3288 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3289
3290 let mut params = BybitOpenOrdersParamsBuilder::default();
3291 params.category(product_type);
3292 params.symbol(bybit_symbol.raw_symbol().to_string());
3294
3295 if let Some(venue_order_id) = venue_order_id {
3296 params.order_id(venue_order_id.to_string());
3297 } else if let Some(client_order_id) = client_order_id {
3298 params.order_link_id(client_order_id.to_string());
3299 } else {
3300 anyhow::bail!("Either client_order_id or venue_order_id must be provided");
3301 }
3302
3303 let params = params.build().build_anyhow()?;
3304 let mut response: BybitOpenOrdersResponse = self
3305 .inner
3306 .send_request(Method::GET, BYBIT_ORDER_REALTIME, Some(¶ms), None, true)
3307 .await?;
3308
3309 if response.result.list.is_empty() && product_type != BybitProductType::Option {
3311 log::debug!("Order not found in open orders, trying with StopOrder filter");
3312
3313 let mut stop_params = BybitOpenOrdersParamsBuilder::default();
3314 stop_params.category(product_type);
3315 stop_params.symbol(bybit_symbol.raw_symbol().to_string());
3316 stop_params.order_filter(BybitOrderFilter::StopOrder);
3317
3318 if let Some(venue_order_id) = venue_order_id {
3319 stop_params.order_id(venue_order_id.to_string());
3320 } else if let Some(client_order_id) = client_order_id {
3321 stop_params.order_link_id(client_order_id.to_string());
3322 }
3323
3324 let stop_params = stop_params.build().build_anyhow()?;
3325 response = self
3326 .inner
3327 .send_request(
3328 Method::GET,
3329 BYBIT_ORDER_REALTIME,
3330 Some(&stop_params),
3331 None,
3332 true,
3333 )
3334 .await?;
3335 }
3336
3337 if response.result.list.is_empty() {
3339 log::debug!("Order not found in open orders, checking order history");
3340
3341 let mut history_params = BybitOrderHistoryParamsBuilder::default();
3342 history_params.category(product_type);
3343 history_params.symbol(bybit_symbol.raw_symbol().to_string());
3344
3345 if let Some(venue_order_id) = venue_order_id {
3346 history_params.order_id(venue_order_id.to_string());
3347 } else if let Some(client_order_id) = client_order_id {
3348 history_params.order_link_id(client_order_id.to_string());
3349 }
3350
3351 let history_params = history_params.build().build_anyhow()?;
3352
3353 let mut history_response: BybitOrderHistoryResponse = self
3354 .inner
3355 .send_request(
3356 Method::GET,
3357 BYBIT_ORDER_HISTORY,
3358 Some(&history_params),
3359 None,
3360 true,
3361 )
3362 .await?;
3363
3364 if history_response.result.list.is_empty() && product_type == BybitProductType::Option {
3365 log::debug!("Option order not found in order history");
3366 return Ok(None);
3367 }
3368
3369 if history_response.result.list.is_empty() && product_type != BybitProductType::Option {
3371 log::debug!("Order not found in order history, trying with StopOrder filter");
3372
3373 let mut stop_history_params = BybitOrderHistoryParamsBuilder::default();
3374 stop_history_params.category(product_type);
3375 stop_history_params.symbol(bybit_symbol.raw_symbol().to_string());
3376 stop_history_params.order_filter(BybitOrderFilter::StopOrder);
3377
3378 if let Some(venue_order_id) = venue_order_id {
3379 stop_history_params.order_id(venue_order_id.to_string());
3380 } else if let Some(client_order_id) = client_order_id {
3381 stop_history_params.order_link_id(client_order_id.to_string());
3382 }
3383
3384 let stop_history_params = stop_history_params
3385 .build()
3386 .map_err(|e| anyhow::anyhow!(e))?;
3387
3388 history_response = self
3389 .inner
3390 .send_request(
3391 Method::GET,
3392 BYBIT_ORDER_HISTORY,
3393 Some(&stop_history_params),
3394 None,
3395 true,
3396 )
3397 .await?;
3398
3399 if history_response.result.list.is_empty() {
3400 log::debug!("Order not found in order history with StopOrder filter either");
3401 return Ok(None);
3402 }
3403 }
3404
3405 response.result.list = history_response.result.list;
3407 }
3408
3409 let order = &response.result.list[0];
3410 let ts_init = self.generate_ts_init();
3411
3412 log::debug!(
3413 "Query order response: symbol={}, order_id={}, order_link_id={}",
3414 order.symbol.as_str(),
3415 order.order_id.as_str(),
3416 order.order_link_id.as_str()
3417 );
3418
3419 let instrument = self
3420 .instrument_from_cache(&instrument_id.symbol)
3421 .map_err(|e| {
3422 anyhow::anyhow!(
3423 "Failed to query order {}: {}",
3424 client_order_id
3425 .as_ref()
3426 .map(|id| id.to_string())
3427 .or_else(|| venue_order_id.as_ref().map(|id| id.to_string()))
3428 .unwrap_or_else(|| "unknown".to_string()),
3429 e
3430 )
3431 })?;
3432
3433 log::debug!("Retrieved instrument from cache: id={}", instrument.id());
3434
3435 let report =
3436 parse_order_status_report(order, &instrument, account_id, ts_init).map_err(|e| {
3437 log::debug!(
3438 "Failed to parse order status report for {}: {}",
3439 order.order_link_id.as_str(),
3440 e
3441 );
3442 e
3443 })?;
3444
3445 log::debug!(
3446 "Successfully created OrderStatusReport for {}",
3447 order.order_link_id.as_str()
3448 );
3449
3450 Ok(Some(report))
3451 }
3452
3453 async fn paginate_instruments<D, F>(
3454 &self,
3455 product_type: BybitProductType,
3456 symbol: &Option<String>,
3457 base_coin: Option<Ustr>,
3458 mut parse: F,
3459 ) -> anyhow::Result<Vec<InstrumentAny>>
3460 where
3461 D: DeserializeOwned,
3462 BybitCursorListResponse<D>: BybitResponseCheck,
3463 F: FnMut(&D) -> Option<InstrumentAny>,
3464 {
3465 let mut instruments = Vec::new();
3466 let mut cursor: Option<String> = None;
3467 let mut cursor_walk = CursorWalk::default();
3468
3469 loop {
3470 let params = BybitInstrumentsInfoParams {
3471 category: product_type,
3472 symbol: symbol.clone(),
3473 status: None,
3474 base_coin: instrument_base_coin(product_type, symbol.as_deref(), base_coin),
3475 limit: Some(1000),
3476 cursor: cursor.clone(),
3477 };
3478
3479 let response: BybitCursorListResponse<D> = self.inner.get_instruments(¶ms).await?;
3480
3481 for definition in &response.result.list {
3482 if let Some(instrument) = parse(definition) {
3483 instruments.push(instrument);
3484 }
3485 }
3486
3487 cursor = match cursor_walk
3491 .advance(BYBIT_INSTRUMENTS_INFO, response.result.next_page_cursor)
3492 {
3493 Ok(cursor) => cursor,
3494 Err(e) => {
3495 log::warn!(
3496 "{e}, keeping the {} instrument(s) already read",
3497 instruments.len()
3498 );
3499 break;
3500 }
3501 };
3502
3503 if cursor.is_none() {
3504 break;
3505 }
3506 }
3507
3508 Ok(instruments)
3509 }
3510
3511 pub async fn request_instrument_statuses(
3521 &self,
3522 product_type: BybitProductType,
3523 ) -> anyhow::Result<AHashMap<InstrumentId, MarketStatusAction>> {
3524 match product_type {
3525 BybitProductType::Spot => {
3526 self.paginate_instrument_statuses::<BybitInstrumentSpot, _>(product_type, |def| {
3527 (def.symbol, def.status.into())
3528 })
3529 .await
3530 }
3531 BybitProductType::Linear => {
3532 self.paginate_instrument_statuses::<BybitInstrumentLinear, _>(product_type, |def| {
3533 let scheduled = def.contract_type == BybitContractType::LinearPerpetual
3534 && def.delivery_time != "0";
3535 (def.symbol, perp_status(def.status.into(), scheduled))
3536 })
3537 .await
3538 }
3539 BybitProductType::Inverse => {
3540 self.paginate_instrument_statuses::<BybitInstrumentInverse, _>(
3541 product_type,
3542 |def| {
3543 let scheduled = def.contract_type == BybitContractType::InversePerpetual
3544 && def.delivery_time != "0";
3545 (def.symbol, perp_status(def.status.into(), scheduled))
3546 },
3547 )
3548 .await
3549 }
3550 BybitProductType::Option => {
3551 self.paginate_instrument_statuses::<BybitInstrumentOption, _>(product_type, |def| {
3552 (def.symbol, def.status.into())
3553 })
3554 .await
3555 }
3556 }
3557 }
3558
3559 async fn paginate_instrument_statuses<D, F>(
3560 &self,
3561 product_type: BybitProductType,
3562 mut parse: F,
3563 ) -> anyhow::Result<AHashMap<InstrumentId, MarketStatusAction>>
3564 where
3565 D: DeserializeOwned,
3566 BybitCursorListResponse<D>: BybitResponseCheck,
3567 F: FnMut(&D) -> (Ustr, MarketStatusAction),
3568 {
3569 let mut statuses = AHashMap::new();
3570 let mut cursor: Option<String> = None;
3571 let mut cursor_walk = CursorWalk::default();
3572
3573 loop {
3574 let params = BybitInstrumentsInfoParams {
3575 category: product_type,
3576 symbol: None,
3577 status: None,
3578 base_coin: instrument_base_coin(product_type, None, None),
3579 limit: Some(1000),
3580 cursor: cursor.clone(),
3581 };
3582
3583 let response: BybitCursorListResponse<D> = self.inner.get_instruments(¶ms).await?;
3584 for definition in &response.result.list {
3585 let (raw_symbol, status) = parse(definition);
3586 let symbol = make_bybit_symbol(raw_symbol, product_type);
3587 let id = InstrumentId::new(Symbol::from(symbol), *BYBIT_VENUE);
3588 statuses.insert(id, status);
3589 }
3590
3591 cursor =
3592 cursor_walk.advance(BYBIT_INSTRUMENTS_INFO, response.result.next_page_cursor)?;
3593
3594 if cursor.is_none() {
3595 break;
3596 }
3597 }
3598
3599 Ok(statuses)
3600 }
3601
3602 pub async fn request_instruments(
3612 &self,
3613 product_type: BybitProductType,
3614 symbol: Option<String>,
3615 base_coin: Option<Ustr>,
3616 ) -> anyhow::Result<Vec<InstrumentAny>> {
3617 let ts_init = self.generate_ts_init();
3618
3619 let instruments = match product_type {
3620 BybitProductType::Spot => {
3621 self.paginate_instruments::<BybitInstrumentSpot, _>(
3622 product_type,
3623 &symbol,
3624 base_coin,
3625 |def| {
3626 instrument_or_warn(
3627 product_type,
3628 def.symbol,
3629 parse_spot_instrument(def, ts_init, ts_init),
3630 )
3631 },
3632 )
3633 .await?
3634 }
3635 BybitProductType::Linear => {
3636 self.paginate_instruments::<BybitInstrumentLinear, _>(
3637 product_type,
3638 &symbol,
3639 base_coin,
3640 |def| {
3641 instrument_or_warn(
3642 product_type,
3643 def.symbol,
3644 parse_linear_instrument(def, ts_init, ts_init),
3645 )
3646 },
3647 )
3648 .await?
3649 }
3650 BybitProductType::Inverse => {
3651 self.paginate_instruments::<BybitInstrumentInverse, _>(
3652 product_type,
3653 &symbol,
3654 base_coin,
3655 |def| {
3656 instrument_or_warn(
3657 product_type,
3658 def.symbol,
3659 parse_inverse_instrument(def, ts_init, ts_init),
3660 )
3661 },
3662 )
3663 .await?
3664 }
3665 BybitProductType::Option => {
3666 self.paginate_instruments::<BybitInstrumentOption, _>(
3667 product_type,
3668 &symbol,
3669 base_coin,
3670 |def| {
3671 instrument_or_warn(
3672 product_type,
3673 def.symbol,
3674 parse_option_instrument(def, ts_init, ts_init),
3675 )
3676 },
3677 )
3678 .await?
3679 }
3680 };
3681
3682 self.cache_instruments(&instruments);
3683
3684 Ok(instruments)
3685 }
3686
3687 pub async fn request_instruments_with_statuses(
3697 &self,
3698 product_type: BybitProductType,
3699 ) -> anyhow::Result<(
3700 Vec<InstrumentAny>,
3701 AHashMap<InstrumentId, MarketStatusAction>,
3702 )> {
3703 let ts_init = self.generate_ts_init();
3704 let mut statuses = AHashMap::new();
3705
3706 let instruments = match product_type {
3707 BybitProductType::Spot => {
3708 self.paginate_instruments::<BybitInstrumentSpot, _>(
3709 product_type,
3710 &None::<String>,
3711 None,
3712 |def| {
3713 let id = InstrumentId::new(
3714 Symbol::from(make_bybit_symbol(def.symbol, product_type)),
3715 *BYBIT_VENUE,
3716 );
3717 statuses.insert(id, MarketStatusAction::from(def.status));
3718 instrument_or_warn(
3719 product_type,
3720 def.symbol,
3721 parse_spot_instrument(def, ts_init, ts_init),
3722 )
3723 },
3724 )
3725 .await?
3726 }
3727 BybitProductType::Linear => {
3728 self.paginate_instruments::<BybitInstrumentLinear, _>(
3729 product_type,
3730 &None::<String>,
3731 None,
3732 |def| {
3733 let id = InstrumentId::new(
3734 Symbol::from(make_bybit_symbol(def.symbol, product_type)),
3735 *BYBIT_VENUE,
3736 );
3737 let scheduled = def.contract_type == BybitContractType::LinearPerpetual
3738 && def.delivery_time != "0";
3739 statuses.insert(id, perp_status(def.status.into(), scheduled));
3740 instrument_or_warn(
3741 product_type,
3742 def.symbol,
3743 parse_linear_instrument(def, ts_init, ts_init),
3744 )
3745 },
3746 )
3747 .await?
3748 }
3749 BybitProductType::Inverse => {
3750 self.paginate_instruments::<BybitInstrumentInverse, _>(
3751 product_type,
3752 &None::<String>,
3753 None,
3754 |def| {
3755 let id = InstrumentId::new(
3756 Symbol::from(make_bybit_symbol(def.symbol, product_type)),
3757 *BYBIT_VENUE,
3758 );
3759 let scheduled = def.contract_type == BybitContractType::InversePerpetual
3760 && def.delivery_time != "0";
3761 statuses.insert(id, perp_status(def.status.into(), scheduled));
3762 instrument_or_warn(
3763 product_type,
3764 def.symbol,
3765 parse_inverse_instrument(def, ts_init, ts_init),
3766 )
3767 },
3768 )
3769 .await?
3770 }
3771 BybitProductType::Option => {
3772 self.paginate_instruments::<BybitInstrumentOption, _>(
3773 product_type,
3774 &None::<String>,
3775 None,
3776 |def| {
3777 let id = InstrumentId::new(
3778 Symbol::from(make_bybit_symbol(def.symbol, product_type)),
3779 *BYBIT_VENUE,
3780 );
3781 statuses.insert(id, MarketStatusAction::from(def.status));
3782 instrument_or_warn(
3783 product_type,
3784 def.symbol,
3785 parse_option_instrument(def, ts_init, ts_init),
3786 )
3787 },
3788 )
3789 .await?
3790 }
3791 };
3792
3793 self.cache_instruments(&instruments);
3794
3795 Ok((instruments, statuses))
3796 }
3797
3798 pub async fn request_tickers(
3811 &self,
3812 params: &BybitTickersParams,
3813 ) -> anyhow::Result<Vec<BybitTickerData>> {
3814 use super::models::{
3815 BybitTickersLinearResponse, BybitTickersOptionResponse, BybitTickersSpotResponse,
3816 };
3817
3818 match params.category {
3819 BybitProductType::Spot => {
3820 let response: BybitTickersSpotResponse = self.inner.get_tickers(params).await?;
3821 Ok(response.result.list.into_iter().map(Into::into).collect())
3822 }
3823 BybitProductType::Linear | BybitProductType::Inverse => {
3824 let response: BybitTickersLinearResponse = self.inner.get_tickers(params).await?;
3825 Ok(response.result.list.into_iter().map(Into::into).collect())
3826 }
3827 BybitProductType::Option => {
3828 let response: BybitTickersOptionResponse = self.inner.get_tickers(params).await?;
3829 Ok(response.result.list.into_iter().map(Into::into).collect())
3830 }
3831 }
3832 }
3833
3834 pub async fn request_option_tickers_raw(
3842 &self,
3843 base_coin: &str,
3844 ) -> anyhow::Result<Vec<BybitTickerOption>> {
3845 let params = BybitTickersParams {
3846 category: BybitProductType::Option,
3847 symbol: None,
3848 base_coin: Some(base_coin.to_string()),
3849 exp_date: None,
3850 };
3851 let response: BybitTickersOptionResponse = self.inner.get_tickers(¶ms).await?;
3852 Ok(response.result.list)
3853 }
3854
3855 pub async fn request_option_tickers_raw_with_params(
3864 &self,
3865 params: &BybitTickersParams,
3866 ) -> anyhow::Result<Vec<BybitTickerOption>> {
3867 let response: BybitTickersOptionResponse = self.inner.get_tickers(params).await?;
3868 Ok(response.result.list)
3869 }
3870
3871 pub async fn request_trades(
3891 &self,
3892 product_type: BybitProductType,
3893 instrument_id: InstrumentId,
3894 limit: Option<u32>,
3895 ) -> anyhow::Result<Vec<TradeTick>> {
3896 let instrument = self.instrument_from_cache_by_id(instrument_id)?;
3897 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3898
3899 let mut params_builder = BybitTradesParamsBuilder::default();
3900 params_builder.category(product_type);
3901 params_builder.symbol(bybit_symbol.raw_symbol().to_string());
3902
3903 if let Some(limit_val) = limit {
3904 params_builder.limit(limit_val);
3905 }
3906
3907 let params = params_builder.build().build_anyhow()?;
3908 let response = self.inner.get_recent_trades(¶ms).await?;
3909
3910 let mut trades = Vec::new();
3911
3912 for trade in response.result.list {
3913 if let Ok(trade_tick) = parse_trade_tick(&trade, &instrument, None) {
3914 trades.push(trade_tick);
3915 }
3916 }
3917
3918 Ok(trades)
3919 }
3920
3921 pub async fn request_funding_rates(
3934 &self,
3935 product_type: BybitProductType,
3936 instrument_id: InstrumentId,
3937 start: Option<Timestamp>,
3938 end: Option<Timestamp>,
3939 limit: Option<u32>,
3940 ) -> anyhow::Result<Vec<FundingRateUpdate>> {
3941 let instrument = self.instrument_from_cache_by_id(instrument_id)?;
3942 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3943
3944 let start_ms = start.map(|dt| dt.as_millisecond());
3945 let mut seen_timestamps: AHashSet<i64> = AHashSet::new();
3946
3947 let mut raw_funding_rates = Vec::new();
3948
3949 let mut current_end_ms = match (start, end) {
3951 (Some(_), None) => Some(Timestamp::now().as_millisecond()),
3952 _ => end.map(|dt| dt.as_millisecond()),
3953 };
3954
3955 loop {
3956 let mut params_builder = BybitFundingParamsBuilder::default();
3957 params_builder.category(product_type);
3958 params_builder.symbol(bybit_symbol.raw_symbol().to_string());
3959 params_builder.limit(limit.unwrap_or(200).clamp(0, 200)); if let Some(start_val) = start_ms {
3962 params_builder.start_time(start_val);
3963 }
3964
3965 if let Some(end_val) = current_end_ms {
3966 params_builder.end_time(end_val);
3967 }
3968
3969 let params = params_builder.build().build_anyhow()?;
3970 let response = self.inner.get_funding_history(¶ms).await?;
3971
3972 let funding_rates = response.result.list;
3973
3974 let mut new_funding_rates_with_ts: Vec<(i64, _)> = funding_rates
3975 .into_iter()
3976 .filter_map(|f| {
3977 let Ok(ts) = f.funding_rate_timestamp.parse::<i64>() else {
3978 return None;
3979 };
3980
3981 seen_timestamps.insert(ts).then_some((ts, f))
3982 })
3983 .collect();
3984
3985 new_funding_rates_with_ts.sort_by_key(|(ts, _)| Reverse(*ts));
3986
3987 let earliest_funding_time = match new_funding_rates_with_ts.last() {
3988 Some((last_ts, _)) => *last_ts,
3989 None => break,
3990 };
3991
3992 let new_funding_rates = new_funding_rates_with_ts.into_iter().map(|(_, f)| f);
3993 raw_funding_rates.extend(new_funding_rates);
3994
3995 if let Some(limit_val) = limit
3997 && raw_funding_rates.len() >= limit_val as usize
3998 {
3999 break;
4000 }
4001
4002 if let Some(start_val) = start_ms
4003 && earliest_funding_time <= start_val
4004 {
4005 break;
4006 }
4007
4008 current_end_ms = Some(earliest_funding_time - 1);
4010 }
4011
4012 if let Some(limit_val) = limit {
4013 raw_funding_rates.truncate(limit_val as usize);
4014 }
4015 let mut rates: Vec<FundingRateUpdate> = Vec::with_capacity(raw_funding_rates.len());
4016
4017 for window in raw_funding_rates.windows(2) {
4018 let raw = &window[0];
4019 let timestamp = raw
4020 .funding_rate_timestamp
4021 .parse::<i64>()
4022 .map_err(|_| anyhow::anyhow!("invalid funding_rate_timestamp"))?;
4023 let older_timestamp = window[1]
4024 .funding_rate_timestamp
4025 .parse::<i64>()
4026 .map_err(|_| anyhow::anyhow!("invalid funding_rate_timestamp"))?;
4027
4028 let interval_millis = timestamp - older_timestamp;
4029 let rate = parse_funding_rate(raw, &instrument, Some(interval_millis))?;
4030
4031 rates.push(rate);
4032 }
4033
4034 if let Some(last_raw) = raw_funding_rates.last() {
4035 let rate = parse_funding_rate(last_raw, &instrument, None)?;
4036 rates.push(rate);
4037 }
4038
4039 rates.reverse();
4040
4041 Ok(rates)
4042 }
4043
4044 pub async fn request_orderbook_snapshot(
4062 &self,
4063 product_type: BybitProductType,
4064 instrument_id: InstrumentId,
4065 limit: Option<u32>,
4066 ) -> anyhow::Result<OrderBookDeltas> {
4067 let instrument = self.instrument_from_cache_by_id(instrument_id)?;
4068 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
4069
4070 let mut params_builder = BybitOrderbookParamsBuilder::default();
4071 params_builder.category(product_type);
4072 params_builder.symbol(bybit_symbol.raw_symbol().to_string());
4073
4074 if let Some(limit) = limit {
4075 let max_limit = match product_type {
4076 BybitProductType::Spot => 200,
4077 BybitProductType::Option => 25,
4078 BybitProductType::Linear | BybitProductType::Inverse => 500,
4079 };
4080 let clamped_limit = limit.min(max_limit);
4081 if limit > max_limit {
4082 log::warn!(
4083 "Bybit orderbook snapshot request depth limit exceeds venue maximum; clamping: limit={limit}, clamped_limit={clamped_limit}",
4084 );
4085 }
4086 params_builder.limit(clamped_limit);
4087 }
4088
4089 let params = params_builder.build().build_anyhow()?;
4090 let response = self.inner.get_orderbook(¶ms).await?;
4091
4092 let deltas = parse_orderbook(&response.result, &instrument, None)?;
4093
4094 Ok(deltas)
4095 }
4096
4097 pub async fn request_bars(
4110 &self,
4111 product_type: BybitProductType,
4112 bar_type: BarType,
4113 start: Option<Timestamp>,
4114 end: Option<Timestamp>,
4115 limit: Option<u32>,
4116 timestamp_on_close: bool,
4117 ) -> anyhow::Result<Vec<Bar>> {
4118 let instrument_id = bar_type.instrument_id();
4119 let instrument = self.instrument_from_cache_by_id(instrument_id)?;
4120 let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
4121
4122 let interval = bar_spec_to_bybit_interval(
4124 bar_type.spec().aggregation,
4125 bar_type.spec().step.get() as u64,
4126 )?;
4127
4128 let start_ms = start.map(|dt| dt.as_millisecond());
4129 let mut seen_timestamps: AHashSet<i64> = AHashSet::new();
4130 let current_time_ms = get_atomic_clock_realtime().get_time_ms() as i64;
4131
4132 let mut pages: Vec<Vec<Bar>> = Vec::new();
4142 let mut total_bars = 0usize;
4143 let mut current_end = end.map(|dt| dt.as_millisecond());
4144 let mut page_count = 0;
4145
4146 loop {
4147 page_count += 1;
4148
4149 let mut params_builder = BybitKlinesParamsBuilder::default();
4150 params_builder.category(product_type);
4151 params_builder.symbol(bybit_symbol.raw_symbol().to_string());
4152 params_builder.interval(interval);
4153 params_builder.limit(1000u32); if let Some(start_val) = start_ms {
4156 params_builder.start(start_val);
4157 }
4158
4159 if let Some(end_val) = current_end {
4160 params_builder.end(end_val);
4161 }
4162
4163 let params = params_builder.build().build_anyhow()?;
4164 let response = self.inner.get_klines(¶ms).await?;
4165
4166 let klines = response.result.list;
4167 if klines.is_empty() {
4168 break;
4169 }
4170
4171 let mut klines_with_ts: Vec<(i64, _)> = klines
4173 .into_iter()
4174 .filter_map(|k| k.start.parse::<i64>().ok().map(|ts| (ts, k)))
4175 .collect();
4176
4177 klines_with_ts.sort_by_key(|(ts, _)| *ts);
4178
4179 let has_new = klines_with_ts
4181 .iter()
4182 .any(|(ts, _)| !seen_timestamps.contains(ts));
4183
4184 if !has_new {
4185 break;
4186 }
4187
4188 let mut page_bars = Vec::with_capacity(klines_with_ts.len());
4189
4190 let mut earliest_ts: Option<i64> = None;
4191
4192 for (start_time, kline) in &klines_with_ts {
4193 if earliest_ts.is_none_or(|ts| *start_time < ts) {
4195 earliest_ts = Some(*start_time);
4196 }
4197
4198 let bar_end_time = interval.bar_end_time_ms(*start_time);
4199 if bar_end_time > current_time_ms {
4200 continue;
4201 }
4202
4203 if !seen_timestamps.contains(start_time)
4204 && let Ok(bar) =
4205 parse_kline_bar(kline, &instrument, bar_type, timestamp_on_close, None)
4206 {
4207 page_bars.push(bar);
4208 seen_timestamps.insert(*start_time);
4209 }
4210 }
4211
4212 total_bars += page_bars.len();
4215 pages.push(page_bars);
4216
4217 if let Some(limit_val) = limit
4219 && total_bars >= limit_val as usize
4220 {
4221 break;
4222 }
4223
4224 let Some(earliest_bar_time) = earliest_ts else {
4227 break;
4228 };
4229
4230 if let Some(start_val) = start_ms
4231 && earliest_bar_time <= start_val
4232 {
4233 break;
4234 }
4235
4236 current_end = Some(earliest_bar_time - 1);
4237
4238 if page_count > 100 {
4240 break;
4241 }
4242 }
4243
4244 let mut all_bars: Vec<Bar> = Vec::with_capacity(total_bars);
4246 for page in pages.into_iter().rev() {
4247 all_bars.extend(page);
4248 }
4249
4250 if let Some(limit_val) = limit {
4252 let limit_usize = limit_val as usize;
4253 if all_bars.len() > limit_usize {
4254 let start_idx = all_bars.len() - limit_usize;
4255 return Ok(all_bars[start_idx..].to_vec());
4256 }
4257 }
4258
4259 Ok(all_bars)
4260 }
4261
4262 fn instrument_from_cache_by_id(
4263 &self,
4264 instrument_id: InstrumentId,
4265 ) -> anyhow::Result<InstrumentAny> {
4266 self.get_instrument(&instrument_id.symbol.inner())
4267 .ok_or_else(|| InstrumentLookupError::not_found(instrument_id).into())
4268 }
4269
4270 pub async fn request_fee_rates(
4282 &self,
4283 product_type: BybitProductType,
4284 symbol: Option<String>,
4285 base_coin: Option<String>,
4286 ) -> anyhow::Result<Vec<BybitFeeRate>> {
4287 let params = BybitFeeRateParams {
4288 category: product_type,
4289 symbol,
4290 base_coin,
4291 };
4292
4293 let response = self.inner.get_fee_rate(¶ms).await?;
4294 Ok(response.result.list)
4295 }
4296
4297 pub async fn request_account_state(
4309 &self,
4310 account_type: BybitAccountType,
4311 account_id: AccountId,
4312 ) -> anyhow::Result<AccountState> {
4313 let params = BybitWalletBalanceParams {
4314 account_type,
4315 coin: None,
4316 };
4317
4318 let response = self.inner.get_wallet_balance(¶ms).await?;
4319 let ts_init = self.generate_ts_init();
4320
4321 let wallet_balance = response
4323 .result
4324 .list
4325 .first()
4326 .ok_or_else(|| anyhow::anyhow!("No wallet balance found in response"))?;
4327
4328 parse_account_state(wallet_balance, account_id, ts_init)
4329 }
4330
4331 #[expect(clippy::too_many_arguments)]
4348 pub async fn request_order_status_reports(
4349 &self,
4350 account_id: AccountId,
4351 product_type: BybitProductType,
4352 instrument_id: Option<InstrumentId>,
4353 open_only: bool,
4354 start: Option<Timestamp>,
4355 end: Option<Timestamp>,
4356 limit: Option<u32>,
4357 ) -> anyhow::Result<Vec<OrderStatusReport>> {
4358 self.request_order_status_reports_scoped(
4359 account_id,
4360 product_type,
4361 instrument_id,
4362 open_only,
4363 start,
4364 end,
4365 limit,
4366 None,
4367 (
4368 start.map(|ts| ts.as_millisecond()),
4369 end.map(|ts| ts.as_millisecond()),
4370 ),
4371 )
4372 .await?
4373 .into_reports()
4374 }
4375
4376 #[expect(clippy::too_many_arguments)]
4377 pub(crate) async fn request_order_status_reports_scoped(
4378 &self,
4379 account_id: AccountId,
4380 product_type: BybitProductType,
4381 instrument_id: Option<InstrumentId>,
4382 open_only: bool,
4383 start: Option<Timestamp>,
4384 end: Option<Timestamp>,
4385 limit: Option<u32>,
4386 load_ids: Option<&[InstrumentId]>,
4387 history_window: (Option<i64>, Option<i64>),
4388 ) -> anyhow::Result<ReportRead<OrderStatusReport>> {
4389 let (history_start, history_end) = history_window;
4390
4391 if let Some(instrument_id) = instrument_id {
4392 anyhow::ensure!(
4393 instrument_in_scope(instrument_id, load_ids),
4394 "requested instrument {instrument_id} is outside reconciliation scope"
4395 );
4396 }
4397
4398 let symbol_param = if let Some(id) = instrument_id.as_ref() {
4400 let symbol_str = id.symbol.as_str();
4401 if symbol_str.is_empty() {
4402 None
4403 } else {
4404 Some(BybitSymbol::new(symbol_str)?.raw_symbol().to_string())
4405 }
4406 } else {
4407 None
4408 };
4409
4410 let settle_coins_to_query: Vec<Option<String>> =
4413 if product_type == BybitProductType::Linear && symbol_param.is_none() {
4414 vec![Some("USDT".to_string()), Some("USDC".to_string())]
4415 } else {
4416 match product_type {
4417 BybitProductType::Inverse => vec![None],
4418 _ => vec![None],
4419 }
4420 };
4421
4422 let mut all_collected_orders = Vec::new();
4423 let mut total_collected_across_coins = 0;
4424
4425 for settle_coin in settle_coins_to_query {
4426 let remaining_limit = if let Some(limit) = limit {
4427 let remaining = (limit as usize).saturating_sub(total_collected_across_coins);
4428 if remaining == 0 {
4429 break;
4430 }
4431 Some(remaining as u32)
4432 } else {
4433 None
4434 };
4435
4436 let orders_for_coin = if open_only {
4437 let mut all_orders = Vec::new();
4438 let mut seen_ids: AHashSet<Ustr> = AHashSet::new();
4439
4440 let order_filters: Vec<Option<BybitOrderFilter>> =
4443 if product_type == BybitProductType::Option {
4444 vec![None]
4445 } else {
4446 vec![None, Some(BybitOrderFilter::StopOrder)]
4447 };
4448
4449 let open_only_modes = [None, Some(BybitOpenOnly::ClosedRecent)];
4450
4451 for oo in open_only_modes {
4452 for order_filter in &order_filters {
4453 let mut cursor: Option<String> = None;
4454 let mut cursor_walk = CursorWalk::default();
4455
4456 loop {
4457 let remaining = if let Some(limit) = remaining_limit {
4458 (limit as usize).saturating_sub(all_orders.len())
4459 } else {
4460 usize::MAX
4461 };
4462
4463 if remaining == 0 {
4464 break;
4465 }
4466
4467 let page_limit = std::cmp::min(remaining, 50);
4469
4470 let mut p = BybitOpenOrdersParamsBuilder::default();
4471 p.category(product_type);
4472
4473 if let Some(symbol) = symbol_param.clone() {
4474 p.symbol(symbol);
4475 }
4476
4477 if let Some(coin) = settle_coin.clone() {
4478 p.settle_coin(coin);
4479 }
4480
4481 if let Some(of) = order_filter {
4482 p.order_filter(*of);
4483 }
4484
4485 if let Some(oo) = oo {
4486 p.open_only(oo);
4487 }
4488 p.limit(page_limit as u32);
4489
4490 if let Some(c) = cursor {
4491 p.cursor(c);
4492 }
4493 let params = p.build().build_anyhow()?;
4494 let response: BybitOpenOrdersResponse = self
4495 .inner
4496 .send_request(
4497 Method::GET,
4498 BYBIT_ORDER_REALTIME,
4499 Some(¶ms),
4500 None,
4501 true,
4502 )
4503 .await?;
4504
4505 for order in response.result.list {
4506 if seen_ids.insert(order.order_id) {
4507 all_orders.push(order);
4508 }
4509 }
4510
4511 if oo.is_some() {
4513 break;
4514 }
4515
4516 cursor = cursor_walk
4517 .advance(BYBIT_ORDER_REALTIME, response.result.next_page_cursor)?;
4518
4519 if cursor.is_none() {
4520 break;
4521 }
4522 }
4523 }
4524 }
4525
4526 all_orders
4527 } else {
4528 let mut all_orders = Vec::new();
4531 let mut open_orders = Vec::new();
4532 let mut seen_open_ids: AHashSet<Ustr> = AHashSet::new();
4533
4534 let order_filters: Vec<Option<BybitOrderFilter>> =
4537 if product_type == BybitProductType::Option {
4538 vec![None]
4539 } else {
4540 vec![None, Some(BybitOrderFilter::StopOrder)]
4541 };
4542
4543 for order_filter in &order_filters {
4544 let mut cursor: Option<String> = None;
4545 let mut cursor_walk = CursorWalk::default();
4546
4547 loop {
4548 let remaining = if let Some(limit) = remaining_limit {
4549 (limit as usize).saturating_sub(open_orders.len())
4550 } else {
4551 usize::MAX
4552 };
4553
4554 if remaining == 0 {
4555 break;
4556 }
4557
4558 let page_limit = std::cmp::min(remaining, 50);
4560
4561 let mut open_params = BybitOpenOrdersParamsBuilder::default();
4562 open_params.category(product_type);
4563
4564 if let Some(symbol) = symbol_param.clone() {
4565 open_params.symbol(symbol);
4566 }
4567
4568 if let Some(coin) = settle_coin.clone() {
4569 open_params.settle_coin(coin);
4570 }
4571
4572 if let Some(of) = order_filter {
4573 open_params.order_filter(*of);
4574 }
4575 open_params.limit(page_limit as u32);
4576
4577 if let Some(c) = cursor {
4578 open_params.cursor(c);
4579 }
4580 let open_params = open_params.build().build_anyhow()?;
4581 let open_response: BybitOpenOrdersResponse = self
4582 .inner
4583 .send_request(
4584 Method::GET,
4585 BYBIT_ORDER_REALTIME,
4586 Some(&open_params),
4587 None,
4588 true,
4589 )
4590 .await?;
4591
4592 for order in open_response.result.list {
4593 if !seen_open_ids.contains(&order.order_id) {
4594 seen_open_ids.insert(order.order_id);
4595 open_orders.push(order);
4596 }
4597 }
4598
4599 cursor = cursor_walk
4600 .advance(BYBIT_ORDER_REALTIME, open_response.result.next_page_cursor)?;
4601
4602 if cursor.is_none() {
4603 break;
4604 }
4605 }
4606 }
4607
4608 let seen_order_ids: AHashSet<Ustr> = seen_open_ids;
4609 let total_open_orders = open_orders.len();
4610
4611 all_orders.extend(open_orders);
4612
4613 let mut total_history_orders = 0;
4614
4615 for order_filter in &order_filters {
4616 let mut cursor: Option<String> = None;
4617 let mut cursor_walk = CursorWalk::default();
4618
4619 loop {
4620 let total_orders = total_open_orders + total_history_orders;
4621 let remaining = if let Some(limit) = remaining_limit {
4622 (limit as usize).saturating_sub(total_orders)
4623 } else {
4624 usize::MAX
4625 };
4626
4627 if remaining == 0 {
4628 break;
4629 }
4630
4631 let page_limit = std::cmp::min(remaining, 50);
4633
4634 let mut history_params = BybitOrderHistoryParamsBuilder::default();
4635 history_params.category(product_type);
4636
4637 if let Some(symbol) = symbol_param.clone() {
4638 history_params.symbol(symbol);
4639 }
4640
4641 if let Some(coin) = settle_coin.clone() {
4642 history_params.settle_coin(coin);
4643 }
4644
4645 if let Some(of) = order_filter {
4646 history_params.order_filter(*of);
4647 }
4648
4649 if let Some(start) = start {
4650 history_params.start_time(start.as_millisecond());
4651 }
4652
4653 if let Some(end) = end {
4654 history_params.end_time(end.as_millisecond());
4655 }
4656 history_params.limit(page_limit as u32);
4657
4658 if let Some(c) = cursor {
4659 history_params.cursor(c);
4660 }
4661 let history_params = history_params.build().build_anyhow()?;
4662 let history_response: BybitOrderHistoryResponse = self
4663 .inner
4664 .send_request(
4665 Method::GET,
4666 BYBIT_ORDER_HISTORY,
4667 Some(&history_params),
4668 None,
4669 true,
4670 )
4671 .await?;
4672
4673 for order in history_response.result.list {
4675 if !seen_order_ids.contains(&order.order_id) {
4676 all_orders.push(order);
4677 total_history_orders += 1;
4678 }
4679 }
4680
4681 cursor = cursor_walk.advance(
4682 BYBIT_ORDER_HISTORY,
4683 history_response.result.next_page_cursor,
4684 )?;
4685
4686 if cursor.is_none() {
4687 break;
4688 }
4689 }
4690 }
4691
4692 all_orders
4693 };
4694
4695 total_collected_across_coins += orders_for_coin.len();
4696 all_collected_orders.extend(orders_for_coin);
4697 }
4698
4699 let ts_init = self.generate_ts_init();
4700 let mut read = ReportRead::new();
4701
4702 for order in all_collected_orders {
4703 anyhow::ensure!(!order.symbol.is_empty(), "order symbol is empty");
4704 let symbol = Symbol::from_ustr_unchecked(make_bybit_symbol(order.symbol, product_type));
4705 let id = InstrumentId::new(symbol, *BYBIT_VENUE);
4706
4707 if instrument_id.is_some_and(|requested| requested != id)
4708 || !instrument_in_scope(id, load_ids)
4709 {
4710 log::debug!("Skipping out-of-scope order report for {id}");
4711 continue;
4712 }
4713
4714 let historical = matches!(
4715 order.order_status,
4716 BybitOrderStatus::Rejected
4717 | BybitOrderStatus::PartiallyFilledCanceled
4718 | BybitOrderStatus::Filled
4719 | BybitOrderStatus::Canceled
4720 | BybitOrderStatus::Deactivated
4721 );
4722
4723 if historical && !millis_in_window(&order.updated_time, history_start, history_end)? {
4724 continue;
4725 }
4726
4727 let instrument = match self.instrument_from_cache(&symbol) {
4728 Ok(instrument) => instrument,
4729 Err(_) if historical => {
4730 read.record_historical_miss(id);
4731 continue;
4732 }
4733 Err(e) => return Err(e),
4734 };
4735
4736 let report = parse_order_status_report(&order, &instrument, account_id, ts_init)?;
4737 read.reports.push(report);
4738 }
4739
4740 Ok(read)
4741 }
4742
4743 pub async fn request_fill_reports(
4759 &self,
4760 account_id: AccountId,
4761 product_type: BybitProductType,
4762 instrument_id: Option<InstrumentId>,
4763 start: Option<i64>,
4764 end: Option<i64>,
4765 limit: Option<u32>,
4766 ) -> anyhow::Result<Vec<FillReport>> {
4767 self.request_fill_reports_scoped(
4768 account_id,
4769 product_type,
4770 instrument_id,
4771 start,
4772 end,
4773 limit,
4774 None,
4775 )
4776 .await?
4777 .into_reports()
4778 }
4779
4780 #[expect(clippy::too_many_arguments)]
4781 pub(crate) async fn request_fill_reports_scoped(
4782 &self,
4783 account_id: AccountId,
4784 product_type: BybitProductType,
4785 instrument_id: Option<InstrumentId>,
4786 start: Option<i64>,
4787 end: Option<i64>,
4788 limit: Option<u32>,
4789 load_ids: Option<&[InstrumentId]>,
4790 ) -> anyhow::Result<ReportRead<FillReport>> {
4791 if let Some(instrument_id) = instrument_id {
4792 anyhow::ensure!(
4793 instrument_in_scope(instrument_id, load_ids),
4794 "requested instrument {instrument_id} is outside reconciliation scope"
4795 );
4796 }
4797
4798 let symbol = if let Some(id) = instrument_id {
4800 let bybit_symbol = BybitSymbol::new(id.symbol.as_str())?;
4801 Some(bybit_symbol.raw_symbol().to_string())
4802 } else {
4803 None
4804 };
4805
4806 let mut all_executions = Vec::new();
4808 let mut cursor: Option<String> = None;
4809 let mut cursor_walk = CursorWalk::default();
4810
4811 loop {
4812 let remaining = limit.map_or(usize::MAX, |limit| {
4814 (limit as usize).saturating_sub(all_executions.len())
4815 });
4816
4817 if remaining == 0 {
4819 break;
4820 }
4821
4822 let page_limit = std::cmp::min(remaining, 100);
4824
4825 let params = BybitTradeHistoryParams {
4826 category: product_type,
4827 symbol: symbol.clone(),
4828 base_coin: None,
4829 order_id: None,
4830 order_link_id: None,
4831 start_time: start,
4832 end_time: end,
4833 exec_type: None,
4834 limit: Some(page_limit as u32),
4835 cursor: cursor.clone(),
4836 };
4837
4838 let response = self.inner.get_trade_history(¶ms).await?;
4839 for execution in response.result.list {
4840 if execution.exec_type == BybitExecType::Funding {
4841 log::debug!(
4842 "Skipping funding execution: symbol={}, order_id={}, exec_id={}",
4843 execution.symbol,
4844 execution.order_id,
4845 execution.exec_id,
4846 );
4847 continue;
4848 }
4849
4850 all_executions.push(execution);
4851 }
4852
4853 cursor = cursor_walk.advance(BYBIT_EXECUTION_LIST, response.result.next_page_cursor)?;
4854 if cursor.is_none() {
4855 break;
4856 }
4857 }
4858
4859 let ts_init = self.generate_ts_init();
4860 let mut read = ReportRead::new();
4861
4862 for execution in all_executions {
4863 anyhow::ensure!(!execution.symbol.is_empty(), "execution symbol is empty");
4864 let symbol =
4865 Symbol::from_ustr_unchecked(make_bybit_symbol(execution.symbol, product_type));
4866 let id = InstrumentId::new(symbol, *BYBIT_VENUE);
4867
4868 if instrument_id.is_some_and(|requested| requested != id)
4869 || !instrument_in_scope(id, load_ids)
4870 {
4871 log::debug!("Skipping out-of-scope fill report for {id}");
4872 continue;
4873 }
4874
4875 if !millis_in_window(&execution.exec_time, start, end)? {
4876 continue;
4877 }
4878
4879 let Ok(instrument) = self.instrument_from_cache(&symbol) else {
4880 read.record_historical_miss(id);
4881 continue;
4882 };
4883
4884 let report = parse_fill_report(&execution, account_id, &instrument, ts_init)?;
4885 read.reports.push(report);
4886 }
4887
4888 Ok(read)
4889 }
4890
4891 pub async fn request_position_status_reports(
4912 &self,
4913 account_id: AccountId,
4914 product_type: BybitProductType,
4915 instrument_id: Option<InstrumentId>,
4916 ) -> anyhow::Result<Vec<PositionStatusReport>> {
4917 self.request_position_status_reports_scoped(account_id, product_type, instrument_id, None)
4918 .await
4919 }
4920
4921 pub(crate) async fn request_position_status_reports_scoped(
4922 &self,
4923 account_id: AccountId,
4924 product_type: BybitProductType,
4925 instrument_id: Option<InstrumentId>,
4926 load_ids: Option<&[InstrumentId]>,
4927 ) -> anyhow::Result<Vec<PositionStatusReport>> {
4928 if let Some(instrument_id) = instrument_id {
4929 anyhow::ensure!(
4930 instrument_in_scope(instrument_id, load_ids),
4931 "requested instrument {instrument_id} is outside reconciliation scope"
4932 );
4933 }
4934
4935 if product_type == BybitProductType::Spot {
4937 if self.use_spot_position_reports.load(Ordering::Relaxed) {
4938 let Some(instrument_id) = instrument_id else {
4939 anyhow::bail!(
4940 "SPOT wallet balances carry no pair identity and cannot be attributed for a bulk position report request"
4941 );
4942 };
4943
4944 self.instrument_from_cache(&instrument_id.symbol)?;
4945 return self
4946 .generate_spot_position_reports_from_wallet(account_id, instrument_id)
4947 .await;
4948 } else {
4949 return Ok(Vec::new());
4951 }
4952 }
4953
4954 let ts_init = self.generate_ts_init();
4955 let mut reports = Vec::new();
4956
4957 let symbol = if let Some(id) = instrument_id {
4959 let symbol_str = id.symbol.as_str();
4960 if symbol_str.is_empty() {
4961 anyhow::bail!("InstrumentId symbol is empty");
4962 }
4963 let bybit_symbol = BybitSymbol::new(symbol_str)?;
4964 Some(bybit_symbol.raw_symbol().to_string())
4965 } else {
4966 None
4967 };
4968
4969 let settle_coins: &[Option<&str>] =
4971 if product_type == BybitProductType::Linear && symbol.is_none() {
4972 &[Some("USDT"), Some("USDC")]
4973 } else {
4974 &[None]
4975 };
4976
4977 for settle_coin in settle_coins {
4978 let params = BybitPositionListParams {
4979 category: product_type,
4980 symbol: symbol.clone(),
4981 base_coin: None,
4982 settle_coin: settle_coin.map(str::to_string),
4983 limit: Some(200), cursor: None,
4985 };
4986
4987 self.request_position_pages(account_id, params, ts_init, load_ids, &mut reports)
4988 .await?;
4989 }
4990
4991 Ok(reports)
4992 }
4993
4994 async fn request_position_pages(
4995 &self,
4996 account_id: AccountId,
4997 mut params: BybitPositionListParams,
4998 ts_init: UnixNanos,
4999 load_ids: Option<&[InstrumentId]>,
5000 reports: &mut Vec<PositionStatusReport>,
5001 ) -> anyhow::Result<()> {
5002 let mut cursor_walk = CursorWalk::default();
5003
5004 loop {
5005 let response = self.inner.get_positions(¶ms).await?;
5006
5007 for position in response.result.list {
5008 if position.symbol.is_empty() {
5009 anyhow::bail!(
5010 "Position symbol is empty, category={:?}, symbol={:?}, settle_coin={:?}",
5011 params.category,
5012 params.symbol,
5013 params.settle_coin,
5014 );
5015 }
5016
5017 let symbol = Symbol::new(format!(
5018 "{}{}",
5019 position.symbol.as_str(),
5020 params.category.suffix()
5021 ));
5022 let id = InstrumentId::new(symbol, *BYBIT_VENUE);
5023
5024 if params
5025 .symbol
5026 .as_ref()
5027 .is_some_and(|requested| requested != position.symbol.as_str())
5028 || !instrument_in_scope(id, load_ids)
5029 {
5030 log::debug!("Skipping out-of-scope position report for {id}");
5031 continue;
5032 }
5033
5034 let instrument = self.instrument_from_cache(&symbol)?;
5035 let report =
5036 parse_position_status_report(&position, account_id, &instrument, ts_init)
5037 .with_context(|| format!("failed to parse position report for {symbol}"))?;
5038 reports.push(report);
5039 }
5040
5041 params.cursor =
5042 cursor_walk.advance(BYBIT_POSITION_LIST, response.result.next_page_cursor)?;
5043
5044 if params.cursor.is_none() {
5045 break;
5046 }
5047 }
5048
5049 Ok(())
5050 }
5051
5052 async fn query_order_by_id(
5053 &self,
5054 product_type: BybitProductType,
5055 order_id: &str,
5056 endpoint: &str,
5057 context: &str,
5058 ) -> anyhow::Result<BybitOrder> {
5059 let mut query_params = BybitOpenOrdersParamsBuilder::default();
5060 query_params.category(product_type);
5061 query_params.order_id(order_id.to_string());
5062
5063 let query_params = query_params.build().build_anyhow()?;
5064 let order_response: BybitOpenOrdersResponse = self
5065 .inner
5066 .send_request(Method::GET, endpoint, Some(&query_params), None, true)
5067 .await?;
5068
5069 order_response
5070 .result
5071 .list
5072 .into_iter()
5073 .next()
5074 .ok_or_else(|| anyhow::anyhow!("No order returned {context}"))
5075 }
5076}
5077
5078fn instrument_base_coin(
5079 product_type: BybitProductType,
5080 symbol: Option<&str>,
5081 base_coin: Option<Ustr>,
5082) -> Option<String> {
5083 base_coin.map(|coin| coin.to_string()).or_else(|| {
5084 (product_type == BybitProductType::Option && symbol.is_none()).then(|| "All".to_string())
5085 })
5086}
5087
5088fn instrument_or_warn(
5089 product_type: BybitProductType,
5090 symbol: Ustr,
5091 result: anyhow::Result<InstrumentAny>,
5092) -> Option<InstrumentAny> {
5093 result
5094 .inspect_err(|e| {
5095 let symbol = make_bybit_symbol(symbol, product_type);
5096 log::warn!("Failed to parse instrument {symbol}: {e}");
5097 })
5098 .ok()
5099}
5100
5101fn perp_status(status: MarketStatusAction, is_scheduled_perp: bool) -> MarketStatusAction {
5102 if status == MarketStatusAction::Trading && is_scheduled_perp {
5104 MarketStatusAction::PreClose
5105 } else {
5106 status
5107 }
5108}
5109
5110#[cfg(test)]
5111mod tests {
5112 use nautilus_testkit::http::assert_http_redirect_rejected;
5113 use rstest::rstest;
5114
5115 use super::*;
5116
5117 #[tokio::test]
5118 async fn test_authenticated_client_rejects_redirects() {
5119 let client = BybitRawHttpClient::build_http_client(3, None).unwrap();
5120 assert_http_redirect_rejected(|url| async move {
5121 client
5122 .get(url, None, None, Some(3), None)
5123 .await
5124 .unwrap()
5125 .status
5126 .as_u16()
5127 })
5128 .await;
5129 }
5130
5131 #[rstest]
5132 fn test_client_creation() {
5133 let client = BybitHttpClient::new(None, 60, 3, 1000, 10_000, 5_000, None);
5134 assert!(client.is_ok());
5135
5136 let client = client.unwrap();
5137 assert!(client.base_url().contains("bybit.com"));
5138 assert!(client.credential().is_none());
5139 }
5140
5141 #[rstest]
5142 fn test_client_with_credentials() {
5143 let client = BybitHttpClient::with_credentials(
5144 "test_key".to_string(),
5145 "test_secret".to_string(),
5146 Some("https://api-testnet.bybit.com".to_string()),
5147 60,
5148 3,
5149 1000,
5150 10_000,
5151 5_000,
5152 None,
5153 );
5154 assert!(client.is_ok());
5155
5156 let client = client.unwrap();
5157 assert!(client.credential().is_some());
5158 }
5159
5160 #[rstest]
5161 fn test_build_path_with_params() {
5162 #[derive(Serialize)]
5163 struct TestParams {
5164 category: String,
5165 symbol: String,
5166 }
5167
5168 let params = TestParams {
5169 category: "linear".to_string(),
5170 symbol: "BTCUSDT".to_string(),
5171 };
5172
5173 let path = BybitRawHttpClient::build_path("/v5/market/test", ¶ms);
5174 assert!(path.is_ok());
5175 assert!(path.unwrap().contains("category=linear"));
5176 }
5177
5178 #[rstest]
5179 fn test_build_path_without_params() {
5180 let params = ();
5181 let path = BybitRawHttpClient::build_path("/v5/market/time", ¶ms);
5182 assert!(path.is_ok());
5183 assert_eq!(path.unwrap(), "/v5/market/time");
5184 }
5185
5186 #[rstest]
5187 fn test_params_serialization_matches_build_path() {
5188 #[derive(Serialize)]
5190 struct TestParams {
5191 category: String,
5192 limit: u32,
5193 }
5194
5195 let params = TestParams {
5196 category: "spot".to_string(),
5197 limit: 50,
5198 };
5199
5200 let old_path = BybitRawHttpClient::build_path(BYBIT_ORDER_REALTIME, ¶ms).unwrap();
5202 let old_query = old_path.split('?').nth(1).unwrap_or("");
5203
5204 let new_query = serde_urlencoded::to_string(¶ms).unwrap();
5206
5207 assert_eq!(old_query, new_query);
5209 }
5210
5211 #[rstest]
5212 fn test_params_serialization_order() {
5213 #[derive(Serialize)]
5215 struct OrderParams {
5216 category: String,
5217 symbol: String,
5218 limit: u32,
5219 }
5220
5221 let params = OrderParams {
5222 category: "spot".to_string(),
5223 symbol: "BTCUSDT".to_string(),
5224 limit: 50,
5225 };
5226
5227 let query1 = serde_urlencoded::to_string(¶ms).unwrap();
5229 let query2 = serde_urlencoded::to_string(¶ms).unwrap();
5230 let query3 = serde_urlencoded::to_string(¶ms).unwrap();
5231
5232 assert_eq!(query1, query2);
5233 assert_eq!(query2, query3);
5234
5235 assert!(query1.contains("category=spot"));
5237 assert!(query1.contains("symbol=BTCUSDT"));
5238 assert!(query1.contains("limit=50"));
5239 }
5240
5241 #[rstest]
5242 #[case(403, "Access too frequent", true)]
5243 #[case(403, "Forbidden", false)]
5244 #[case(429, "Access too frequent", false)]
5245 fn test_rate_limit_403_detection(
5246 #[case] status: u16,
5247 #[case] body: &str,
5248 #[case] expected: bool,
5249 ) {
5250 assert_eq!(
5251 BybitRawHttpClient::is_rate_limit_403(status, body),
5252 expected
5253 );
5254 }
5255
5256 #[rstest]
5257 fn test_cursor_walk_stops_on_absent_or_empty_cursor() {
5258 let mut walk = CursorWalk::default();
5259
5260 assert_eq!(walk.advance("/endpoint", None).unwrap(), None);
5261 assert_eq!(
5262 walk.advance("/endpoint", Some(String::new())).unwrap(),
5263 None
5264 );
5265 assert!(walk.followed.is_empty());
5266 }
5267
5268 #[rstest]
5269 fn test_cursor_walk_follows_advancing_cursors() {
5270 let mut walk = CursorWalk::default();
5271
5272 for page in ["page-2", "page-3", "page-4"] {
5273 assert_eq!(
5274 walk.advance("/endpoint", Some(page.to_string())).unwrap(),
5275 Some(page.to_string())
5276 );
5277 }
5278 }
5279
5280 #[rstest]
5281 fn test_cursor_walk_rejects_a_cursor_that_does_not_advance() {
5282 let mut walk = CursorWalk::default();
5283 walk.advance("/endpoint", Some("page-2".to_string()))
5284 .unwrap();
5285
5286 let error = walk
5287 .advance("/endpoint", Some("page-2".to_string()))
5288 .expect_err("a cursor that addresses the page it came with has no next page");
5289
5290 assert_eq!(
5291 error.to_string(),
5292 r#"/endpoint pagination cursor did not advance from "page-2""#
5293 );
5294 }
5295
5296 #[rstest]
5297 #[case::two_cycle(vec!["page-2", "page-3"], "page-2")]
5298 #[case::long_cycle(vec!["page-2", "page-3", "page-4", "page-5"], "page-3")]
5299 fn test_cursor_walk_rejects_a_cursor_already_followed(
5300 #[case] followed: Vec<&str>,
5301 #[case] repeated: &str,
5302 ) {
5303 let mut walk = CursorWalk::default();
5304 for cursor in followed {
5305 walk.advance("/endpoint", Some(cursor.to_string())).unwrap();
5306 }
5307
5308 let error = walk
5309 .advance("/endpoint", Some(repeated.to_string()))
5310 .expect_err("a cursor already followed has no further page to offer");
5311
5312 assert_eq!(
5313 error.to_string(),
5314 format!(r#"/endpoint pagination repeated cursor "{repeated}""#)
5315 );
5316 }
5317}