Skip to main content

nautilus_bybit/http/
client.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Provides the HTTP client integration for the [Bybit](https://bybit.com) REST API.
17//!
18//! Bybit API reference <https://bybit-exchange.github.io/docs/>.
19
20use 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};
95use crate::common::{
96    consts::{BYBIT_NAUTILUS_BROKER_ID, BYBIT_VENUE},
97    credential::{Credential, credential_env_vars},
98    enums::{
99        BybitAccountType, BybitBboSideType, BybitContractType, BybitEnvironment, BybitExecType,
100        BybitMarginMode, BybitOpenOnly, BybitOrderFilter, BybitOrderSide, BybitOrderSmpType,
101        BybitOrderType, BybitPositionIdx, BybitPositionMode, BybitProductType, BybitRepayStatus,
102        BybitTpSlMode,
103    },
104    models::{BybitCursorListResponse, BybitErrorCheck, BybitResponseCheck},
105    parse::{
106        bar_spec_to_bybit_interval, bybit_rejection_due_post_only, make_bybit_symbol,
107        map_time_in_force, parse_account_state, parse_fill_report, parse_funding_rate,
108        parse_inverse_instrument, parse_kline_bar, parse_linear_instrument,
109        parse_option_instrument, parse_order_status_report, parse_orderbook,
110        parse_position_status_report, parse_spot_instrument, parse_trade_tick, spot_leverage,
111        spot_market_unit, trigger_direction,
112    },
113    rate_limit::{
114        BYBIT_RATE_LIMIT_HEADER, BYBIT_RATE_LIMIT_RESET_HEADER, BYBIT_RATE_LIMIT_STATUS_HEADER,
115        BybitRateLimiter, batch_call_limit, batch_endpoint_limit, batch_send_limit, batch_weight,
116        category_from_payload,
117    },
118    retry::should_retry_http,
119    symbol::BybitSymbol,
120    urls::bybit_http_base_url,
121};
122
123const DEFAULT_RECV_WINDOW_MS: u64 = 5_000;
124
125trait BuilderResultExt<T> {
126    fn build_anyhow(self) -> anyhow::Result<T>;
127}
128
129impl<T, E: Display> BuilderResultExt<T> for Result<T, E> {
130    fn build_anyhow(self) -> anyhow::Result<T> {
131        self.map_err(|e| anyhow::anyhow!("{e}"))
132    }
133}
134
135const BYBIT_INSTRUMENTS_INFO: &str = "/v5/market/instruments-info";
136const BYBIT_ORDER_REALTIME: &str = "/v5/order/realtime";
137const BYBIT_ORDER_HISTORY: &str = "/v5/order/history";
138const BYBIT_EXECUTION_LIST: &str = "/v5/execution/list";
139const BYBIT_POSITION_LIST: &str = "/v5/position/list";
140
141/// Tracks the cursors one paginated walk has already followed.
142///
143/// A venue can serve a page whose `nextPageCursor` addresses that same page. Requesting it
144/// returns the same rows and the same cursor, so an empty cursor never arrives and the walk does
145/// not terminate. A cursor that does not advance, or that the walk has already followed, has no
146/// further page to offer.
147///
148/// The two cases are separated because they describe different venue behavior: a cursor that
149/// repeats the one just used has stopped advancing, while a cursor seen earlier in the walk means
150/// the pages have cycled. `nautilus-polymarket` draws the same distinction in
151/// `http::pagination::PaginationError`.
152#[derive(Debug, Default)]
153struct CursorWalk {
154    followed: AHashSet<String>,
155    last: Option<String>,
156}
157
158impl CursorWalk {
159    /// Returns the cursor to follow next, or `None` when the walk is complete.
160    ///
161    /// # Errors
162    ///
163    /// Returns an error if the cursor stops advancing or repeats one already followed. Stopping
164    /// with the rows gathered so far would hand the caller a truncated result it cannot distinguish
165    /// from a complete one.
166    fn advance(
167        &mut self,
168        endpoint: &str,
169        cursor: Option<String>,
170    ) -> anyhow::Result<Option<String>> {
171        let Some(cursor) = cursor.filter(|cursor| !cursor.is_empty()) else {
172            return Ok(None);
173        };
174
175        anyhow::ensure!(
176            self.last.as_deref() != Some(cursor.as_str()),
177            "{endpoint} pagination cursor did not advance from {cursor:?}",
178        );
179        anyhow::ensure!(
180            self.followed.insert(cursor.clone()),
181            "{endpoint} pagination repeated cursor {cursor:?}",
182        );
183
184        self.last = Some(cursor.clone());
185
186        Ok(Some(cursor))
187    }
188}
189
190/// Legacy conservative Bybit REST quota retained for source compatibility.
191pub static BYBIT_REST_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
192    Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant")
193});
194
195/// Legacy Bybit repayment quota retained for source compatibility.
196pub static BYBIT_REPAY_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
197    Quota::per_second(NonZeroU32::new(1).expect("non-zero")).expect("valid constant")
198});
199
200/// Raw HTTP client for low-level Bybit API operations.
201///
202/// This client handles request/response operations with the Bybit API,
203/// returning venue-specific response types. It does not parse to Nautilus domain types.
204#[cfg_attr(
205    feature = "python",
206    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
207)]
208#[cfg_attr(
209    feature = "python",
210    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
211)]
212#[derive(Clone)]
213pub struct BybitRawHttpClient {
214    base_url: String,
215    client: Arc<ArcSwap<HttpClient>>,
216    rate_limiter: BybitRateLimiter,
217    credential: Option<Credential>,
218    mm_level: Arc<AtomicU8>,
219    mm_detection: Arc<AtomicBool>,
220    recv_window_ms: u64,
221    timeout_secs: u64,
222    proxy_url: Option<String>,
223    session_generation: Arc<AtomicU64>,
224    retry_manager: RetryManager<BybitHttpError>,
225    cancellation_token: Arc<parking_lot::Mutex<CancellationToken>>,
226}
227
228impl Default for BybitRawHttpClient {
229    fn default() -> Self {
230        Self::new(None, 60, 3, 1000, 10_000, DEFAULT_RECV_WINDOW_MS, None)
231            .expect("Failed to create default BybitRawHttpClient")
232    }
233}
234
235impl Debug for BybitRawHttpClient {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        f.debug_struct(stringify!(BybitRawHttpClient))
238            .field("base_url", &self.base_url)
239            .field("has_credentials", &self.credential.is_some())
240            .field("recv_window_ms", &self.recv_window_ms)
241            .finish()
242    }
243}
244
245impl BybitRawHttpClient {
246    /// Cancels all pending HTTP requests.
247    pub fn cancel_all_requests(&self) {
248        self.cancellation_token.lock().cancel();
249    }
250
251    /// Replaces the cancelled token with a fresh one so subsequent
252    /// requests are not immediately short-circuited.
253    pub fn reset_cancellation_token(&self) {
254        let mut guard = self.cancellation_token.lock();
255        *guard = CancellationToken::new();
256    }
257
258    /// Returns a clone of the current cancellation token.
259    pub fn cancellation_token(&self) -> CancellationToken {
260        self.cancellation_token.lock().clone()
261    }
262
263    /// Creates a new [`BybitRawHttpClient`] using the default Bybit HTTP URL.
264    ///
265    /// # Errors
266    ///
267    /// Returns an error if the retry manager cannot be created.
268    pub fn new(
269        base_url: Option<String>,
270        timeout_secs: u64,
271        max_retries: u32,
272        retry_delay_ms: u64,
273        retry_delay_max_ms: u64,
274        recv_window_ms: u64,
275        proxy_url: Option<String>,
276    ) -> Result<Self, BybitHttpError> {
277        let retry_config = RetryConfig {
278            max_retries,
279            initial_delay_ms: retry_delay_ms,
280            max_delay_ms: retry_delay_max_ms,
281            backoff_factor: 2.0,
282            jitter_ms: 1000,
283            operation_timeout_ms: Some(60_000),
284            immediate_first: false,
285            max_elapsed_ms: Some(180_000),
286        };
287
288        let retry_manager = RetryManager::new(retry_config);
289        let base_url =
290            base_url.unwrap_or_else(|| bybit_http_base_url(BybitEnvironment::Mainnet).to_string());
291        let rate_limiter = BybitRateLimiter::for_http(&base_url, None, proxy_url.as_deref());
292        let client = Self::build_http_client(timeout_secs, proxy_url.clone())?;
293        let session_generation = rate_limiter.http_session_generation();
294
295        Ok(Self {
296            base_url,
297            client: Arc::new(ArcSwap::from_pointee(client)),
298            rate_limiter,
299            credential: None,
300            mm_level: Arc::new(AtomicU8::new(0)),
301            mm_detection: Arc::new(AtomicBool::new(false)),
302            recv_window_ms,
303            timeout_secs,
304            proxy_url,
305            session_generation: Arc::new(AtomicU64::new(session_generation)),
306            retry_manager,
307            cancellation_token: Arc::new(parking_lot::Mutex::new(CancellationToken::new())),
308        })
309    }
310
311    /// Creates a new [`BybitRawHttpClient`] configured with credentials.
312    ///
313    /// # Errors
314    ///
315    /// Returns an error if the HTTP client cannot be created.
316    #[expect(clippy::too_many_arguments)]
317    pub fn with_credentials(
318        api_key: String,
319        api_secret: String,
320        base_url: Option<String>,
321        timeout_secs: u64,
322        max_retries: u32,
323        retry_delay_ms: u64,
324        retry_delay_max_ms: u64,
325        recv_window_ms: u64,
326        proxy_url: Option<String>,
327    ) -> Result<Self, BybitHttpError> {
328        let retry_config = RetryConfig {
329            max_retries,
330            initial_delay_ms: retry_delay_ms,
331            max_delay_ms: retry_delay_max_ms,
332            backoff_factor: 2.0,
333            jitter_ms: 1000,
334            operation_timeout_ms: Some(60_000),
335            immediate_first: false,
336            max_elapsed_ms: Some(180_000),
337        };
338
339        let retry_manager = RetryManager::new(retry_config);
340        let base_url =
341            base_url.unwrap_or_else(|| bybit_http_base_url(BybitEnvironment::Mainnet).to_string());
342        let credential = Credential::new(api_key, api_secret);
343        let rate_limiter =
344            BybitRateLimiter::for_http(&base_url, Some(credential.api_key()), proxy_url.as_deref());
345        let client = Self::build_http_client(timeout_secs, proxy_url.clone())?;
346        let session_generation = rate_limiter.http_session_generation();
347
348        Ok(Self {
349            base_url,
350            client: Arc::new(ArcSwap::from_pointee(client)),
351            rate_limiter,
352            credential: Some(credential),
353            mm_level: Arc::new(AtomicU8::new(0)),
354            mm_detection: Arc::new(AtomicBool::new(false)),
355            recv_window_ms,
356            timeout_secs,
357            proxy_url,
358            session_generation: Arc::new(AtomicU64::new(session_generation)),
359            retry_manager,
360            cancellation_token: Arc::new(parking_lot::Mutex::new(CancellationToken::new())),
361        })
362    }
363
364    /// Creates a new [`BybitRawHttpClient`] with environment variable credential resolution.
365    ///
366    /// If `api_key` or `api_secret` are not provided, they will be loaded from
367    /// environment variables based on the environment flags:
368    /// - Demo: `BYBIT_DEMO_API_KEY`, `BYBIT_DEMO_API_SECRET`
369    /// - Testnet: `BYBIT_TESTNET_API_KEY`, `BYBIT_TESTNET_API_SECRET`
370    /// - Mainnet: `BYBIT_API_KEY`, `BYBIT_API_SECRET`
371    ///
372    /// # Errors
373    ///
374    /// Returns an error if the HTTP client cannot be created.
375    #[expect(clippy::too_many_arguments)]
376    pub fn new_with_env(
377        api_key: Option<String>,
378        api_secret: Option<String>,
379        base_url: Option<String>,
380        demo: bool,
381        testnet: bool,
382        timeout_secs: u64,
383        max_retries: u32,
384        retry_delay_ms: u64,
385        retry_delay_max_ms: u64,
386        recv_window_ms: u64,
387        proxy_url: Option<String>,
388    ) -> Result<Self, BybitHttpError> {
389        let environment = if demo {
390            BybitEnvironment::Demo
391        } else if testnet {
392            BybitEnvironment::Testnet
393        } else {
394            BybitEnvironment::Mainnet
395        };
396        let base_url =
397            Some(base_url.unwrap_or_else(|| bybit_http_base_url(environment).to_string()));
398        let (key_var, secret_var) = credential_env_vars(environment);
399        let key = get_or_env_var_opt(api_key, key_var);
400        let secret = get_or_env_var_opt(api_secret, secret_var);
401
402        if let (Some(k), Some(s)) = (key, secret) {
403            Self::with_credentials(
404                k,
405                s,
406                base_url,
407                timeout_secs,
408                max_retries,
409                retry_delay_ms,
410                retry_delay_max_ms,
411                recv_window_ms,
412                proxy_url,
413            )
414        } else {
415            Self::new(
416                base_url,
417                timeout_secs,
418                max_retries,
419                retry_delay_ms,
420                retry_delay_max_ms,
421                recv_window_ms,
422                proxy_url,
423            )
424        }
425    }
426
427    fn default_headers() -> HashMap<String, String> {
428        let mut headers: HashMap<String, String> =
429            create_standard_nautilus_headers().into_iter().collect();
430        headers.insert(
431            "X-Referer".to_string(),
432            BYBIT_NAUTILUS_BROKER_ID.to_string(),
433        );
434        headers
435    }
436
437    fn build_http_client(
438        timeout_secs: u64,
439        proxy_url: Option<String>,
440    ) -> Result<HttpClient, BybitHttpError> {
441        HttpClient::builder()
442            .redirect_policy(HttpRedirectPolicy::Reject)
443            .headers(
444                create_standard_nautilus_headers()
445                    .into_iter()
446                    .collect::<HashMap<_, _>>(),
447            )
448            .header_keys(vec![
449                BYBIT_RATE_LIMIT_HEADER.to_string(),
450                BYBIT_RATE_LIMIT_STATUS_HEADER.to_string(),
451                BYBIT_RATE_LIMIT_RESET_HEADER.to_string(),
452            ])
453            .timeout_secs(timeout_secs)
454            .maybe_proxy_url(proxy_url)
455            .rate_limiters(Vec::new())
456            .build()
457            .map_err(|e| BybitHttpError::NetworkError(format!("Failed to create HTTP client: {e}")))
458    }
459
460    fn refresh_http_session(&self, generation: u64) -> Result<(), BybitHttpError> {
461        let current = self.session_generation.load(Ordering::Acquire);
462        if current == generation {
463            return Ok(());
464        }
465
466        let client = Self::build_http_client(self.timeout_secs, self.proxy_url.clone())?;
467        self.client.store(Arc::new(client));
468        self.session_generation.store(generation, Ordering::Release);
469        Ok(())
470    }
471
472    fn request_rate_limit(
473        endpoint: &str,
474        payload: Option<&str>,
475    ) -> (Option<BybitProductType>, u32) {
476        let category = category_from_payload(payload);
477        let weight = if endpoint.ends_with("-batch") {
478            let order_count = payload
479                .and_then(|payload| serde_json::from_str::<serde_json::Value>(payload).ok())
480                .and_then(|value| value.get("request")?.as_array().map(Vec::len))
481                .unwrap_or(1);
482            category.map_or(1, |category| batch_weight(category, order_count))
483        } else {
484            1
485        };
486        (category, weight)
487    }
488
489    fn observe_rate_limit_headers(
490        &self,
491        endpoint: &str,
492        category: Option<BybitProductType>,
493        headers: &HashMap<String, String>,
494    ) {
495        let Some(limit) = headers
496            .get(BYBIT_RATE_LIMIT_HEADER)
497            .and_then(|value| value.parse::<u32>().ok())
498        else {
499            return;
500        };
501        let Some(remaining) = headers
502            .get(BYBIT_RATE_LIMIT_STATUS_HEADER)
503            .and_then(|value| value.parse::<u32>().ok())
504        else {
505            return;
506        };
507        let reset_timestamp_ms = headers
508            .get(BYBIT_RATE_LIMIT_RESET_HEADER)
509            .and_then(|value| value.parse::<i64>().ok());
510        self.rate_limiter
511            .observe_account(endpoint, category, limit, remaining, reset_timestamp_ms);
512    }
513
514    fn is_rate_limit_403(status: u16, body: &str) -> bool {
515        status == 403 && body.to_ascii_lowercase().contains("access too frequent")
516    }
517
518    fn sign_request(
519        &self,
520        timestamp: &str,
521        params: Option<&str>,
522    ) -> Result<HashMap<String, String>, BybitHttpError> {
523        let credential = self
524            .credential
525            .as_ref()
526            .ok_or(BybitHttpError::MissingCredentials)?;
527
528        let signature = credential.sign_with_payload(timestamp, self.recv_window_ms, params);
529
530        let mut headers = HashMap::new();
531        headers.insert(
532            "X-BAPI-API-KEY".to_string(),
533            credential.api_key().to_string(),
534        );
535        headers.insert("X-BAPI-TIMESTAMP".to_string(), timestamp.to_string());
536        headers.insert("X-BAPI-SIGN".to_string(), signature);
537        headers.insert(
538            "X-BAPI-RECV-WINDOW".to_string(),
539            self.recv_window_ms.to_string(),
540        );
541
542        Ok(headers)
543    }
544
545    async fn send_request<T: DeserializeOwned + BybitResponseCheck, P: Serialize>(
546        &self,
547        method: Method,
548        endpoint: &str,
549        params: Option<&P>,
550        body: Option<Vec<u8>>,
551        authenticate: bool,
552    ) -> Result<T, BybitHttpError> {
553        self.dispatch(method, endpoint, params, body, authenticate, true)
554            .await
555    }
556
557    async fn send_request_once<T: DeserializeOwned + BybitResponseCheck, P: Serialize>(
558        &self,
559        method: Method,
560        endpoint: &str,
561        params: Option<&P>,
562        body: Option<Vec<u8>>,
563        authenticate: bool,
564    ) -> Result<T, BybitHttpError> {
565        self.dispatch(method, endpoint, params, body, authenticate, false)
566            .await
567    }
568
569    async fn dispatch<T: DeserializeOwned + BybitResponseCheck, P: Serialize>(
570        &self,
571        method: Method,
572        endpoint: &str,
573        params: Option<&P>,
574        body: Option<Vec<u8>>,
575        authenticate: bool,
576        retry: bool,
577    ) -> Result<T, BybitHttpError> {
578        let endpoint = endpoint.to_string();
579        let url = format!("{}{endpoint}", self.base_url);
580        let method_clone = method.clone();
581        let body_clone = body.clone();
582
583        // Serialize params before closure to avoid reference lifetime issues
584        let params_str = if method == Method::GET {
585            params
586                .map(serde_urlencoded::to_string)
587                .transpose()
588                .map_err(|e| {
589                    BybitHttpError::JsonError(format!("Failed to serialize params: {e}"))
590                })?
591        } else {
592            None
593        };
594
595        let operation = || {
596            let url = url.clone();
597            let method = method_clone.clone();
598            let body = body_clone.clone();
599            let endpoint = endpoint.clone();
600            let params_str = params_str.clone();
601
602            async move {
603                let full_url = if let Some(ref query) = params_str {
604                    if query.is_empty() {
605                        url
606                    } else {
607                        format!("{url}?{query}")
608                    }
609                } else {
610                    url
611                };
612
613                let sign_payload = if method == Method::GET {
614                    params_str.as_deref()
615                } else {
616                    body.as_ref()
617                        .and_then(|body| std::str::from_utf8(body).ok())
618                };
619                let (category, weight) = Self::request_rate_limit(&endpoint, sign_payload);
620
621                let generation = self.rate_limiter.http_session_generation();
622                self.refresh_http_session(generation)?;
623                self.rate_limiter
624                    .acquire_http(&endpoint, category, weight, authenticate)
625                    .await
626                    .map_err(BybitHttpError::ValidationError)?;
627                let generation = self.rate_limiter.http_session_generation();
628                self.refresh_http_session(generation)?;
629
630                let mut headers = Self::default_headers();
631
632                if endpoint == "/v5/order/create" {
633                    self.start_mm_detection();
634                    let mm_level = self.mm_level();
635                    if mm_level > 0
636                        && body.as_ref().is_some_and(|body| {
637                            serde_json::from_slice::<serde_json::Value>(body).is_ok_and(|value| {
638                                value["timeInForce"].as_str() == Some("PostOnly")
639                            })
640                        })
641                    {
642                        headers.remove("X-Referer");
643                    }
644                }
645
646                if authenticate {
647                    let timestamp = get_atomic_clock_realtime().get_time_ms().to_string();
648                    let auth_headers = self.sign_request(&timestamp, sign_payload)?;
649                    headers.extend(auth_headers);
650                }
651
652                if method == Method::POST || method == Method::PUT {
653                    headers.insert("Content-Type".to_string(), "application/json".to_string());
654                }
655
656                let response = self
657                    .client
658                    .load()
659                    .request(method, full_url, None, Some(headers), body, None, None)
660                    .await?;
661
662                self.observe_rate_limit_headers(&endpoint, category, &response.headers);
663
664                if response.status.as_u16() >= 400 {
665                    let body = String::from_utf8_lossy(&response.body).to_string();
666                    if Self::is_rate_limit_403(response.status.as_u16(), &body) {
667                        let generation = self.rate_limiter.reset_http_sessions();
668                        self.refresh_http_session(generation)?;
669                    }
670                    return Err(BybitHttpError::UnexpectedStatus {
671                        status: response.status.as_u16(),
672                        body,
673                    });
674                }
675
676                // Try to deserialize into the target type
677                match serde_json::from_slice::<T>(&response.body) {
678                    Ok(result) => {
679                        // Check for API-level errors
680                        if result.ret_code() != 0 {
681                            return Err(BybitHttpError::BybitError {
682                                error_code: result.ret_code() as i32,
683                                message: result.ret_msg().to_string(),
684                            });
685                        }
686                        Ok(result)
687                    }
688                    Err(json_err) => {
689                        // Deserialization failed - check if it's a Bybit error response
690                        // (error responses often have result: null which fails typed deserialization)
691                        if let Ok(error_check) =
692                            serde_json::from_slice::<BybitErrorCheck>(&response.body)
693                            && error_check.ret_code != 0
694                        {
695                            return Err(BybitHttpError::BybitError {
696                                error_code: error_check.ret_code as i32,
697                                message: error_check.ret_msg,
698                            });
699                        }
700                        // Not a Bybit error, propagate the JSON parse error
701                        Err(json_err.into())
702                    }
703                }
704            }
705        };
706
707        // Writes are sent once. No POST in this client has a proven idempotency
708        // key that covers a later retry, including a withdraw requestId.
709        let retry = retry && Self::method_may_retry(&method);
710        let should_retry = |e: &BybitHttpError| retry && should_retry_http(e);
711
712        let create_error = |error: RetryError| -> BybitHttpError {
713            match error {
714                RetryError::Canceled => {
715                    BybitHttpError::Canceled("Adapter disconnecting or shutting down".to_string())
716                }
717                error => BybitHttpError::NetworkError(error.to_string()),
718            }
719        };
720
721        let token = self.cancellation_token();
722
723        self.retry_manager
724            .invocation(endpoint.as_str(), operation, should_retry, create_error)
725            .cancellation_token(&token)
726            .execute()
727            .await
728    }
729
730    fn method_may_retry(method: &Method) -> bool {
731        matches!(method, &Method::GET | &Method::HEAD)
732    }
733
734    #[cfg(test)]
735    fn build_path<S: Serialize>(base: &str, params: &S) -> Result<String, BybitHttpError> {
736        let query = serde_urlencoded::to_string(params)
737            .map_err(|e| BybitHttpError::JsonError(e.to_string()))?;
738
739        if query.is_empty() {
740            Ok(base.to_owned())
741        } else {
742            Ok(format!("{base}?{query}"))
743        }
744    }
745
746    /// Fetches the current server time from Bybit.
747    ///
748    /// # Errors
749    ///
750    /// Returns an error if the request fails or the response cannot be parsed.
751    ///
752    /// # References
753    ///
754    /// - <https://bybit-exchange.github.io/docs/v5/market/time>
755    pub async fn get_server_time(&self) -> Result<BybitServerTimeResponse, BybitHttpError> {
756        self.send_request::<_, ()>(Method::GET, "/v5/market/time", None, None, false)
757            .await
758    }
759
760    /// Fetches instrument information from Bybit for a given product category.
761    ///
762    /// # Errors
763    ///
764    /// Returns an error if the request fails or the response cannot be parsed.
765    ///
766    /// # References
767    ///
768    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
769    pub async fn get_instruments<T: DeserializeOwned + BybitResponseCheck>(
770        &self,
771        params: &BybitInstrumentsInfoParams,
772    ) -> Result<T, BybitHttpError> {
773        self.send_request(
774            Method::GET,
775            BYBIT_INSTRUMENTS_INFO,
776            Some(params),
777            None,
778            false,
779        )
780        .await
781    }
782
783    /// Fetches spot instrument information from Bybit.
784    ///
785    /// # Errors
786    ///
787    /// Returns an error if the request fails or the response cannot be parsed.
788    ///
789    /// # References
790    ///
791    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
792    pub async fn get_instruments_spot(
793        &self,
794        params: &BybitInstrumentsInfoParams,
795    ) -> Result<BybitInstrumentSpotResponse, BybitHttpError> {
796        self.get_instruments(params).await
797    }
798
799    /// Fetches linear instrument information from Bybit.
800    ///
801    /// # Errors
802    ///
803    /// Returns an error if the request fails or the response cannot be parsed.
804    ///
805    /// # References
806    ///
807    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
808    pub async fn get_instruments_linear(
809        &self,
810        params: &BybitInstrumentsInfoParams,
811    ) -> Result<BybitInstrumentLinearResponse, BybitHttpError> {
812        self.get_instruments(params).await
813    }
814
815    /// Fetches inverse instrument information from Bybit.
816    ///
817    /// # Errors
818    ///
819    /// Returns an error if the request fails or the response cannot be parsed.
820    ///
821    /// # References
822    ///
823    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
824    pub async fn get_instruments_inverse(
825        &self,
826        params: &BybitInstrumentsInfoParams,
827    ) -> Result<BybitInstrumentInverseResponse, BybitHttpError> {
828        self.get_instruments(params).await
829    }
830
831    /// Fetches option instrument information from Bybit.
832    ///
833    /// # Errors
834    ///
835    /// Returns an error if the request fails or the response cannot be parsed.
836    ///
837    /// # References
838    ///
839    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
840    pub async fn get_instruments_option(
841        &self,
842        params: &BybitInstrumentsInfoParams,
843    ) -> Result<BybitInstrumentOptionResponse, BybitHttpError> {
844        self.get_instruments(params).await
845    }
846
847    /// Fetches kline/candlestick data from Bybit.
848    ///
849    /// # Errors
850    ///
851    /// Returns an error if the request fails or the response cannot be parsed.
852    ///
853    /// # References
854    ///
855    /// - <https://bybit-exchange.github.io/docs/v5/market/kline>
856    pub async fn get_klines(
857        &self,
858        params: &BybitKlinesParams,
859    ) -> Result<BybitKlinesResponse, BybitHttpError> {
860        self.send_request(Method::GET, "/v5/market/kline", Some(params), None, false)
861            .await
862    }
863
864    /// Fetches recent trades from Bybit.
865    ///
866    /// # Errors
867    ///
868    /// Returns an error if the request fails or the response cannot be parsed.
869    ///
870    /// # References
871    ///
872    /// - <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
873    pub async fn get_recent_trades(
874        &self,
875        params: &BybitTradesParams,
876    ) -> Result<BybitTradesResponse, BybitHttpError> {
877        self.send_request(
878            Method::GET,
879            "/v5/market/recent-trade",
880            Some(params),
881            None,
882            false,
883        )
884        .await
885    }
886
887    /// Fetches funding data from Bybit.
888    ///
889    /// # Errors
890    ///
891    /// Returns an error if the request fails or the response cannot be parsed.
892    ///
893    /// # References
894    ///
895    /// - <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
896    pub async fn get_funding_history(
897        &self,
898        params: &BybitFundingParams,
899    ) -> Result<BybitFundingResponse, BybitHttpError> {
900        self.send_request(
901            Method::GET,
902            "/v5/market/funding/history",
903            Some(params),
904            None,
905            false,
906        )
907        .await
908    }
909
910    /// Fetches orderbook from Bybit.
911    ///
912    /// # Errors
913    ///
914    /// Returns an error if the request fails or the response cannot be parsed.
915    ///
916    /// # References
917    ///
918    /// - <https://bybit-exchange.github.io/docs/v5/market/orderbook>
919    pub async fn get_orderbook(
920        &self,
921        params: &BybitOrderbookParams,
922    ) -> Result<BybitOrderbookResponse, BybitHttpError> {
923        self.send_request(
924            Method::GET,
925            "/v5/market/orderbook",
926            Some(params),
927            None,
928            false,
929        )
930        .await
931    }
932
933    /// Fetches open orders (requires authentication).
934    ///
935    /// # Errors
936    ///
937    /// Returns an error if the request fails or the response cannot be parsed.
938    ///
939    /// # Panics
940    ///
941    /// Panics if the parameter builder fails (should never happen with valid inputs).
942    ///
943    /// # References
944    ///
945    /// - <https://bybit-exchange.github.io/docs/v5/order/open-order>
946    #[expect(clippy::too_many_arguments)]
947    pub async fn get_open_orders(
948        &self,
949        category: BybitProductType,
950        symbol: Option<String>,
951        base_coin: Option<String>,
952        settle_coin: Option<String>,
953        order_id: Option<String>,
954        order_link_id: Option<String>,
955        open_only: Option<BybitOpenOnly>,
956        order_filter: Option<BybitOrderFilter>,
957        limit: Option<u32>,
958        cursor: Option<String>,
959    ) -> Result<BybitOpenOrdersResponse, BybitHttpError> {
960        let mut builder = BybitOpenOrdersParamsBuilder::default();
961        builder.category(category);
962
963        if let Some(s) = symbol {
964            builder.symbol(s);
965        }
966
967        if let Some(bc) = base_coin {
968            builder.base_coin(bc);
969        }
970
971        if let Some(sc) = settle_coin {
972            builder.settle_coin(sc);
973        }
974
975        if let Some(oi) = order_id {
976            builder.order_id(oi);
977        }
978
979        if let Some(ol) = order_link_id {
980            builder.order_link_id(ol);
981        }
982
983        if let Some(oo) = open_only {
984            builder.open_only(oo);
985        }
986
987        if let Some(of) = order_filter {
988            builder.order_filter(of);
989        }
990
991        if let Some(l) = limit {
992            builder.limit(l);
993        }
994
995        if let Some(c) = cursor {
996            builder.cursor(c);
997        }
998
999        let params = builder
1000            .build()
1001            .expect("Failed to build BybitOpenOrdersParams");
1002
1003        self.send_request(Method::GET, BYBIT_ORDER_REALTIME, Some(&params), None, true)
1004            .await
1005    }
1006
1007    /// Places a new order (requires authentication).
1008    ///
1009    /// # Errors
1010    ///
1011    /// Returns an error if the request fails or the response cannot be parsed.
1012    ///
1013    /// # References
1014    ///
1015    /// - <https://bybit-exchange.github.io/docs/v5/order/create-order>
1016    pub async fn place_order(
1017        &self,
1018        request: &serde_json::Value,
1019    ) -> Result<BybitPlaceOrderResponse, BybitHttpError> {
1020        let body = serde_json::to_vec(request)?;
1021        self.send_request::<_, ()>(Method::POST, "/v5/order/create", None, Some(body), true)
1022            .await
1023    }
1024
1025    /// Fetches wallet balance (requires authentication).
1026    ///
1027    /// # Errors
1028    ///
1029    /// Returns an error if the request fails or the response cannot be parsed.
1030    ///
1031    /// # References
1032    ///
1033    /// - <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
1034    pub async fn get_wallet_balance(
1035        &self,
1036        params: &BybitWalletBalanceParams,
1037    ) -> Result<BybitWalletBalanceResponse, BybitHttpError> {
1038        self.send_request(
1039            Method::GET,
1040            "/v5/account/wallet-balance",
1041            Some(params),
1042            None,
1043            true,
1044        )
1045        .await
1046    }
1047
1048    /// Fetches account information (requires authentication).
1049    ///
1050    /// # Errors
1051    ///
1052    /// Returns an error if the request fails or the response cannot be parsed.
1053    ///
1054    /// # References
1055    ///
1056    /// - <https://bybit-exchange.github.io/docs/v5/account/account-info>
1057    pub async fn get_account_info(&self) -> Result<BybitAccountInfoResponse, BybitHttpError> {
1058        self.send_request::<_, ()>(Method::GET, "/v5/account/info", None, None, true)
1059            .await
1060    }
1061
1062    /// Fetches account details (requires authentication).
1063    ///
1064    /// # Errors
1065    ///
1066    /// Returns an error if the request fails or the response cannot be parsed.
1067    ///
1068    /// # References
1069    ///
1070    /// - <https://bybit-exchange.github.io/docs/v5/user/apikey-info>
1071    pub async fn get_account_details(&self) -> Result<BybitAccountDetailsResponse, BybitHttpError> {
1072        let response: BybitAccountDetailsResponse = self
1073            .send_request::<_, ()>(Method::GET, "/v5/user/query-api", None, None, true)
1074            .await?;
1075        self.mm_level
1076            .store(response.result.mkt_maker_level, Ordering::Release);
1077        self.mm_detection.store(true, Ordering::Release);
1078        Ok(response)
1079    }
1080
1081    fn start_mm_detection(&self) {
1082        if self
1083            .mm_detection
1084            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
1085            .is_ok()
1086        {
1087            let client = self.clone();
1088            get_runtime().spawn(async move {
1089                if let Err(e) = client.get_account_details().await {
1090                    log::debug!(
1091                        "Failed to detect market-maker level; retaining broker attribution: {e}"
1092                    );
1093                }
1094            });
1095        }
1096    }
1097
1098    fn mm_level(&self) -> u8 {
1099        self.mm_level.load(Ordering::Acquire)
1100    }
1101
1102    /// Modifies a sub-account API key (requires authentication).
1103    ///
1104    /// # Errors
1105    ///
1106    /// Returns an error if the request fails or the response cannot be parsed.
1107    ///
1108    /// # References
1109    ///
1110    /// - <https://bybit-exchange.github.io/docs/v5/user/modify-sub-apikey>
1111    pub async fn update_sub_api_key(
1112        &self,
1113        params: &BybitUpdateSubApiParams,
1114    ) -> Result<BybitUpdateSubApiResponse, BybitHttpError> {
1115        let body = serde_json::to_vec(params)?;
1116        self.send_request::<_, ()>(
1117            Method::POST,
1118            "/v5/user/update-sub-api",
1119            None,
1120            Some(body),
1121            true,
1122        )
1123        .await
1124    }
1125
1126    /// Modifies the master API key that issued the request (requires authentication).
1127    ///
1128    /// # Errors
1129    ///
1130    /// Returns an error if the request fails or the response cannot be parsed.
1131    ///
1132    /// # References
1133    ///
1134    /// - <https://bybit-exchange.github.io/docs/v5/user/modify-master-apikey>
1135    pub async fn update_master_api_key(
1136        &self,
1137        params: &BybitUpdateMasterApiParams,
1138    ) -> Result<BybitUpdateMasterApiResponse, BybitHttpError> {
1139        let body = serde_json::to_vec(params)?;
1140        self.send_request::<_, ()>(Method::POST, "/v5/user/update-api", None, Some(body), true)
1141            .await
1142    }
1143
1144    /// Fetches the sub-account list (up to 1000 rows, non-paginated).
1145    ///
1146    /// # Errors
1147    ///
1148    /// Returns an error if the request fails or the response cannot be parsed.
1149    ///
1150    /// # References
1151    ///
1152    /// - <https://bybit-exchange.github.io/docs/v5/user/subuid-list>
1153    pub async fn get_sub_members(&self) -> Result<BybitSubMembersResponse, BybitHttpError> {
1154        self.send_request::<_, ()>(Method::GET, "/v5/user/query-sub-members", None, None, true)
1155            .await
1156    }
1157
1158    /// Fetches a cursor-paginated sub-account list (`/v5/user/submembers`).
1159    ///
1160    /// # Errors
1161    ///
1162    /// Returns an error if the request fails or the response cannot be parsed.
1163    ///
1164    /// # References
1165    ///
1166    /// - <https://bybit-exchange.github.io/docs/v5/user/page-subuid>
1167    pub async fn get_sub_members_paged(
1168        &self,
1169        params: &BybitSubMembersPageParams,
1170    ) -> Result<BybitSubMembersPagedResponse, BybitHttpError> {
1171        self.send_request(Method::GET, "/v5/user/submembers", Some(params), None, true)
1172            .await
1173    }
1174
1175    /// Fetches fund-custodial sub-accounts (`/v5/user/escrow_sub_members`).
1176    ///
1177    /// # Errors
1178    ///
1179    /// Returns an error if the request fails or the response cannot be parsed.
1180    ///
1181    /// # References
1182    ///
1183    /// - <https://bybit-exchange.github.io/docs/v5/user/fund-subuid-list>
1184    pub async fn get_escrow_sub_members(
1185        &self,
1186        params: &BybitSubMembersPageParams,
1187    ) -> Result<BybitEscrowSubMembersResponse, BybitHttpError> {
1188        self.send_request(
1189            Method::GET,
1190            "/v5/user/escrow_sub_members",
1191            Some(params),
1192            None,
1193            true,
1194        )
1195        .await
1196    }
1197
1198    /// Fetches all API keys belonging to a given sub-account.
1199    ///
1200    /// # Errors
1201    ///
1202    /// Returns an error if the request fails or the response cannot be parsed.
1203    ///
1204    /// # References
1205    ///
1206    /// - <https://bybit-exchange.github.io/docs/v5/user/list-sub-apikeys>
1207    pub async fn get_sub_api_keys(
1208        &self,
1209        params: &BybitSubApiKeysParams,
1210    ) -> Result<BybitSubApiKeysResponse, BybitHttpError> {
1211        self.send_request(
1212            Method::GET,
1213            "/v5/user/sub-apikeys",
1214            Some(params),
1215            None,
1216            true,
1217        )
1218        .await
1219    }
1220
1221    /// Fetches every sub-account page via `/v5/user/submembers` and returns the
1222    /// flattened list. Walks the cursor until Bybit signals end-of-pages.
1223    ///
1224    /// # Errors
1225    ///
1226    /// Returns an error if any page request fails or the response cannot be parsed.
1227    pub async fn fetch_all_sub_members_paged(
1228        &self,
1229        page_size: Option<u32>,
1230    ) -> Result<Vec<BybitSubMember>, BybitHttpError> {
1231        let mut members = Vec::new();
1232        let mut cursor: Option<String> = None;
1233
1234        loop {
1235            let params = BybitSubMembersPageParams {
1236                page_size,
1237                next_cursor: cursor.take(),
1238            };
1239            let mut page = self.get_sub_members_paged(&params).await?;
1240            let next = page.result.continuation_cursor().map(str::to_owned);
1241            members.append(&mut page.result.sub_members);
1242
1243            match next {
1244                Some(c) => cursor = Some(c),
1245                None => break,
1246            }
1247        }
1248
1249        Ok(members)
1250    }
1251
1252    /// Fetches every fund-custodial page via `/v5/user/escrow_sub_members` and
1253    /// returns the flattened list. Walks the cursor until Bybit signals
1254    /// end-of-pages.
1255    ///
1256    /// # Errors
1257    ///
1258    /// Returns an error if any page request fails or the response cannot be parsed.
1259    pub async fn fetch_all_escrow_sub_members(
1260        &self,
1261        page_size: Option<u32>,
1262    ) -> Result<Vec<BybitSubMember>, BybitHttpError> {
1263        let mut members = Vec::new();
1264        let mut cursor: Option<String> = None;
1265
1266        loop {
1267            let params = BybitSubMembersPageParams {
1268                page_size,
1269                next_cursor: cursor.take(),
1270            };
1271            let mut page = self.get_escrow_sub_members(&params).await?;
1272            let next = page.result.continuation_cursor().map(str::to_owned);
1273            members.append(&mut page.result.sub_members);
1274
1275            match next {
1276                Some(c) => cursor = Some(c),
1277                None => break,
1278            }
1279        }
1280
1281        Ok(members)
1282    }
1283
1284    /// Fetches every page of sub-account API keys for `sub_member_id` and
1285    /// returns the flattened list. Walks the cursor until Bybit signals
1286    /// end-of-pages.
1287    ///
1288    /// # Errors
1289    ///
1290    /// Returns an error if any page request fails or the response cannot be parsed.
1291    pub async fn fetch_all_sub_api_keys(
1292        &self,
1293        sub_member_id: impl Into<String>,
1294        limit: Option<u32>,
1295    ) -> Result<Vec<BybitSubApiKeyInfo>, BybitHttpError> {
1296        let sub_member_id = sub_member_id.into();
1297        let mut keys = Vec::new();
1298        let mut cursor: Option<String> = None;
1299
1300        loop {
1301            let params = BybitSubApiKeysParams {
1302                sub_member_id: sub_member_id.clone(),
1303                limit,
1304                cursor: cursor.take(),
1305            };
1306            let mut page = self.get_sub_api_keys(&params).await?;
1307            let next = page.result.continuation_cursor().map(str::to_owned);
1308            keys.append(&mut page.result.keys);
1309
1310            match next {
1311                Some(c) => cursor = Some(c),
1312                None => break,
1313            }
1314        }
1315
1316        Ok(keys)
1317    }
1318
1319    /// Fetches trading fee rates for symbols.
1320    ///
1321    /// # Errors
1322    ///
1323    /// Returns an error if the request fails or the response cannot be parsed.
1324    ///
1325    /// # References
1326    ///
1327    /// - <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
1328    pub async fn get_fee_rate(
1329        &self,
1330        params: &BybitFeeRateParams,
1331    ) -> Result<BybitFeeRateResponse, BybitHttpError> {
1332        self.send_request(
1333            Method::GET,
1334            "/v5/account/fee-rate",
1335            Some(params),
1336            None,
1337            true,
1338        )
1339        .await
1340    }
1341
1342    /// Sets the margin mode for the account.
1343    ///
1344    /// # Errors
1345    ///
1346    /// Returns an error if:
1347    /// - Credentials are missing.
1348    /// - The request fails.
1349    /// - The API returns an error.
1350    ///
1351    /// # Panics
1352    ///
1353    /// Panics if required parameters are not provided (should not happen with current implementation).
1354    ///
1355    /// # References
1356    ///
1357    /// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
1358    pub async fn set_margin_mode(
1359        &self,
1360        margin_mode: BybitMarginMode,
1361    ) -> Result<BybitSetMarginModeResponse, BybitHttpError> {
1362        let params = BybitSetMarginModeParamsBuilder::default()
1363            .set_margin_mode(margin_mode)
1364            .build()
1365            .expect("Failed to build BybitSetMarginModeParams");
1366
1367        let body = serde_json::to_vec(&params)?;
1368        self.send_request::<_, ()>(
1369            Method::POST,
1370            "/v5/account/set-margin-mode",
1371            None,
1372            Some(body),
1373            true,
1374        )
1375        .await
1376    }
1377
1378    /// Sets leverage for a symbol.
1379    ///
1380    /// # Errors
1381    ///
1382    /// Returns an error if:
1383    /// - Credentials are missing.
1384    /// - The request fails.
1385    /// - The API returns an error.
1386    ///
1387    /// # Panics
1388    ///
1389    /// Panics if required parameters are not provided (should not happen with current implementation).
1390    ///
1391    /// # References
1392    ///
1393    /// - <https://bybit-exchange.github.io/docs/v5/position/leverage>
1394    pub async fn set_leverage(
1395        &self,
1396        product_type: BybitProductType,
1397        symbol: &str,
1398        buy_leverage: &str,
1399        sell_leverage: &str,
1400    ) -> Result<BybitSetLeverageResponse, BybitHttpError> {
1401        let params = BybitSetLeverageParamsBuilder::default()
1402            .category(product_type)
1403            .symbol(symbol.to_string())
1404            .buy_leverage(buy_leverage.to_string())
1405            .sell_leverage(sell_leverage.to_string())
1406            .build()
1407            .expect("Failed to build BybitSetLeverageParams");
1408
1409        let body = serde_json::to_vec(&params)?;
1410        self.send_request::<_, ()>(
1411            Method::POST,
1412            "/v5/position/set-leverage",
1413            None,
1414            Some(body),
1415            true,
1416        )
1417        .await
1418    }
1419
1420    /// Switches position mode for a product type.
1421    ///
1422    /// # Errors
1423    ///
1424    /// Returns an error if:
1425    /// - Credentials are missing.
1426    /// - The request fails.
1427    /// - The API returns an error.
1428    ///
1429    /// # Panics
1430    ///
1431    /// Panics if required parameters are not provided (should not happen with current implementation).
1432    ///
1433    /// # References
1434    ///
1435    /// - <https://bybit-exchange.github.io/docs/v5/position/position-mode>
1436    pub async fn switch_mode(
1437        &self,
1438        product_type: BybitProductType,
1439        mode: BybitPositionMode,
1440        symbol: Option<String>,
1441        coin: Option<String>,
1442    ) -> Result<BybitSwitchModeResponse, BybitHttpError> {
1443        let mut builder = BybitSwitchModeParamsBuilder::default();
1444        builder.category(product_type);
1445        builder.mode(mode);
1446
1447        if let Some(s) = symbol {
1448            builder.symbol(s);
1449        }
1450
1451        if let Some(c) = coin {
1452            builder.coin(c);
1453        }
1454
1455        let params = builder
1456            .build()
1457            .expect("Failed to build BybitSwitchModeParams");
1458
1459        let body = serde_json::to_vec(&params)?;
1460        self.send_request::<_, ()>(
1461            Method::POST,
1462            "/v5/position/switch-mode",
1463            None,
1464            Some(body),
1465            true,
1466        )
1467        .await
1468    }
1469
1470    /// Sets trading stop parameters including trailing stops.
1471    ///
1472    /// # Errors
1473    ///
1474    /// Returns an error if:
1475    /// - Credentials are missing.
1476    /// - The request fails.
1477    /// - The API returns an error.
1478    ///
1479    /// # References
1480    ///
1481    /// - <https://bybit-exchange.github.io/docs/v5/position/trading-stop>
1482    pub async fn set_trading_stop(
1483        &self,
1484        params: &BybitSetTradingStopParams,
1485    ) -> Result<BybitSetTradingStopResponse, BybitHttpError> {
1486        let body = serde_json::to_vec(params)?;
1487        self.send_request::<_, ()>(
1488            Method::POST,
1489            "/v5/position/trading-stop",
1490            None,
1491            Some(body),
1492            true,
1493        )
1494        .await
1495    }
1496
1497    /// Manually borrows coins for margin trading.
1498    ///
1499    /// # Errors
1500    ///
1501    /// Returns an error if:
1502    /// - Credentials are missing.
1503    /// - The request fails.
1504    /// - Insufficient collateral for the borrow.
1505    ///
1506    /// # Panics
1507    ///
1508    /// Panics if the parameter builder fails (should never happen with valid inputs).
1509    ///
1510    /// # References
1511    ///
1512    /// - <https://bybit-exchange.github.io/docs/v5/account/borrow>
1513    pub async fn borrow(
1514        &self,
1515        coin: &str,
1516        amount: &str,
1517    ) -> Result<BybitBorrowResponse, BybitHttpError> {
1518        let params = BybitBorrowParamsBuilder::default()
1519            .coin(coin.to_string())
1520            .amount(amount.to_string())
1521            .build()
1522            .expect("Failed to build BybitBorrowParams");
1523
1524        let body = serde_json::to_vec(&params)?;
1525        self.send_request::<_, ()>(Method::POST, "/v5/account/borrow", None, Some(body), true)
1526            .await
1527    }
1528
1529    /// Manually repays borrowed coins without asset conversion.
1530    ///
1531    /// # Errors
1532    ///
1533    /// Returns an error if:
1534    /// - Credentials are missing.
1535    /// - The request fails.
1536    /// - Called during the hourly interest-calculation window (mm:04:00-mm:05:30 UTC each hour).
1537    /// - Insufficient spot balance for repayment.
1538    ///
1539    /// # Panics
1540    ///
1541    /// Panics if the parameter builder fails (should never happen with valid inputs).
1542    ///
1543    /// # References
1544    ///
1545    /// - <https://bybit-exchange.github.io/docs/v5/account/no-convert-repay>
1546    pub async fn no_convert_repay(
1547        &self,
1548        coin: &str,
1549        amount: Option<&str>,
1550    ) -> Result<BybitNoConvertRepayResponse, BybitHttpError> {
1551        let mut builder = BybitNoConvertRepayParamsBuilder::default();
1552        builder.coin(coin.to_string());
1553
1554        if let Some(amt) = amount {
1555            builder.amount(amt.to_string());
1556        }
1557
1558        let params = builder
1559            .build()
1560            .expect("Failed to build BybitNoConvertRepayParams");
1561
1562        if let Ok(params_json) = serde_json::to_string(&params) {
1563            log::debug!("Repay request params: {params_json}");
1564        }
1565
1566        let body = serde_json::to_vec(&params)?;
1567        let result = self
1568            .send_request::<_, ()>(
1569                Method::POST,
1570                "/v5/account/no-convert-repay",
1571                None,
1572                Some(body),
1573                true,
1574            )
1575            .await;
1576
1577        if let Err(ref e) = result
1578            && let Ok(params_json) = serde_json::to_string(&params)
1579        {
1580            log::debug!("Repay request failed with params {params_json}: {e}");
1581        }
1582
1583        result
1584    }
1585
1586    /// Manually repays borrowed coins, converting other assets if required.
1587    ///
1588    /// # Errors
1589    ///
1590    /// Returns an error if:
1591    /// - Credentials are missing.
1592    /// - The request fails.
1593    /// - Called during the hourly interest-calculation window (mm:04:00-mm:05:30 UTC each hour).
1594    /// - Insufficient balance for repayment.
1595    ///
1596    /// # Panics
1597    ///
1598    /// Panics if the parameter builder fails (should never happen with valid inputs).
1599    ///
1600    /// # References
1601    ///
1602    /// - <https://bybit-exchange.github.io/docs/v5/account/repay>
1603    pub async fn repay(
1604        &self,
1605        coin: Option<&str>,
1606        amount: Option<&str>,
1607    ) -> Result<BybitRepayResponse, BybitHttpError> {
1608        let mut builder = BybitRepayParamsBuilder::default();
1609
1610        if let Some(coin) = coin {
1611            builder.coin(coin.to_string());
1612        }
1613
1614        if let Some(amt) = amount {
1615            builder.amount(amt.to_string());
1616        }
1617
1618        let params = builder.build().expect("Failed to build BybitRepayParams");
1619
1620        if let Ok(params_json) = serde_json::to_string(&params) {
1621            log::debug!("Repay request params: {params_json}");
1622        }
1623
1624        let body = serde_json::to_vec(&params)?;
1625        let result = self
1626            .send_request::<_, ()>(Method::POST, "/v5/account/repay", None, Some(body), true)
1627            .await;
1628
1629        if let Err(ref e) = result
1630            && let Ok(params_json) = serde_json::to_string(&params)
1631        {
1632            log::debug!("Repay request failed with params {params_json}: {e}");
1633        }
1634
1635        result
1636    }
1637
1638    /// Withdraws coins from the account.
1639    ///
1640    /// The request is sent once. Bybit's `requestId` is a client identifier, not
1641    /// a proven duplicate-detection window, so it is not a retry key.
1642    ///
1643    /// # Errors
1644    ///
1645    /// Returns an error if:
1646    /// - Credentials are missing.
1647    /// - The request fails.
1648    /// - The API key lacks withdrawal permission or is not a master UID key.
1649    /// - The address is not in the account's withdrawal address book.
1650    ///
1651    /// # References
1652    ///
1653    /// - <https://bybit-exchange.github.io/docs/v5/asset/withdraw>
1654    pub async fn withdraw(
1655        &self,
1656        params: &BybitWithdrawParams,
1657    ) -> Result<BybitWithdrawResponse, BybitHttpError> {
1658        let body = serde_json::to_vec(params)?;
1659        self.send_request_once::<_, ()>(
1660            Method::POST,
1661            "/v5/asset/withdraw/create",
1662            None,
1663            Some(body),
1664            true,
1665        )
1666        .await
1667    }
1668
1669    /// Fetches withdrawal records.
1670    ///
1671    /// # Errors
1672    ///
1673    /// Returns an error if:
1674    /// - Credentials are missing.
1675    /// - The request fails.
1676    /// - The response cannot be parsed.
1677    ///
1678    /// # References
1679    ///
1680    /// - <https://bybit-exchange.github.io/docs/v5/asset/withdraw/withdraw-record>
1681    pub async fn get_withdrawal_records(
1682        &self,
1683        params: &BybitWithdrawalRecordsParams,
1684    ) -> Result<BybitWithdrawalRecordsResponse, BybitHttpError> {
1685        self.send_request(
1686            Method::GET,
1687            "/v5/asset/withdraw/query-record",
1688            Some(params),
1689            None,
1690            true,
1691        )
1692        .await
1693    }
1694
1695    /// Fetches every page of withdrawal records matching `params` and returns
1696    /// the flattened list. Walks the cursor until Bybit signals end-of-pages.
1697    ///
1698    /// # Errors
1699    ///
1700    /// Returns an error if any page request fails or the response cannot be parsed.
1701    pub async fn fetch_all_withdrawal_records(
1702        &self,
1703        params: &BybitWithdrawalRecordsParams,
1704    ) -> Result<Vec<BybitWithdrawalRecord>, BybitHttpError> {
1705        let mut params = params.clone();
1706        let mut records = Vec::new();
1707        let mut cursor_walk = CursorWalk::default();
1708
1709        loop {
1710            let mut page = self.get_withdrawal_records(&params).await?;
1711            records.append(&mut page.result.rows);
1712
1713            let next = cursor_walk
1714                .advance(
1715                    "/v5/asset/withdraw/query-record",
1716                    page.result.next_page_cursor.take(),
1717                )
1718                .map_err(|e| BybitHttpError::ValidationError(e.to_string()))?;
1719
1720            match next {
1721                Some(c) => params.cursor = Some(c),
1722                None => break,
1723            }
1724        }
1725
1726        Ok(records)
1727    }
1728
1729    /// Fetches tickers for market data.
1730    ///
1731    /// # Errors
1732    ///
1733    /// Returns an error if the request fails or the response cannot be parsed.
1734    ///
1735    /// # References
1736    ///
1737    /// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
1738    pub async fn get_tickers<T: DeserializeOwned + BybitResponseCheck>(
1739        &self,
1740        params: &BybitTickersParams,
1741    ) -> Result<T, BybitHttpError> {
1742        self.send_request(Method::GET, "/v5/market/tickers", Some(params), None, false)
1743            .await
1744    }
1745
1746    /// Fetches trade execution history (requires authentication).
1747    ///
1748    /// # Errors
1749    ///
1750    /// Returns an error if the request fails or the response cannot be parsed.
1751    ///
1752    /// # References
1753    ///
1754    /// - <https://bybit-exchange.github.io/docs/v5/order/execution>
1755    pub async fn get_trade_history(
1756        &self,
1757        params: &BybitTradeHistoryParams,
1758    ) -> Result<BybitTradeHistoryResponse, BybitHttpError> {
1759        self.send_request(Method::GET, BYBIT_EXECUTION_LIST, Some(params), None, true)
1760            .await
1761    }
1762
1763    /// Fetches position information (requires authentication).
1764    ///
1765    /// # Errors
1766    ///
1767    /// Returns an error if:
1768    /// - Credentials are missing.
1769    /// - The request fails.
1770    /// - The API returns an error.
1771    ///
1772    /// # References
1773    ///
1774    /// - <https://bybit-exchange.github.io/docs/v5/position>
1775    pub async fn get_positions(
1776        &self,
1777        params: &BybitPositionListParams,
1778    ) -> Result<BybitPositionListResponse, BybitHttpError> {
1779        self.send_request(Method::GET, BYBIT_POSITION_LIST, Some(params), None, true)
1780            .await
1781    }
1782
1783    /// Returns the base URL used for requests.
1784    #[must_use]
1785    pub fn base_url(&self) -> &str {
1786        &self.base_url
1787    }
1788
1789    /// Returns the configured receive window in milliseconds.
1790    #[must_use]
1791    pub fn recv_window_ms(&self) -> u64 {
1792        self.recv_window_ms
1793    }
1794
1795    /// Returns the API credential if configured.
1796    #[must_use]
1797    pub fn credential(&self) -> Option<&Credential> {
1798        self.credential.as_ref()
1799    }
1800}
1801
1802/// Provides a HTTP client for connecting to the [Bybit](https://bybit.com) REST API.
1803#[cfg_attr(
1804    feature = "python",
1805    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
1806)]
1807#[cfg_attr(
1808    feature = "python",
1809    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
1810)]
1811/// High-level HTTP client that wraps the raw client and provides Nautilus domain types.
1812///
1813/// This client maintains an instrument cache and uses it to parse venue responses
1814/// into Nautilus domain objects.
1815pub struct BybitHttpClient {
1816    pub(crate) inner: Arc<BybitRawHttpClient>,
1817    pub(crate) instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
1818    clock: &'static AtomicTime,
1819    cache_initialized: Arc<AtomicBool>,
1820    use_spot_position_reports: Arc<AtomicBool>,
1821}
1822
1823impl Clone for BybitHttpClient {
1824    fn clone(&self) -> Self {
1825        Self {
1826            inner: self.inner.clone(),
1827            instruments_cache: self.instruments_cache.clone(),
1828            cache_initialized: self.cache_initialized.clone(),
1829            use_spot_position_reports: self.use_spot_position_reports.clone(),
1830            clock: self.clock,
1831        }
1832    }
1833}
1834
1835impl Default for BybitHttpClient {
1836    fn default() -> Self {
1837        Self::new(None, 60, 3, 1000, 10_000, DEFAULT_RECV_WINDOW_MS, None)
1838            .expect("Failed to create default BybitHttpClient")
1839    }
1840}
1841
1842impl Debug for BybitHttpClient {
1843    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1844        f.debug_struct(stringify!(BybitHttpClient))
1845            .field("inner", &self.inner)
1846            .finish()
1847    }
1848}
1849
1850impl BybitHttpClient {
1851    pub(crate) fn start_mm_detection(&self) {
1852        self.inner.start_mm_detection();
1853    }
1854
1855    pub(crate) fn mm_level(&self) -> u8 {
1856        self.inner.mm_level()
1857    }
1858
1859    /// Creates a new [`BybitHttpClient`] using the default Bybit HTTP URL.
1860    ///
1861    /// # Errors
1862    ///
1863    /// Returns an error if the retry manager cannot be created.
1864    pub fn new(
1865        base_url: Option<String>,
1866        timeout_secs: u64,
1867        max_retries: u32,
1868        retry_delay_ms: u64,
1869        retry_delay_max_ms: u64,
1870        recv_window_ms: u64,
1871        proxy_url: Option<String>,
1872    ) -> Result<Self, BybitHttpError> {
1873        Ok(Self {
1874            inner: Arc::new(BybitRawHttpClient::new(
1875                base_url,
1876                timeout_secs,
1877                max_retries,
1878                retry_delay_ms,
1879                retry_delay_max_ms,
1880                recv_window_ms,
1881                proxy_url,
1882            )?),
1883            instruments_cache: Arc::new(AtomicMap::new()),
1884            cache_initialized: Arc::new(AtomicBool::new(false)),
1885            use_spot_position_reports: Arc::new(AtomicBool::new(false)),
1886            clock: get_atomic_clock_realtime(),
1887        })
1888    }
1889
1890    /// Creates a new [`BybitHttpClient`] configured with credentials.
1891    ///
1892    /// # Errors
1893    ///
1894    /// Returns an error if the retry manager cannot be created.
1895    #[expect(clippy::too_many_arguments)]
1896    pub fn with_credentials(
1897        api_key: String,
1898        api_secret: String,
1899        base_url: Option<String>,
1900        timeout_secs: u64,
1901        max_retries: u32,
1902        retry_delay_ms: u64,
1903        retry_delay_max_ms: u64,
1904        recv_window_ms: u64,
1905        proxy_url: Option<String>,
1906    ) -> Result<Self, BybitHttpError> {
1907        Ok(Self {
1908            inner: Arc::new(BybitRawHttpClient::with_credentials(
1909                api_key,
1910                api_secret,
1911                base_url,
1912                timeout_secs,
1913                max_retries,
1914                retry_delay_ms,
1915                retry_delay_max_ms,
1916                recv_window_ms,
1917                proxy_url,
1918            )?),
1919            instruments_cache: Arc::new(AtomicMap::new()),
1920            cache_initialized: Arc::new(AtomicBool::new(false)),
1921            use_spot_position_reports: Arc::new(AtomicBool::new(false)),
1922            clock: get_atomic_clock_realtime(),
1923        })
1924    }
1925
1926    /// Creates a new [`BybitHttpClient`] with optional credentials resolved from environment variables.
1927    ///
1928    /// Credentials are resolved in the following order:
1929    /// 1. Use provided `api_key`/`api_secret` if `Some`
1930    /// 2. Fall back to environment variables based on environment:
1931    ///    - Demo: `BYBIT_DEMO_API_KEY`, `BYBIT_DEMO_API_SECRET`
1932    ///    - Testnet: `BYBIT_TESTNET_API_KEY`, `BYBIT_TESTNET_API_SECRET`
1933    ///    - Mainnet: `BYBIT_API_KEY`, `BYBIT_API_SECRET`
1934    ///
1935    /// # Errors
1936    ///
1937    /// Returns an error if the retry manager cannot be created.
1938    #[expect(clippy::too_many_arguments)]
1939    pub fn new_with_env(
1940        api_key: Option<String>,
1941        api_secret: Option<String>,
1942        base_url: Option<String>,
1943        demo: bool,
1944        testnet: bool,
1945        timeout_secs: u64,
1946        max_retries: u32,
1947        retry_delay_ms: u64,
1948        retry_delay_max_ms: u64,
1949        recv_window_ms: u64,
1950        proxy_url: Option<String>,
1951    ) -> Result<Self, BybitHttpError> {
1952        Ok(Self {
1953            inner: Arc::new(BybitRawHttpClient::new_with_env(
1954                api_key,
1955                api_secret,
1956                base_url,
1957                demo,
1958                testnet,
1959                timeout_secs,
1960                max_retries,
1961                retry_delay_ms,
1962                retry_delay_max_ms,
1963                recv_window_ms,
1964                proxy_url,
1965            )?),
1966            instruments_cache: Arc::new(AtomicMap::new()),
1967            cache_initialized: Arc::new(AtomicBool::new(false)),
1968            use_spot_position_reports: Arc::new(AtomicBool::new(false)),
1969            clock: get_atomic_clock_realtime(),
1970        })
1971    }
1972
1973    #[must_use]
1974    pub fn base_url(&self) -> &str {
1975        self.inner.base_url()
1976    }
1977
1978    #[must_use]
1979    pub fn recv_window_ms(&self) -> u64 {
1980        self.inner.recv_window_ms()
1981    }
1982
1983    #[must_use]
1984    pub fn credential(&self) -> Option<&Credential> {
1985        self.inner.credential()
1986    }
1987
1988    pub fn set_use_spot_position_reports(&self, use_spot_position_reports: bool) {
1989        self.use_spot_position_reports
1990            .store(use_spot_position_reports, Ordering::Relaxed);
1991    }
1992
1993    pub fn cancel_all_requests(&self) {
1994        self.inner.cancel_all_requests();
1995    }
1996
1997    pub fn reset_cancellation_token(&self) {
1998        self.inner.reset_cancellation_token();
1999    }
2000
2001    pub fn cancellation_token(&self) -> CancellationToken {
2002        self.inner.cancellation_token()
2003    }
2004
2005    /// Any existing instrument with the same symbol will be replaced.
2006    pub fn cache_instrument(&self, instrument: InstrumentAny) {
2007        self.instruments_cache
2008            .insert(instrument.symbol().inner(), instrument);
2009        self.cache_initialized.store(true, Ordering::Release);
2010    }
2011
2012    /// Any existing instruments with the same symbols will be replaced.
2013    pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
2014        self.instruments_cache.rcu(|m| {
2015            for instrument in instruments {
2016                m.insert(instrument.symbol().inner(), instrument.clone());
2017            }
2018        });
2019        self.cache_initialized.store(true, Ordering::Release);
2020    }
2021
2022    pub fn get_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
2023        self.instruments_cache.get_cloned(symbol)
2024    }
2025
2026    fn instrument_from_cache(&self, symbol: &Symbol) -> anyhow::Result<InstrumentAny> {
2027        self.get_instrument(&symbol.inner()).ok_or_else(|| {
2028            anyhow::anyhow!(
2029                "Instrument {symbol} not found in cache, ensure instruments loaded first"
2030            )
2031        })
2032    }
2033
2034    #[must_use]
2035    fn generate_ts_init(&self) -> UnixNanos {
2036        self.clock.get_time_ns()
2037    }
2038
2039    /// Fetches the current server time from Bybit.
2040    ///
2041    /// # Errors
2042    ///
2043    /// Returns an error if:
2044    /// - The request fails.
2045    /// - The response cannot be parsed.
2046    ///
2047    /// # References
2048    ///
2049    /// - <https://bybit-exchange.github.io/docs/v5/market/time>
2050    pub async fn get_server_time(&self) -> Result<BybitServerTimeResponse, BybitHttpError> {
2051        self.inner.get_server_time().await
2052    }
2053
2054    /// Fetches instrument information from Bybit for a given product category.
2055    ///
2056    /// # Errors
2057    ///
2058    /// Returns an error if:
2059    /// - The request fails.
2060    /// - The response cannot be parsed.
2061    ///
2062    /// # References
2063    ///
2064    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
2065    pub async fn get_instruments<T: DeserializeOwned + BybitResponseCheck>(
2066        &self,
2067        params: &BybitInstrumentsInfoParams,
2068    ) -> Result<T, BybitHttpError> {
2069        self.inner.get_instruments(params).await
2070    }
2071
2072    /// Fetches spot instrument information from Bybit.
2073    ///
2074    /// # Errors
2075    ///
2076    /// Returns an error if:
2077    /// - The request fails.
2078    /// - The response cannot be parsed.
2079    ///
2080    /// # References
2081    ///
2082    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
2083    pub async fn get_instruments_spot(
2084        &self,
2085        params: &BybitInstrumentsInfoParams,
2086    ) -> Result<BybitInstrumentSpotResponse, BybitHttpError> {
2087        self.inner.get_instruments_spot(params).await
2088    }
2089
2090    /// Fetches linear instrument information from Bybit.
2091    ///
2092    /// # Errors
2093    ///
2094    /// Returns an error if:
2095    /// - The request fails.
2096    /// - The response cannot be parsed.
2097    ///
2098    /// # References
2099    ///
2100    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
2101    pub async fn get_instruments_linear(
2102        &self,
2103        params: &BybitInstrumentsInfoParams,
2104    ) -> Result<BybitInstrumentLinearResponse, BybitHttpError> {
2105        self.inner.get_instruments_linear(params).await
2106    }
2107
2108    /// Fetches inverse instrument information from Bybit.
2109    ///
2110    /// # Errors
2111    ///
2112    /// Returns an error if:
2113    /// - The request fails.
2114    /// - The response cannot be parsed.
2115    ///
2116    /// # References
2117    ///
2118    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
2119    pub async fn get_instruments_inverse(
2120        &self,
2121        params: &BybitInstrumentsInfoParams,
2122    ) -> Result<BybitInstrumentInverseResponse, BybitHttpError> {
2123        self.inner.get_instruments_inverse(params).await
2124    }
2125
2126    /// Fetches option instrument information from Bybit.
2127    ///
2128    /// # Errors
2129    ///
2130    /// Returns an error if:
2131    /// - The request fails.
2132    /// - The response cannot be parsed.
2133    ///
2134    /// # References
2135    ///
2136    /// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
2137    pub async fn get_instruments_option(
2138        &self,
2139        params: &BybitInstrumentsInfoParams,
2140    ) -> Result<BybitInstrumentOptionResponse, BybitHttpError> {
2141        self.inner.get_instruments_option(params).await
2142    }
2143
2144    /// Fetches kline/candlestick data from Bybit.
2145    ///
2146    /// # Errors
2147    ///
2148    /// Returns an error if:
2149    /// - The request fails.
2150    /// - The response cannot be parsed.
2151    ///
2152    /// # References
2153    ///
2154    /// - <https://bybit-exchange.github.io/docs/v5/market/kline>
2155    pub async fn get_klines(
2156        &self,
2157        params: &BybitKlinesParams,
2158    ) -> Result<BybitKlinesResponse, BybitHttpError> {
2159        self.inner.get_klines(params).await
2160    }
2161
2162    /// Fetches recent trades from Bybit.
2163    ///
2164    /// # Errors
2165    ///
2166    /// Returns an error if:
2167    /// - The request fails.
2168    /// - The response cannot be parsed.
2169    ///
2170    /// # References
2171    ///
2172    /// - <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
2173    pub async fn get_recent_trades(
2174        &self,
2175        params: &BybitTradesParams,
2176    ) -> Result<BybitTradesResponse, BybitHttpError> {
2177        self.inner.get_recent_trades(params).await
2178    }
2179
2180    /// Fetches open orders (requires authentication).
2181    ///
2182    /// # Errors
2183    ///
2184    /// Returns an error if:
2185    /// - The request fails.
2186    /// - The response cannot be parsed.
2187    ///
2188    /// # References
2189    ///
2190    /// - <https://bybit-exchange.github.io/docs/v5/order/open-order>
2191    #[expect(clippy::too_many_arguments)]
2192    pub async fn get_open_orders(
2193        &self,
2194        category: BybitProductType,
2195        symbol: Option<String>,
2196        base_coin: Option<String>,
2197        settle_coin: Option<String>,
2198        order_id: Option<String>,
2199        order_link_id: Option<String>,
2200        open_only: Option<BybitOpenOnly>,
2201        order_filter: Option<BybitOrderFilter>,
2202        limit: Option<u32>,
2203        cursor: Option<String>,
2204    ) -> Result<BybitOpenOrdersResponse, BybitHttpError> {
2205        self.inner
2206            .get_open_orders(
2207                category,
2208                symbol,
2209                base_coin,
2210                settle_coin,
2211                order_id,
2212                order_link_id,
2213                open_only,
2214                order_filter,
2215                limit,
2216                cursor,
2217            )
2218            .await
2219    }
2220
2221    /// Places a new order (requires authentication).
2222    ///
2223    /// # Errors
2224    ///
2225    /// Returns an error if:
2226    /// - The request fails.
2227    /// - The response cannot be parsed.
2228    ///
2229    /// # References
2230    ///
2231    /// - <https://bybit-exchange.github.io/docs/v5/order/create-order>
2232    pub async fn place_order(
2233        &self,
2234        request: &serde_json::Value,
2235    ) -> Result<BybitPlaceOrderResponse, BybitHttpError> {
2236        self.inner.place_order(request).await
2237    }
2238
2239    /// Fetches wallet balance (requires authentication).
2240    ///
2241    /// # Errors
2242    ///
2243    /// Returns an error if:
2244    /// - The request fails.
2245    /// - The response cannot be parsed.
2246    ///
2247    /// # References
2248    ///
2249    /// - <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
2250    pub async fn get_wallet_balance(
2251        &self,
2252        params: &BybitWalletBalanceParams,
2253    ) -> Result<BybitWalletBalanceResponse, BybitHttpError> {
2254        self.inner.get_wallet_balance(params).await
2255    }
2256
2257    /// Fetches account information (requires authentication).
2258    ///
2259    /// # Errors
2260    ///
2261    /// Returns an error if:
2262    /// - The request fails.
2263    /// - The response cannot be parsed.
2264    ///
2265    /// # References
2266    ///
2267    /// - <https://bybit-exchange.github.io/docs/v5/account/account-info>
2268    pub async fn get_account_info(&self) -> Result<BybitAccountInfoResponse, BybitHttpError> {
2269        self.inner.get_account_info().await
2270    }
2271
2272    /// Fetches API key information including account details (requires authentication).
2273    ///
2274    /// # Errors
2275    ///
2276    /// Returns an error if:
2277    /// - The request fails.
2278    /// - The response cannot be parsed.
2279    ///
2280    /// # References
2281    ///
2282    /// - <https://bybit-exchange.github.io/docs/v5/user/apikey-info>
2283    pub async fn get_account_details(&self) -> Result<BybitAccountDetailsResponse, BybitHttpError> {
2284        self.inner.get_account_details().await
2285    }
2286
2287    /// Modifies a sub-account API key (requires authentication).
2288    ///
2289    /// # Errors
2290    ///
2291    /// Returns an error if:
2292    /// - The request fails.
2293    /// - The response cannot be parsed.
2294    ///
2295    /// # References
2296    ///
2297    /// - <https://bybit-exchange.github.io/docs/v5/user/modify-sub-apikey>
2298    pub async fn update_sub_api_key(
2299        &self,
2300        params: &BybitUpdateSubApiParams,
2301    ) -> Result<BybitUpdateSubApiResponse, BybitHttpError> {
2302        self.inner.update_sub_api_key(params).await
2303    }
2304
2305    /// Modifies the master API key that issued the request (requires authentication).
2306    ///
2307    /// # Errors
2308    ///
2309    /// Returns an error if:
2310    /// - The request fails.
2311    /// - The response cannot be parsed.
2312    ///
2313    /// # References
2314    ///
2315    /// - <https://bybit-exchange.github.io/docs/v5/user/modify-master-apikey>
2316    pub async fn update_master_api_key(
2317        &self,
2318        params: &BybitUpdateMasterApiParams,
2319    ) -> Result<BybitUpdateMasterApiResponse, BybitHttpError> {
2320        self.inner.update_master_api_key(params).await
2321    }
2322
2323    /// Fetches the sub-account list (up to 1000 rows, non-paginated).
2324    ///
2325    /// # Errors
2326    ///
2327    /// Returns an error if:
2328    /// - The request fails.
2329    /// - The response cannot be parsed.
2330    ///
2331    /// # References
2332    ///
2333    /// - <https://bybit-exchange.github.io/docs/v5/user/subuid-list>
2334    pub async fn get_sub_members(&self) -> Result<BybitSubMembersResponse, BybitHttpError> {
2335        self.inner.get_sub_members().await
2336    }
2337
2338    /// Fetches a cursor-paginated sub-account list.
2339    ///
2340    /// # Errors
2341    ///
2342    /// Returns an error if:
2343    /// - The request fails.
2344    /// - The response cannot be parsed.
2345    ///
2346    /// # References
2347    ///
2348    /// - <https://bybit-exchange.github.io/docs/v5/user/page-subuid>
2349    pub async fn get_sub_members_paged(
2350        &self,
2351        params: &BybitSubMembersPageParams,
2352    ) -> Result<BybitSubMembersPagedResponse, BybitHttpError> {
2353        self.inner.get_sub_members_paged(params).await
2354    }
2355
2356    /// Fetches fund-custodial sub-accounts.
2357    ///
2358    /// # Errors
2359    ///
2360    /// Returns an error if:
2361    /// - The request fails.
2362    /// - The response cannot be parsed.
2363    ///
2364    /// # References
2365    ///
2366    /// - <https://bybit-exchange.github.io/docs/v5/user/fund-subuid-list>
2367    pub async fn get_escrow_sub_members(
2368        &self,
2369        params: &BybitSubMembersPageParams,
2370    ) -> Result<BybitEscrowSubMembersResponse, BybitHttpError> {
2371        self.inner.get_escrow_sub_members(params).await
2372    }
2373
2374    /// Fetches all API keys belonging to a given sub-account.
2375    ///
2376    /// # Errors
2377    ///
2378    /// Returns an error if:
2379    /// - The request fails.
2380    /// - The response cannot be parsed.
2381    ///
2382    /// # References
2383    ///
2384    /// - <https://bybit-exchange.github.io/docs/v5/user/list-sub-apikeys>
2385    pub async fn get_sub_api_keys(
2386        &self,
2387        params: &BybitSubApiKeysParams,
2388    ) -> Result<BybitSubApiKeysResponse, BybitHttpError> {
2389        self.inner.get_sub_api_keys(params).await
2390    }
2391
2392    /// Fetches position information (requires authentication).
2393    ///
2394    /// # Errors
2395    ///
2396    /// Returns an error if:
2397    /// - Credentials are missing.
2398    /// - The request fails.
2399    /// - The API returns an error.
2400    ///
2401    /// # References
2402    ///
2403    /// - <https://bybit-exchange.github.io/docs/v5/position>
2404    pub async fn get_positions(
2405        &self,
2406        params: &BybitPositionListParams,
2407    ) -> Result<BybitPositionListResponse, BybitHttpError> {
2408        self.inner.get_positions(params).await
2409    }
2410
2411    /// Fetches fee rate (requires authentication).
2412    ///
2413    /// # Errors
2414    ///
2415    /// Returns an error if:
2416    /// - Credentials are missing.
2417    /// - The request fails.
2418    /// - The API returns an error.
2419    ///
2420    /// # References
2421    ///
2422    /// - <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
2423    pub async fn get_fee_rate(
2424        &self,
2425        params: &BybitFeeRateParams,
2426    ) -> Result<BybitFeeRateResponse, BybitHttpError> {
2427        self.inner.get_fee_rate(params).await
2428    }
2429
2430    /// Sets margin mode (requires authentication).
2431    ///
2432    /// # Errors
2433    ///
2434    /// Returns an error if:
2435    /// - Credentials are missing.
2436    /// - The request fails.
2437    /// - The API returns an error.
2438    ///
2439    /// # References
2440    ///
2441    /// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
2442    pub async fn set_margin_mode(
2443        &self,
2444        margin_mode: BybitMarginMode,
2445    ) -> Result<BybitSetMarginModeResponse, BybitHttpError> {
2446        self.inner.set_margin_mode(margin_mode).await
2447    }
2448
2449    /// Sets leverage for a symbol (requires authentication).
2450    ///
2451    /// # Errors
2452    ///
2453    /// Returns an error if:
2454    /// - Credentials are missing.
2455    /// - The request fails.
2456    /// - The API returns an error.
2457    ///
2458    /// # References
2459    ///
2460    /// - <https://bybit-exchange.github.io/docs/v5/position/leverage>
2461    pub async fn set_leverage(
2462        &self,
2463        product_type: BybitProductType,
2464        symbol: &str,
2465        buy_leverage: &str,
2466        sell_leverage: &str,
2467    ) -> Result<BybitSetLeverageResponse, BybitHttpError> {
2468        self.inner
2469            .set_leverage(product_type, symbol, buy_leverage, sell_leverage)
2470            .await
2471    }
2472
2473    /// Switches position mode (requires authentication).
2474    ///
2475    /// # Errors
2476    ///
2477    /// Returns an error if:
2478    /// - Credentials are missing.
2479    /// - The request fails.
2480    /// - The API returns an error.
2481    ///
2482    /// # References
2483    ///
2484    /// - <https://bybit-exchange.github.io/docs/v5/position/position-mode>
2485    pub async fn switch_mode(
2486        &self,
2487        product_type: BybitProductType,
2488        mode: BybitPositionMode,
2489        symbol: Option<String>,
2490        coin: Option<String>,
2491    ) -> Result<BybitSwitchModeResponse, BybitHttpError> {
2492        self.inner
2493            .switch_mode(product_type, mode, symbol, coin)
2494            .await
2495    }
2496
2497    /// Sets trading stop parameters including trailing stops (requires authentication).
2498    ///
2499    /// # Errors
2500    ///
2501    /// Returns an error if:
2502    /// - Credentials are missing.
2503    /// - The request fails.
2504    /// - The API returns an error.
2505    ///
2506    /// # References
2507    ///
2508    /// - <https://bybit-exchange.github.io/docs/v5/position/trading-stop>
2509    pub async fn set_trading_stop(
2510        &self,
2511        params: &BybitSetTradingStopParams,
2512    ) -> Result<BybitSetTradingStopResponse, BybitHttpError> {
2513        self.inner.set_trading_stop(params).await
2514    }
2515
2516    /// Get the outstanding spot borrow amount for a specific coin.
2517    ///
2518    /// Returns zero if no borrow exists.
2519    ///
2520    /// # Parameters
2521    ///
2522    /// - `coin`: The coin to check (e.g., "BTC", "ETH")
2523    ///
2524    /// # Errors
2525    ///
2526    /// Returns an error if:
2527    /// - Credentials are missing.
2528    /// - The request fails.
2529    /// - The coin is not found in the wallet.
2530    pub async fn get_spot_borrow_amount(&self, coin: &str) -> anyhow::Result<Decimal> {
2531        let params = BybitWalletBalanceParams {
2532            account_type: BybitAccountType::Unified,
2533            coin: Some(coin.to_string()),
2534        };
2535
2536        let response = self.inner.get_wallet_balance(&params).await?;
2537
2538        let borrow_amount = response
2539            .result
2540            .list
2541            .first()
2542            .and_then(|wallet| wallet.coin.iter().find(|c| c.coin == coin))
2543            .map_or(Decimal::ZERO, |balance| balance.spot_borrow);
2544
2545        Ok(borrow_amount)
2546    }
2547
2548    /// Borrows coins for spot margin trading.
2549    ///
2550    /// This should be called before opening short spot positions.
2551    ///
2552    /// # Parameters
2553    ///
2554    /// - `coin`: The coin to repay (e.g., "BTC", "ETH")
2555    /// - `amount`: Optional amount to borrow. If None, repays all outstanding borrows.
2556    ///
2557    /// # Errors
2558    ///
2559    /// Returns an error if:
2560    /// - Credentials are missing.
2561    /// - The request fails.
2562    /// - Insufficient collateral for the borrow.
2563    pub async fn borrow_spot(
2564        &self,
2565        coin: &str,
2566        amount: Quantity,
2567    ) -> anyhow::Result<BybitBorrowResponse> {
2568        let amount_str = amount.to_string();
2569        self.inner
2570            .borrow(coin, &amount_str)
2571            .await
2572            .map_err(|e| anyhow::anyhow!("Failed to borrow {amount} {coin}: {e}"))
2573    }
2574
2575    /// Repays spot borrows for a specific coin.
2576    ///
2577    /// This should be called after closing short spot positions to avoid accruing interest.
2578    ///
2579    /// # Parameters
2580    ///
2581    /// - `coin`: The coin to repay (e.g., "BTC", "ETH")
2582    /// - `amount`: Optional amount to repay. If None, repays all outstanding borrows.
2583    ///
2584    /// # Errors
2585    ///
2586    /// Returns an error if:
2587    /// - Credentials are missing.
2588    /// - The request fails.
2589    /// - Called during the hourly interest-calculation window (mm:04:00-mm:05:30 UTC each hour).
2590    /// - Insufficient spot balance for repayment.
2591    pub async fn repay_spot_borrow(
2592        &self,
2593        coin: &str,
2594        amount: Option<Quantity>,
2595    ) -> anyhow::Result<BybitNoConvertRepayResponse> {
2596        let amount_str = amount.as_ref().map(|q| q.to_string());
2597        let response = self
2598            .inner
2599            .no_convert_repay(coin, amount_str.as_deref())
2600            .await
2601            .map_err(|e| anyhow::anyhow!("Failed to repay spot borrow for {coin}: {e}"))?;
2602        Self::ensure_repay_accepted(coin, response.result.result_status)?;
2603        Ok(response)
2604    }
2605
2606    /// Repays spot borrows for a specific coin, converting other assets if required.
2607    ///
2608    /// Unlike [`Self::repay_spot_borrow`], this uses the venue's manual repay endpoint,
2609    /// which may draw on other holdings when the debt coin's spot balance is insufficient.
2610    ///
2611    /// # Parameters
2612    ///
2613    /// - `coin`: The coin to repay (e.g., "BTC", "ETH")
2614    /// - `amount`: Optional amount to repay. If None, repays all outstanding borrows.
2615    ///
2616    /// # Errors
2617    ///
2618    /// Returns an error if:
2619    /// - Credentials are missing.
2620    /// - The request fails.
2621    /// - Called during the hourly interest-calculation window (mm:04:00-mm:05:30 UTC each hour).
2622    /// - Insufficient balance for repayment.
2623    pub async fn repay_spot_borrow_with_conversion(
2624        &self,
2625        coin: &str,
2626        amount: Option<Quantity>,
2627    ) -> anyhow::Result<BybitRepayResponse> {
2628        let amount_str = amount.as_ref().map(|q| q.to_string());
2629        let response = self
2630            .inner
2631            .repay(Some(coin), amount_str.as_deref())
2632            .await
2633            .map_err(|e| {
2634                anyhow::anyhow!("Failed to repay spot borrow (with conversion) for {coin}: {e}")
2635            })?;
2636        Self::ensure_repay_accepted(coin, response.result.result_status)?;
2637        Ok(response)
2638    }
2639
2640    fn ensure_repay_accepted(coin: &str, status: BybitRepayStatus) -> anyhow::Result<()> {
2641        anyhow::ensure!(
2642            status != BybitRepayStatus::Failed,
2643            "Bybit repay for {coin} returned result status {status}"
2644        );
2645        Ok(())
2646    }
2647
2648    /// Generate SPOT position reports from wallet balances.
2649    ///
2650    /// # Errors
2651    ///
2652    /// Returns an error if:
2653    /// - The wallet balance request fails.
2654    /// - Parsing fails.
2655    async fn generate_spot_position_reports_from_wallet(
2656        &self,
2657        account_id: AccountId,
2658        instrument_id: InstrumentId,
2659    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2660        let params = BybitWalletBalanceParams {
2661            account_type: BybitAccountType::Unified,
2662            coin: None,
2663        };
2664
2665        let response = self.inner.get_wallet_balance(&params).await?;
2666        let ts_init = self.generate_ts_init();
2667
2668        let mut wallet_by_coin: HashMap<Ustr, Decimal> = HashMap::new();
2669
2670        for wallet in &response.result.list {
2671            for coin_balance in &wallet.coin {
2672                let balance = coin_balance.wallet_balance - coin_balance.spot_borrow;
2673                *wallet_by_coin
2674                    .entry(coin_balance.coin)
2675                    .or_insert(Decimal::ZERO) += balance;
2676            }
2677        }
2678
2679        let mut reports = Vec::new();
2680
2681        if let Some(instrument) = self
2682            .instruments_cache
2683            .get_cloned(&instrument_id.symbol.inner())
2684        {
2685            let base_currency = instrument
2686                .base_currency()
2687                .expect("SPOT instrument should have base currency");
2688            let coin = base_currency.code;
2689            let wallet_balance = wallet_by_coin.get(&coin).copied().unwrap_or(Decimal::ZERO);
2690
2691            let side = if wallet_balance > Decimal::ZERO {
2692                PositionSide::Long
2693            } else if wallet_balance < Decimal::ZERO {
2694                PositionSide::Short
2695            } else {
2696                PositionSide::Flat
2697            };
2698
2699            let abs_balance = wallet_balance.abs();
2700            let quantity = Quantity::from_decimal_dp(abs_balance, instrument.size_precision())?;
2701
2702            let report = PositionStatusReport::new(
2703                account_id,
2704                instrument_id,
2705                side,
2706                quantity,
2707                ts_init,
2708                ts_init,
2709                None,
2710                None,
2711                None,
2712            );
2713
2714            reports.push(report);
2715        }
2716
2717        Ok(reports)
2718    }
2719
2720    /// Submit a new order.
2721    ///
2722    /// # Errors
2723    ///
2724    /// Returns an error if:
2725    /// - Credentials are missing.
2726    /// - The request fails.
2727    /// - Order validation fails.
2728    /// - The order is rejected.
2729    /// - The API returns an error.
2730    #[expect(clippy::too_many_arguments)]
2731    pub async fn submit_order(
2732        &self,
2733        account_id: AccountId,
2734        product_type: BybitProductType,
2735        instrument_id: InstrumentId,
2736        client_order_id: ClientOrderId,
2737        order_side: OrderSide,
2738        order_type: OrderType,
2739        quantity: Quantity,
2740        time_in_force: Option<TimeInForce>,
2741        price: Option<Price>,
2742        trigger_price: Option<Price>,
2743        post_only: Option<bool>,
2744        reduce_only: bool,
2745        is_quote_quantity: bool,
2746        is_leverage: bool,
2747        position_idx: Option<BybitPositionIdx>,
2748        bbo_side_type: Option<BybitBboSideType>,
2749        bbo_level: Option<String>,
2750        smp_type: Option<BybitOrderSmpType>,
2751        native_tp_sl: Option<&BybitNativeTpSlParams>,
2752    ) -> anyhow::Result<OrderStatusReport> {
2753        let instrument = self.instrument_from_cache(&instrument_id.symbol)?;
2754        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
2755
2756        let bybit_side = match order_side {
2757            OrderSide::Buy => BybitOrderSide::Buy,
2758            OrderSide::Sell => BybitOrderSide::Sell,
2759        };
2760
2761        // For stop/conditional orders, Bybit uses Market/Limit with trigger parameters
2762        let (bybit_order_type, is_stop_order) = match order_type {
2763            OrderType::Market => (BybitOrderType::Market, false),
2764            OrderType::Limit => (BybitOrderType::Limit, false),
2765            OrderType::StopMarket | OrderType::MarketIfTouched => (BybitOrderType::Market, true),
2766            OrderType::StopLimit | OrderType::LimitIfTouched => (BybitOrderType::Limit, true),
2767            _ => anyhow::bail!("Unsupported order type: {order_type:?}"),
2768        };
2769
2770        let bybit_tif = map_time_in_force(bybit_order_type, time_in_force, post_only)
2771            .map_err(|tif| anyhow::anyhow!("Unsupported time in force: {tif:?}"))?;
2772        let market_unit = spot_market_unit(product_type, bybit_order_type, is_quote_quantity);
2773        let trigger_dir = trigger_direction(order_type, order_side, is_stop_order);
2774
2775        let mut order_entry = BybitBatchPlaceOrderEntryBuilder::default();
2776        order_entry.symbol(bybit_symbol.raw_symbol().to_string());
2777        order_entry.side(bybit_side);
2778        order_entry.order_type(bybit_order_type);
2779        order_entry.qty(quantity.to_string());
2780        order_entry.time_in_force(bybit_tif);
2781        order_entry.order_link_id(client_order_id.to_string());
2782        order_entry.market_unit(market_unit);
2783        order_entry.trigger_direction(trigger_dir);
2784
2785        if bbo_side_type.is_none()
2786            && let Some(price) = price
2787        {
2788            order_entry.price(Some(price.to_string()));
2789        }
2790
2791        if let Some(trigger_price) = trigger_price {
2792            order_entry.trigger_price(Some(trigger_price.to_string()));
2793        }
2794
2795        if reduce_only {
2796            order_entry.reduce_only(Some(true));
2797        }
2798
2799        order_entry.is_leverage(spot_leverage(product_type, is_leverage));
2800
2801        if let Some(idx) = position_idx {
2802            order_entry.position_idx(Some(idx));
2803        }
2804
2805        order_entry.bbo_side_type(bbo_side_type);
2806        order_entry.bbo_level(bbo_level);
2807        order_entry.smp_type(smp_type);
2808
2809        if let Some(tp_sl) = native_tp_sl {
2810            if let Some(ref tp) = tp_sl.take_profit {
2811                order_entry.take_profit(Some(tp.clone()));
2812            }
2813
2814            if let Some(ref sl) = tp_sl.stop_loss {
2815                order_entry.stop_loss(Some(sl.clone()));
2816            }
2817
2818            if let Some(tp_trigger) = tp_sl.tp_trigger_by {
2819                order_entry.tp_trigger_by(Some(tp_trigger));
2820            }
2821
2822            if let Some(sl_trigger) = tp_sl.sl_trigger_by {
2823                order_entry.sl_trigger_by(Some(sl_trigger));
2824            }
2825
2826            if let Some(tp_ot) = tp_sl.tp_order_type {
2827                order_entry.tp_order_type(Some(tp_ot));
2828            }
2829
2830            if let Some(sl_ot) = tp_sl.sl_order_type {
2831                order_entry.sl_order_type(Some(sl_ot));
2832            }
2833
2834            if let Some(ref tp_lp) = tp_sl.tp_limit_price {
2835                order_entry.tp_limit_price(Some(tp_lp.clone()));
2836            }
2837
2838            if let Some(ref sl_lp) = tp_sl.sl_limit_price {
2839                order_entry.sl_limit_price(Some(sl_lp.clone()));
2840            }
2841
2842            // Default to `Full` when TP or SL is set without an explicit mode, mirroring the WS
2843            // path, so Bybit accepts the field instead of rejecting it.
2844            let mode = tp_sl.tpsl_mode.or_else(|| {
2845                (tp_sl.take_profit.is_some() || tp_sl.stop_loss.is_some())
2846                    .then_some(BybitTpSlMode::Full)
2847            });
2848
2849            if let Some(m) = mode {
2850                order_entry.tpsl_mode(Some(m));
2851            }
2852
2853            if let Some(close) = tp_sl.close_on_trigger {
2854                order_entry.close_on_trigger(Some(close));
2855            }
2856
2857            if let Some(ref iv) = tp_sl.order_iv {
2858                order_entry.order_iv(Some(iv.clone()));
2859            }
2860
2861            if let Some(mmp) = tp_sl.mmp {
2862                order_entry.mmp(Some(mmp));
2863            }
2864        }
2865
2866        let order_entry = order_entry.build().build_anyhow()?;
2867
2868        let mut params = BybitPlaceOrderParamsBuilder::default();
2869        params.category(product_type);
2870        params.order(order_entry);
2871
2872        let params = params.build().build_anyhow()?;
2873
2874        let body = serde_json::to_value(&params)?;
2875        let response = self.inner.place_order(&body).await?;
2876
2877        let order_id = response
2878            .result
2879            .order_id
2880            .ok_or(BybitSubmitOrderError::MissingOrderId)?;
2881
2882        let order = self
2883            .query_order_by_id(
2884                product_type,
2885                order_id.as_str(),
2886                BYBIT_ORDER_REALTIME,
2887                "after submission",
2888            )
2889            .await
2890            .map_err(|source| BybitSubmitOrderError::PostSubmitLookup { source })?;
2891
2892        // Only bail on rejection if there are no fills
2893        // If the order has fills (cum_exec_qty > 0), let the parser remap Rejected -> Canceled.
2894        // A post-only order that would take liquidity is reported as Cancelled with
2895        // rejectReason=EC_PostOnlyWillTakeLiquidity (not Rejected), so treat that as a rejection too.
2896        let is_rejection = order.order_status == crate::common::enums::BybitOrderStatus::Rejected
2897            || (order.order_status == crate::common::enums::BybitOrderStatus::Canceled
2898                && bybit_rejection_due_post_only(order.reject_reason.as_str()));
2899        if is_rejection && (order.cum_exec_qty.as_str() == "0" || order.cum_exec_qty.is_empty()) {
2900            return Err(BybitSubmitOrderError::Rejected {
2901                reason: order.reject_reason.to_string(),
2902            }
2903            .into());
2904        }
2905
2906        let ts_init = self.generate_ts_init();
2907
2908        parse_order_status_report(&order, &instrument, account_id, ts_init)
2909    }
2910
2911    /// Cancels an order and returns its confirmed terminal status.
2912    ///
2913    /// Polls until the order closes, bounded by the configured HTTP timeout.
2914    ///
2915    /// # Errors
2916    ///
2917    /// Returns an error if:
2918    /// - Credentials are missing.
2919    /// - The request fails.
2920    /// - The order doesn't exist.
2921    /// - The API returns an error.
2922    /// - Terminal status confirmation times out.
2923    pub async fn cancel_order(
2924        &self,
2925        account_id: AccountId,
2926        product_type: BybitProductType,
2927        instrument_id: InstrumentId,
2928        client_order_id: Option<ClientOrderId>,
2929        venue_order_id: Option<VenueOrderId>,
2930    ) -> anyhow::Result<OrderStatusReport> {
2931        self.instrument_from_cache(&instrument_id.symbol)?;
2932        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
2933
2934        let mut cancel_entry = BybitBatchCancelOrderEntryBuilder::default();
2935        cancel_entry.symbol(bybit_symbol.raw_symbol().to_string());
2936
2937        if let Some(venue_order_id) = venue_order_id {
2938            cancel_entry.order_id(venue_order_id.to_string());
2939        } else if let Some(client_order_id) = client_order_id {
2940            cancel_entry.order_link_id(client_order_id.to_string());
2941        } else {
2942            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
2943        }
2944
2945        let cancel_entry = cancel_entry.build().build_anyhow()?;
2946
2947        let mut params = BybitCancelOrderParamsBuilder::default();
2948        params.category(product_type);
2949        params.order(cancel_entry);
2950
2951        let params = params.build().build_anyhow()?;
2952        let body = serde_json::to_vec(&params)?;
2953
2954        let response: BybitPlaceOrderResponse = self
2955            .inner
2956            .send_request::<_, ()>(Method::POST, "/v5/order/cancel", None, Some(body), true)
2957            .await?;
2958
2959        let order_id = response
2960            .result
2961            .order_id
2962            .ok_or(BybitCancelOrderError::MissingOrderId)?;
2963
2964        let venue_order_id = VenueOrderId::from(order_id.as_str());
2965
2966        let confirmation = async {
2967            loop {
2968                if let Some(report) = self
2969                    .query_order(
2970                        account_id,
2971                        product_type,
2972                        instrument_id,
2973                        client_order_id,
2974                        Some(venue_order_id),
2975                    )
2976                    .await?
2977                    && report.order_status.is_closed()
2978                {
2979                    return Ok(report);
2980                }
2981
2982                tokio::time::sleep(Duration::from_millis(100)).await;
2983            }
2984        };
2985
2986        tokio::time::timeout(Duration::from_secs(self.inner.timeout_secs), confirmation)
2987            .await
2988            .context("timed out confirming Bybit order cancellation")
2989            .and_then(|result| result)
2990            .map_err(|source| BybitCancelOrderError::PostCancelLookup { source }.into())
2991    }
2992
2993    /// Batch cancel multiple orders.
2994    ///
2995    /// # Errors
2996    ///
2997    /// Returns an error if:
2998    /// - Credentials are missing.
2999    /// - The request fails.
3000    /// - Any of the orders don't exist.
3001    /// - The API returns an error.
3002    pub async fn batch_cancel_orders(
3003        &self,
3004        account_id: AccountId,
3005        product_type: BybitProductType,
3006        instrument_ids: Vec<InstrumentId>,
3007        client_order_ids: Vec<Option<ClientOrderId>>,
3008        venue_order_ids: Vec<Option<VenueOrderId>>,
3009    ) -> anyhow::Result<Vec<OrderStatusReport>> {
3010        if instrument_ids.len() != client_order_ids.len()
3011            || instrument_ids.len() != venue_order_ids.len()
3012        {
3013            anyhow::bail!(
3014                "instrument_ids, client_order_ids, and venue_order_ids must have the same length"
3015            );
3016        }
3017
3018        if instrument_ids.is_empty() {
3019            return Ok(Vec::new());
3020        }
3021
3022        let call_limit = batch_call_limit(product_type);
3023        if instrument_ids.len() > call_limit {
3024            anyhow::bail!(
3025                "Batch cancel limit is {call_limit} orders for {}",
3026                product_type.as_str()
3027            );
3028        }
3029
3030        let mut cancel_entries = Vec::new();
3031
3032        for ((instrument_id, client_order_id), venue_order_id) in instrument_ids
3033            .iter()
3034            .zip(client_order_ids.iter())
3035            .zip(venue_order_ids.iter())
3036        {
3037            let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3038            let mut cancel_entry = BybitBatchCancelOrderEntryBuilder::default();
3039            cancel_entry.symbol(bybit_symbol.raw_symbol().to_string());
3040
3041            if let Some(venue_order_id) = venue_order_id {
3042                cancel_entry.order_id(venue_order_id.to_string());
3043            } else if let Some(client_order_id) = client_order_id {
3044                cancel_entry.order_link_id(client_order_id.to_string());
3045            } else {
3046                anyhow::bail!(
3047                    "Either client_order_id or venue_order_id must be provided for each order"
3048                );
3049            }
3050
3051            cancel_entries.push(cancel_entry.build().build_anyhow()?);
3052        }
3053
3054        let chunk_limit = batch_endpoint_limit(product_type).min(batch_send_limit(product_type));
3055        for chunk in cancel_entries.chunks(chunk_limit) {
3056            let mut params = BybitBatchCancelOrderParamsBuilder::default();
3057            params.category(product_type);
3058            params.request(chunk.to_vec());
3059
3060            let params = params.build().build_anyhow()?;
3061            let body = serde_json::to_vec(&params)?;
3062
3063            let _response: BybitPlaceOrderResponse = self
3064                .inner
3065                .send_request::<_, ()>(
3066                    Method::POST,
3067                    "/v5/order/cancel-batch",
3068                    None,
3069                    Some(body),
3070                    true,
3071                )
3072                .await?;
3073        }
3074
3075        // Query each order to get full details after cancellation
3076        let mut reports = Vec::new();
3077
3078        for (instrument_id, (client_order_id, venue_order_id)) in instrument_ids
3079            .iter()
3080            .zip(client_order_ids.iter().zip(venue_order_ids.iter()))
3081        {
3082            let Ok(instrument) = self.instrument_from_cache(&instrument_id.symbol) else {
3083                log::debug!(
3084                    "Skipping cancelled order report for instrument not in cache: symbol={}",
3085                    instrument_id.symbol
3086                );
3087                continue;
3088            };
3089
3090            let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3091
3092            let mut query_params = BybitOpenOrdersParamsBuilder::default();
3093            query_params.category(product_type);
3094            query_params.symbol(bybit_symbol.raw_symbol().to_string());
3095
3096            if let Some(venue_order_id) = venue_order_id {
3097                query_params.order_id(venue_order_id.to_string());
3098            } else if let Some(client_order_id) = client_order_id {
3099                query_params.order_link_id(client_order_id.to_string());
3100            }
3101
3102            let query_params = query_params.build().build_anyhow()?;
3103            let order_response: BybitOrderHistoryResponse = self
3104                .inner
3105                .send_request(
3106                    Method::GET,
3107                    BYBIT_ORDER_HISTORY,
3108                    Some(&query_params),
3109                    None,
3110                    true,
3111                )
3112                .await?;
3113
3114            if let Some(order) = order_response.result.list.into_iter().next() {
3115                let ts_init = self.generate_ts_init();
3116                let report = parse_order_status_report(&order, &instrument, account_id, ts_init)?;
3117                reports.push(report);
3118            }
3119        }
3120
3121        Ok(reports)
3122    }
3123
3124    /// Cancel all orders for an instrument.
3125    ///
3126    /// # Errors
3127    ///
3128    /// Returns an error if:
3129    /// - Credentials are missing.
3130    /// - The request fails.
3131    /// - The API returns an error.
3132    pub async fn cancel_all_orders(
3133        &self,
3134        account_id: AccountId,
3135        product_type: BybitProductType,
3136        instrument_id: InstrumentId,
3137    ) -> anyhow::Result<Vec<OrderStatusReport>> {
3138        let instrument = self.instrument_from_cache(&instrument_id.symbol)?;
3139        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3140
3141        let mut params = BybitCancelAllOrdersParamsBuilder::default();
3142        params.category(product_type);
3143        params.symbol(bybit_symbol.raw_symbol().to_string());
3144
3145        let params = params.build().build_anyhow()?;
3146        let body = serde_json::to_vec(&params)?;
3147
3148        let _response: crate::common::models::BybitListResponse<serde_json::Value> = self
3149            .inner
3150            .send_request::<_, ()>(Method::POST, "/v5/order/cancel-all", None, Some(body), true)
3151            .await?;
3152
3153        // Query the order history to get all canceled orders
3154        let mut query_params = BybitOrderHistoryParamsBuilder::default();
3155        query_params.category(product_type);
3156        query_params.symbol(bybit_symbol.raw_symbol().to_string());
3157        query_params.limit(50u32);
3158
3159        let query_params = query_params.build().build_anyhow()?;
3160        let order_response: BybitOrderHistoryResponse = self
3161            .inner
3162            .send_request(
3163                Method::GET,
3164                BYBIT_ORDER_HISTORY,
3165                Some(&query_params),
3166                None,
3167                true,
3168            )
3169            .await?;
3170
3171        let ts_init = self.generate_ts_init();
3172
3173        let mut reports = Vec::new();
3174
3175        for order in order_response.result.list {
3176            if let Ok(report) = parse_order_status_report(&order, &instrument, account_id, ts_init)
3177            {
3178                reports.push(report);
3179            }
3180        }
3181
3182        Ok(reports)
3183    }
3184
3185    /// Modify an existing order.
3186    ///
3187    /// # Errors
3188    ///
3189    /// Returns an error if:
3190    /// - Credentials are missing.
3191    /// - The request fails.
3192    /// - The order doesn't exist.
3193    /// - The order is already closed.
3194    /// - The API returns an error.
3195    #[expect(clippy::too_many_arguments)]
3196    pub async fn modify_order(
3197        &self,
3198        account_id: AccountId,
3199        product_type: BybitProductType,
3200        instrument_id: InstrumentId,
3201        client_order_id: Option<ClientOrderId>,
3202        venue_order_id: Option<VenueOrderId>,
3203        quantity: Option<Quantity>,
3204        price: Option<Price>,
3205        trigger_price: Option<Price>,
3206    ) -> anyhow::Result<OrderStatusReport> {
3207        let instrument = self.instrument_from_cache(&instrument_id.symbol)?;
3208        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3209
3210        let mut amend_entry = BybitBatchAmendOrderEntryBuilder::default();
3211        amend_entry.symbol(bybit_symbol.raw_symbol().to_string());
3212
3213        if let Some(venue_order_id) = venue_order_id {
3214            amend_entry.order_id(venue_order_id.to_string());
3215        } else if let Some(client_order_id) = client_order_id {
3216            amend_entry.order_link_id(client_order_id.to_string());
3217        } else {
3218            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
3219        }
3220
3221        if let Some(quantity) = quantity {
3222            amend_entry.qty(Some(quantity.to_string()));
3223        }
3224
3225        if let Some(price) = price {
3226            amend_entry.price(Some(price.to_string()));
3227        }
3228
3229        if let Some(trigger_price) = trigger_price {
3230            amend_entry.trigger_price(Some(trigger_price.to_string()));
3231        }
3232
3233        let amend_entry = amend_entry.build().build_anyhow()?;
3234
3235        let mut params = BybitAmendOrderParamsBuilder::default();
3236        params.category(product_type);
3237        params.order(amend_entry);
3238
3239        let params = params.build().build_anyhow()?;
3240        let body = serde_json::to_vec(&params)?;
3241
3242        let response: BybitPlaceOrderResponse = self
3243            .inner
3244            .send_request::<_, ()>(Method::POST, "/v5/order/amend", None, Some(body), true)
3245            .await?;
3246
3247        let order_id = response
3248            .result
3249            .order_id
3250            .ok_or(BybitModifyOrderError::MissingOrderId)?;
3251
3252        let order = self
3253            .query_order_by_id(
3254                product_type,
3255                order_id.as_str(),
3256                BYBIT_ORDER_REALTIME,
3257                "after amendment",
3258            )
3259            .await
3260            .map_err(|source| BybitModifyOrderError::PostModifyLookup { source })?;
3261
3262        let ts_init = self.generate_ts_init();
3263
3264        parse_order_status_report(&order, &instrument, account_id, ts_init)
3265    }
3266
3267    /// Query a single order by client order ID or venue order ID.
3268    ///
3269    /// # Errors
3270    ///
3271    /// Returns an error if:
3272    /// - Credentials are missing.
3273    /// - The request fails.
3274    /// - The API returns an error.
3275    pub async fn query_order(
3276        &self,
3277        account_id: AccountId,
3278        product_type: BybitProductType,
3279        instrument_id: InstrumentId,
3280        client_order_id: Option<ClientOrderId>,
3281        venue_order_id: Option<VenueOrderId>,
3282    ) -> anyhow::Result<Option<OrderStatusReport>> {
3283        log::debug!(
3284            "query_order: instrument_id={instrument_id}, client_order_id={client_order_id:?}, venue_order_id={venue_order_id:?}"
3285        );
3286
3287        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3288
3289        let mut params = BybitOpenOrdersParamsBuilder::default();
3290        params.category(product_type);
3291        // Use the raw Bybit symbol (e.g., "ETHUSDT") not the full instrument symbol
3292        params.symbol(bybit_symbol.raw_symbol().to_string());
3293
3294        if let Some(venue_order_id) = venue_order_id {
3295            params.order_id(venue_order_id.to_string());
3296        } else if let Some(client_order_id) = client_order_id {
3297            params.order_link_id(client_order_id.to_string());
3298        } else {
3299            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
3300        }
3301
3302        let params = params.build().build_anyhow()?;
3303        let mut response: BybitOpenOrdersResponse = self
3304            .inner
3305            .send_request(Method::GET, BYBIT_ORDER_REALTIME, Some(&params), None, true)
3306            .await?;
3307
3308        // Options do not support the StopOrder filter
3309        if response.result.list.is_empty() && product_type != BybitProductType::Option {
3310            log::debug!("Order not found in open orders, trying with StopOrder filter");
3311
3312            let mut stop_params = BybitOpenOrdersParamsBuilder::default();
3313            stop_params.category(product_type);
3314            stop_params.symbol(bybit_symbol.raw_symbol().to_string());
3315            stop_params.order_filter(BybitOrderFilter::StopOrder);
3316
3317            if let Some(venue_order_id) = venue_order_id {
3318                stop_params.order_id(venue_order_id.to_string());
3319            } else if let Some(client_order_id) = client_order_id {
3320                stop_params.order_link_id(client_order_id.to_string());
3321            }
3322
3323            let stop_params = stop_params.build().build_anyhow()?;
3324            response = self
3325                .inner
3326                .send_request(
3327                    Method::GET,
3328                    BYBIT_ORDER_REALTIME,
3329                    Some(&stop_params),
3330                    None,
3331                    true,
3332                )
3333                .await?;
3334        }
3335
3336        // If not found in open orders, check order history
3337        if response.result.list.is_empty() {
3338            log::debug!("Order not found in open orders, checking order history");
3339
3340            let mut history_params = BybitOrderHistoryParamsBuilder::default();
3341            history_params.category(product_type);
3342            history_params.symbol(bybit_symbol.raw_symbol().to_string());
3343
3344            if let Some(venue_order_id) = venue_order_id {
3345                history_params.order_id(venue_order_id.to_string());
3346            } else if let Some(client_order_id) = client_order_id {
3347                history_params.order_link_id(client_order_id.to_string());
3348            }
3349
3350            let history_params = history_params.build().build_anyhow()?;
3351
3352            let mut history_response: BybitOrderHistoryResponse = self
3353                .inner
3354                .send_request(
3355                    Method::GET,
3356                    BYBIT_ORDER_HISTORY,
3357                    Some(&history_params),
3358                    None,
3359                    true,
3360                )
3361                .await?;
3362
3363            if history_response.result.list.is_empty() && product_type == BybitProductType::Option {
3364                log::debug!("Option order not found in order history");
3365                return Ok(None);
3366            }
3367
3368            // Options do not support the StopOrder filter
3369            if history_response.result.list.is_empty() && product_type != BybitProductType::Option {
3370                log::debug!("Order not found in order history, trying with StopOrder filter");
3371
3372                let mut stop_history_params = BybitOrderHistoryParamsBuilder::default();
3373                stop_history_params.category(product_type);
3374                stop_history_params.symbol(bybit_symbol.raw_symbol().to_string());
3375                stop_history_params.order_filter(BybitOrderFilter::StopOrder);
3376
3377                if let Some(venue_order_id) = venue_order_id {
3378                    stop_history_params.order_id(venue_order_id.to_string());
3379                } else if let Some(client_order_id) = client_order_id {
3380                    stop_history_params.order_link_id(client_order_id.to_string());
3381                }
3382
3383                let stop_history_params = stop_history_params
3384                    .build()
3385                    .map_err(|e| anyhow::anyhow!(e))?;
3386
3387                history_response = self
3388                    .inner
3389                    .send_request(
3390                        Method::GET,
3391                        BYBIT_ORDER_HISTORY,
3392                        Some(&stop_history_params),
3393                        None,
3394                        true,
3395                    )
3396                    .await?;
3397
3398                if history_response.result.list.is_empty() {
3399                    log::debug!("Order not found in order history with StopOrder filter either");
3400                    return Ok(None);
3401                }
3402            }
3403
3404            // Move the order from history response to the response list
3405            response.result.list = history_response.result.list;
3406        }
3407
3408        let order = &response.result.list[0];
3409        let ts_init = self.generate_ts_init();
3410
3411        log::debug!(
3412            "Query order response: symbol={}, order_id={}, order_link_id={}",
3413            order.symbol.as_str(),
3414            order.order_id.as_str(),
3415            order.order_link_id.as_str()
3416        );
3417
3418        let instrument = self
3419            .instrument_from_cache(&instrument_id.symbol)
3420            .map_err(|e| {
3421                anyhow::anyhow!(
3422                    "Failed to query order {}: {}",
3423                    client_order_id
3424                        .as_ref()
3425                        .map(|id| id.to_string())
3426                        .or_else(|| venue_order_id.as_ref().map(|id| id.to_string()))
3427                        .unwrap_or_else(|| "unknown".to_string()),
3428                    e
3429                )
3430            })?;
3431
3432        log::debug!("Retrieved instrument from cache: id={}", instrument.id());
3433
3434        let report =
3435            parse_order_status_report(order, &instrument, account_id, ts_init).map_err(|e| {
3436                log::debug!(
3437                    "Failed to parse order status report for {}: {}",
3438                    order.order_link_id.as_str(),
3439                    e
3440                );
3441                e
3442            })?;
3443
3444        log::debug!(
3445            "Successfully created OrderStatusReport for {}",
3446            order.order_link_id.as_str()
3447        );
3448
3449        Ok(Some(report))
3450    }
3451
3452    async fn paginate_instruments<D, F>(
3453        &self,
3454        product_type: BybitProductType,
3455        symbol: &Option<String>,
3456        base_coin: Option<Ustr>,
3457        mut parse: F,
3458    ) -> anyhow::Result<Vec<InstrumentAny>>
3459    where
3460        D: DeserializeOwned,
3461        BybitCursorListResponse<D>: BybitResponseCheck,
3462        F: FnMut(&D) -> Option<InstrumentAny>,
3463    {
3464        let mut instruments = Vec::new();
3465        let mut cursor: Option<String> = None;
3466        let mut cursor_walk = CursorWalk::default();
3467
3468        loop {
3469            let params = BybitInstrumentsInfoParams {
3470                category: product_type,
3471                symbol: symbol.clone(),
3472                status: None,
3473                base_coin: instrument_base_coin(product_type, symbol.as_deref(), base_coin),
3474                limit: Some(1000),
3475                cursor: cursor.clone(),
3476            };
3477
3478            let response: BybitCursorListResponse<D> = self.inner.get_instruments(&params).await?;
3479
3480            for definition in &response.result.list {
3481                if let Some(instrument) = parse(definition) {
3482                    instruments.push(instrument);
3483                }
3484            }
3485
3486            // A short instrument list is a visible gap, since the risk engine denies the next
3487            // order on a missing instrument by name, while a short reconciliation history is
3488            // silent, so the other walks return this error and this one keeps what it has.
3489            cursor = match cursor_walk
3490                .advance(BYBIT_INSTRUMENTS_INFO, response.result.next_page_cursor)
3491            {
3492                Ok(cursor) => cursor,
3493                Err(e) => {
3494                    log::warn!(
3495                        "{e}, keeping the {} instrument(s) already read",
3496                        instruments.len()
3497                    );
3498                    break;
3499                }
3500            };
3501
3502            if cursor.is_none() {
3503                break;
3504            }
3505        }
3506
3507        Ok(instruments)
3508    }
3509
3510    /// Fetches instrument info and returns the current status of each symbol.
3511    ///
3512    /// Paginates through the instruments endpoint collecting only
3513    /// `(InstrumentId, MarketStatusAction)` pairs. This avoids full instrument
3514    /// parsing.
3515    ///
3516    /// # Errors
3517    ///
3518    /// Returns an error if the request fails.
3519    pub async fn request_instrument_statuses(
3520        &self,
3521        product_type: BybitProductType,
3522    ) -> anyhow::Result<AHashMap<InstrumentId, MarketStatusAction>> {
3523        match product_type {
3524            BybitProductType::Spot => {
3525                self.paginate_instrument_statuses::<BybitInstrumentSpot, _>(product_type, |def| {
3526                    (def.symbol, def.status.into())
3527                })
3528                .await
3529            }
3530            BybitProductType::Linear => {
3531                self.paginate_instrument_statuses::<BybitInstrumentLinear, _>(product_type, |def| {
3532                    let scheduled = def.contract_type == BybitContractType::LinearPerpetual
3533                        && def.delivery_time != "0";
3534                    (def.symbol, perp_status(def.status.into(), scheduled))
3535                })
3536                .await
3537            }
3538            BybitProductType::Inverse => {
3539                self.paginate_instrument_statuses::<BybitInstrumentInverse, _>(
3540                    product_type,
3541                    |def| {
3542                        let scheduled = def.contract_type == BybitContractType::InversePerpetual
3543                            && def.delivery_time != "0";
3544                        (def.symbol, perp_status(def.status.into(), scheduled))
3545                    },
3546                )
3547                .await
3548            }
3549            BybitProductType::Option => {
3550                self.paginate_instrument_statuses::<BybitInstrumentOption, _>(product_type, |def| {
3551                    (def.symbol, def.status.into())
3552                })
3553                .await
3554            }
3555        }
3556    }
3557
3558    async fn paginate_instrument_statuses<D, F>(
3559        &self,
3560        product_type: BybitProductType,
3561        mut parse: F,
3562    ) -> anyhow::Result<AHashMap<InstrumentId, MarketStatusAction>>
3563    where
3564        D: DeserializeOwned,
3565        BybitCursorListResponse<D>: BybitResponseCheck,
3566        F: FnMut(&D) -> (Ustr, MarketStatusAction),
3567    {
3568        let mut statuses = AHashMap::new();
3569        let mut cursor: Option<String> = None;
3570        let mut cursor_walk = CursorWalk::default();
3571
3572        loop {
3573            let params = BybitInstrumentsInfoParams {
3574                category: product_type,
3575                symbol: None,
3576                status: None,
3577                base_coin: instrument_base_coin(product_type, None, None),
3578                limit: Some(1000),
3579                cursor: cursor.clone(),
3580            };
3581
3582            let response: BybitCursorListResponse<D> = self.inner.get_instruments(&params).await?;
3583            for definition in &response.result.list {
3584                let (raw_symbol, status) = parse(definition);
3585                let symbol = make_bybit_symbol(raw_symbol, product_type);
3586                let id = InstrumentId::new(Symbol::from(symbol), *BYBIT_VENUE);
3587                statuses.insert(id, status);
3588            }
3589
3590            cursor =
3591                cursor_walk.advance(BYBIT_INSTRUMENTS_INFO, response.result.next_page_cursor)?;
3592
3593            if cursor.is_none() {
3594                break;
3595            }
3596        }
3597
3598        Ok(statuses)
3599    }
3600
3601    /// Request instruments for a given product type.
3602    ///
3603    /// When `base_coin` is provided, the request is narrowed to that base coin.
3604    /// `Option` requests with neither `symbol` nor `base_coin` load all listed
3605    /// base coins.
3606    ///
3607    /// # Errors
3608    ///
3609    /// Returns an error if the request fails or parsing fails.
3610    pub async fn request_instruments(
3611        &self,
3612        product_type: BybitProductType,
3613        symbol: Option<String>,
3614        base_coin: Option<Ustr>,
3615    ) -> anyhow::Result<Vec<InstrumentAny>> {
3616        let ts_init = self.generate_ts_init();
3617
3618        let instruments = match product_type {
3619            BybitProductType::Spot => {
3620                self.paginate_instruments::<BybitInstrumentSpot, _>(
3621                    product_type,
3622                    &symbol,
3623                    base_coin,
3624                    |def| {
3625                        instrument_or_warn(
3626                            product_type,
3627                            def.symbol,
3628                            parse_spot_instrument(def, ts_init, ts_init),
3629                        )
3630                    },
3631                )
3632                .await?
3633            }
3634            BybitProductType::Linear => {
3635                self.paginate_instruments::<BybitInstrumentLinear, _>(
3636                    product_type,
3637                    &symbol,
3638                    base_coin,
3639                    |def| {
3640                        instrument_or_warn(
3641                            product_type,
3642                            def.symbol,
3643                            parse_linear_instrument(def, ts_init, ts_init),
3644                        )
3645                    },
3646                )
3647                .await?
3648            }
3649            BybitProductType::Inverse => {
3650                self.paginate_instruments::<BybitInstrumentInverse, _>(
3651                    product_type,
3652                    &symbol,
3653                    base_coin,
3654                    |def| {
3655                        instrument_or_warn(
3656                            product_type,
3657                            def.symbol,
3658                            parse_inverse_instrument(def, ts_init, ts_init),
3659                        )
3660                    },
3661                )
3662                .await?
3663            }
3664            BybitProductType::Option => {
3665                self.paginate_instruments::<BybitInstrumentOption, _>(
3666                    product_type,
3667                    &symbol,
3668                    base_coin,
3669                    |def| {
3670                        instrument_or_warn(
3671                            product_type,
3672                            def.symbol,
3673                            parse_option_instrument(def, ts_init, ts_init),
3674                        )
3675                    },
3676                )
3677                .await?
3678            }
3679        };
3680
3681        self.cache_instruments(&instruments);
3682
3683        Ok(instruments)
3684    }
3685
3686    /// Requests full instrument definitions and their market statuses in a single endpoint pass.
3687    ///
3688    /// Both are parsed from the same `/v5/market/instruments-info` response, avoiding a second
3689    /// round-trip when a caller needs definitions and statuses together (e.g. the polling loop
3690    /// serving both instrument and status subscriptions).
3691    ///
3692    /// # Errors
3693    ///
3694    /// Returns an error if the request fails or parsing fails.
3695    pub async fn request_instruments_with_statuses(
3696        &self,
3697        product_type: BybitProductType,
3698    ) -> anyhow::Result<(
3699        Vec<InstrumentAny>,
3700        AHashMap<InstrumentId, MarketStatusAction>,
3701    )> {
3702        let ts_init = self.generate_ts_init();
3703        let mut statuses = AHashMap::new();
3704
3705        let instruments = match product_type {
3706            BybitProductType::Spot => {
3707                self.paginate_instruments::<BybitInstrumentSpot, _>(
3708                    product_type,
3709                    &None::<String>,
3710                    None,
3711                    |def| {
3712                        let id = InstrumentId::new(
3713                            Symbol::from(make_bybit_symbol(def.symbol, product_type)),
3714                            *BYBIT_VENUE,
3715                        );
3716                        statuses.insert(id, MarketStatusAction::from(def.status));
3717                        instrument_or_warn(
3718                            product_type,
3719                            def.symbol,
3720                            parse_spot_instrument(def, ts_init, ts_init),
3721                        )
3722                    },
3723                )
3724                .await?
3725            }
3726            BybitProductType::Linear => {
3727                self.paginate_instruments::<BybitInstrumentLinear, _>(
3728                    product_type,
3729                    &None::<String>,
3730                    None,
3731                    |def| {
3732                        let id = InstrumentId::new(
3733                            Symbol::from(make_bybit_symbol(def.symbol, product_type)),
3734                            *BYBIT_VENUE,
3735                        );
3736                        let scheduled = def.contract_type == BybitContractType::LinearPerpetual
3737                            && def.delivery_time != "0";
3738                        statuses.insert(id, perp_status(def.status.into(), scheduled));
3739                        instrument_or_warn(
3740                            product_type,
3741                            def.symbol,
3742                            parse_linear_instrument(def, ts_init, ts_init),
3743                        )
3744                    },
3745                )
3746                .await?
3747            }
3748            BybitProductType::Inverse => {
3749                self.paginate_instruments::<BybitInstrumentInverse, _>(
3750                    product_type,
3751                    &None::<String>,
3752                    None,
3753                    |def| {
3754                        let id = InstrumentId::new(
3755                            Symbol::from(make_bybit_symbol(def.symbol, product_type)),
3756                            *BYBIT_VENUE,
3757                        );
3758                        let scheduled = def.contract_type == BybitContractType::InversePerpetual
3759                            && def.delivery_time != "0";
3760                        statuses.insert(id, perp_status(def.status.into(), scheduled));
3761                        instrument_or_warn(
3762                            product_type,
3763                            def.symbol,
3764                            parse_inverse_instrument(def, ts_init, ts_init),
3765                        )
3766                    },
3767                )
3768                .await?
3769            }
3770            BybitProductType::Option => {
3771                self.paginate_instruments::<BybitInstrumentOption, _>(
3772                    product_type,
3773                    &None::<String>,
3774                    None,
3775                    |def| {
3776                        let id = InstrumentId::new(
3777                            Symbol::from(make_bybit_symbol(def.symbol, product_type)),
3778                            *BYBIT_VENUE,
3779                        );
3780                        statuses.insert(id, MarketStatusAction::from(def.status));
3781                        instrument_or_warn(
3782                            product_type,
3783                            def.symbol,
3784                            parse_option_instrument(def, ts_init, ts_init),
3785                        )
3786                    },
3787                )
3788                .await?
3789            }
3790        };
3791
3792        self.cache_instruments(&instruments);
3793
3794        Ok((instruments, statuses))
3795    }
3796
3797    /// Request ticker information for market data.
3798    ///
3799    /// Fetches ticker data from Bybit's `/v5/market/tickers` endpoint and returns
3800    /// a unified `BybitTickerData` structure compatible with all product types.
3801    ///
3802    /// # Errors
3803    ///
3804    /// Returns an error if the request fails or parsing fails.
3805    ///
3806    /// # References
3807    ///
3808    /// <https://bybit-exchange.github.io/docs/v5/market/tickers>
3809    pub async fn request_tickers(
3810        &self,
3811        params: &BybitTickersParams,
3812    ) -> anyhow::Result<Vec<BybitTickerData>> {
3813        use super::models::{
3814            BybitTickersLinearResponse, BybitTickersOptionResponse, BybitTickersSpotResponse,
3815        };
3816
3817        match params.category {
3818            BybitProductType::Spot => {
3819                let response: BybitTickersSpotResponse = self.inner.get_tickers(params).await?;
3820                Ok(response.result.list.into_iter().map(Into::into).collect())
3821            }
3822            BybitProductType::Linear | BybitProductType::Inverse => {
3823                let response: BybitTickersLinearResponse = self.inner.get_tickers(params).await?;
3824                Ok(response.result.list.into_iter().map(Into::into).collect())
3825            }
3826            BybitProductType::Option => {
3827                let response: BybitTickersOptionResponse = self.inner.get_tickers(params).await?;
3828                Ok(response.result.list.into_iter().map(Into::into).collect())
3829            }
3830        }
3831    }
3832
3833    /// Requests raw option tickers for a given base coin.
3834    ///
3835    /// Returns `Vec<BybitTickerOption>` with the raw fields including `underlying_price`.
3836    ///
3837    /// # Errors
3838    ///
3839    /// Returns an error if the request fails.
3840    pub async fn request_option_tickers_raw(
3841        &self,
3842        base_coin: &str,
3843    ) -> anyhow::Result<Vec<BybitTickerOption>> {
3844        let params = BybitTickersParams {
3845            category: BybitProductType::Option,
3846            symbol: None,
3847            base_coin: Some(base_coin.to_string()),
3848            exp_date: None,
3849        };
3850        let response: BybitTickersOptionResponse = self.inner.get_tickers(&params).await?;
3851        Ok(response.result.list)
3852    }
3853
3854    /// Request raw option tickers with custom params.
3855    ///
3856    /// This allows fetching a single instrument by setting `symbol` in the params,
3857    /// instead of fetching all options for a base coin.
3858    ///
3859    /// # Errors
3860    ///
3861    /// Returns an error if the request fails.
3862    pub async fn request_option_tickers_raw_with_params(
3863        &self,
3864        params: &BybitTickersParams,
3865    ) -> anyhow::Result<Vec<BybitTickerOption>> {
3866        let response: BybitTickersOptionResponse = self.inner.get_tickers(params).await?;
3867        Ok(response.result.list)
3868    }
3869
3870    /// Request recent trade tick history for a given symbol.
3871    ///
3872    /// Returns the most recent public trades from Bybit's `/v5/market/recent-trade` endpoint.
3873    /// This endpoint only provides recent trades (up to 1000 most recent), typically covering
3874    /// only the last few minutes for active markets.
3875    ///
3876    /// **Note**: For historical trade data with time ranges, use the klines endpoint instead.
3877    /// The Bybit public API does not support fetching historical trades by time range.
3878    ///
3879    /// # Errors
3880    ///
3881    /// Returns an error if:
3882    /// - The instrument is not found in cache.
3883    /// - The request fails.
3884    /// - Parsing fails.
3885    ///
3886    /// # References
3887    ///
3888    /// <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
3889    pub async fn request_trades(
3890        &self,
3891        product_type: BybitProductType,
3892        instrument_id: InstrumentId,
3893        limit: Option<u32>,
3894    ) -> anyhow::Result<Vec<TradeTick>> {
3895        let instrument = self.instrument_from_cache_by_id(instrument_id)?;
3896        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3897
3898        let mut params_builder = BybitTradesParamsBuilder::default();
3899        params_builder.category(product_type);
3900        params_builder.symbol(bybit_symbol.raw_symbol().to_string());
3901
3902        if let Some(limit_val) = limit {
3903            params_builder.limit(limit_val);
3904        }
3905
3906        let params = params_builder.build().build_anyhow()?;
3907        let response = self.inner.get_recent_trades(&params).await?;
3908
3909        let mut trades = Vec::new();
3910
3911        for trade in response.result.list {
3912            if let Ok(trade_tick) = parse_trade_tick(&trade, &instrument, None) {
3913                trades.push(trade_tick);
3914            }
3915        }
3916
3917        Ok(trades)
3918    }
3919
3920    /// Request funding rate history for a given symbol.
3921    ///
3922    /// # Errors
3923    ///
3924    /// Returns an error if:
3925    /// - The instrument is not found in cache.
3926    /// - The request fails.
3927    /// - Parsing fails.
3928    ///
3929    /// # References
3930    ///
3931    /// <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
3932    pub async fn request_funding_rates(
3933        &self,
3934        product_type: BybitProductType,
3935        instrument_id: InstrumentId,
3936        start: Option<Timestamp>,
3937        end: Option<Timestamp>,
3938        limit: Option<u32>,
3939    ) -> anyhow::Result<Vec<FundingRateUpdate>> {
3940        let instrument = self.instrument_from_cache_by_id(instrument_id)?;
3941        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
3942
3943        let start_ms = start.map(|dt| dt.as_millisecond());
3944        let mut seen_timestamps: AHashSet<i64> = AHashSet::new();
3945
3946        let mut raw_funding_rates = Vec::new();
3947
3948        // Bybit requires endTime when startTime is provided
3949        let mut current_end_ms = match (start, end) {
3950            (Some(_), None) => Some(Timestamp::now().as_millisecond()),
3951            _ => end.map(|dt| dt.as_millisecond()),
3952        };
3953
3954        loop {
3955            let mut params_builder = BybitFundingParamsBuilder::default();
3956            params_builder.category(product_type);
3957            params_builder.symbol(bybit_symbol.raw_symbol().to_string());
3958            params_builder.limit(limit.unwrap_or(200).clamp(0, 200)); // 200 is the maximum for the Bybit API
3959
3960            if let Some(start_val) = start_ms {
3961                params_builder.start_time(start_val);
3962            }
3963
3964            if let Some(end_val) = current_end_ms {
3965                params_builder.end_time(end_val);
3966            }
3967
3968            let params = params_builder.build().build_anyhow()?;
3969            let response = self.inner.get_funding_history(&params).await?;
3970
3971            let funding_rates = response.result.list;
3972
3973            let mut new_funding_rates_with_ts: Vec<(i64, _)> = funding_rates
3974                .into_iter()
3975                .filter_map(|f| {
3976                    let Ok(ts) = f.funding_rate_timestamp.parse::<i64>() else {
3977                        return None;
3978                    };
3979
3980                    seen_timestamps.insert(ts).then_some((ts, f))
3981                })
3982                .collect();
3983
3984            new_funding_rates_with_ts.sort_by_key(|(ts, _)| Reverse(*ts));
3985
3986            let earliest_funding_time = match new_funding_rates_with_ts.last() {
3987                Some((last_ts, _)) => *last_ts,
3988                None => break,
3989            };
3990
3991            let new_funding_rates = new_funding_rates_with_ts.into_iter().map(|(_, f)| f);
3992            raw_funding_rates.extend(new_funding_rates);
3993
3994            // Check if we've reached the requested limit
3995            if let Some(limit_val) = limit
3996                && raw_funding_rates.len() >= limit_val as usize
3997            {
3998                break;
3999            }
4000
4001            if let Some(start_val) = start_ms
4002                && earliest_funding_time <= start_val
4003            {
4004                break;
4005            }
4006
4007            // Move end time backwards to get earlier data
4008            current_end_ms = Some(earliest_funding_time - 1);
4009        }
4010
4011        if let Some(limit_val) = limit {
4012            raw_funding_rates.truncate(limit_val as usize);
4013        }
4014        let mut rates: Vec<FundingRateUpdate> = Vec::with_capacity(raw_funding_rates.len());
4015
4016        for window in raw_funding_rates.windows(2) {
4017            let raw = &window[0];
4018            let timestamp = raw
4019                .funding_rate_timestamp
4020                .parse::<i64>()
4021                .map_err(|_| anyhow::anyhow!("invalid funding_rate_timestamp"))?;
4022            let older_timestamp = window[1]
4023                .funding_rate_timestamp
4024                .parse::<i64>()
4025                .map_err(|_| anyhow::anyhow!("invalid funding_rate_timestamp"))?;
4026
4027            let interval_millis = timestamp - older_timestamp;
4028            let rate = parse_funding_rate(raw, &instrument, Some(interval_millis))?;
4029
4030            rates.push(rate);
4031        }
4032
4033        if let Some(last_raw) = raw_funding_rates.last() {
4034            let rate = parse_funding_rate(last_raw, &instrument, None)?;
4035            rates.push(rate);
4036        }
4037
4038        rates.reverse();
4039
4040        Ok(rates)
4041    }
4042
4043    /// Request an orderbook snapshot for a given symbol.
4044    ///
4045    /// Bybit limits the amount of levels (depth) for each product type to:
4046    /// - Spot: `1..=200` (default: `1`)
4047    /// - Linear & Inverse: `1..=500` (default: `25`)
4048    /// - Options: `1..=25` (default: `1`)
4049    ///
4050    /// # Errors
4051    ///
4052    /// Returns an error if:
4053    /// - The instrument is not found in cache.
4054    /// - The request fails.
4055    /// - Parsing fails.
4056    ///
4057    /// # References
4058    ///
4059    /// <https://bybit-exchange.github.io/docs/v5/market/orderbook>
4060    pub async fn request_orderbook_snapshot(
4061        &self,
4062        product_type: BybitProductType,
4063        instrument_id: InstrumentId,
4064        limit: Option<u32>,
4065    ) -> anyhow::Result<OrderBookDeltas> {
4066        let instrument = self.instrument_from_cache_by_id(instrument_id)?;
4067        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
4068
4069        let mut params_builder = BybitOrderbookParamsBuilder::default();
4070        params_builder.category(product_type);
4071        params_builder.symbol(bybit_symbol.raw_symbol().to_string());
4072
4073        if let Some(limit) = limit {
4074            let max_limit = match product_type {
4075                BybitProductType::Spot => 200,
4076                BybitProductType::Option => 25,
4077                BybitProductType::Linear | BybitProductType::Inverse => 500,
4078            };
4079            let clamped_limit = limit.min(max_limit);
4080            if limit > max_limit {
4081                log::warn!(
4082                    "Bybit orderbook snapshot request depth limit exceeds venue maximum; clamping: limit={limit}, clamped_limit={clamped_limit}",
4083                );
4084            }
4085            params_builder.limit(clamped_limit);
4086        }
4087
4088        let params = params_builder.build().build_anyhow()?;
4089        let response = self.inner.get_orderbook(&params).await?;
4090
4091        let deltas = parse_orderbook(&response.result, &instrument, None)?;
4092
4093        Ok(deltas)
4094    }
4095
4096    /// Request bar/kline history for a given symbol.
4097    ///
4098    /// # Errors
4099    ///
4100    /// Returns an error if:
4101    /// - The instrument is not found in cache.
4102    /// - The request fails.
4103    /// - Parsing fails.
4104    ///
4105    /// # References
4106    ///
4107    /// <https://bybit-exchange.github.io/docs/v5/market/kline>
4108    pub async fn request_bars(
4109        &self,
4110        product_type: BybitProductType,
4111        bar_type: BarType,
4112        start: Option<Timestamp>,
4113        end: Option<Timestamp>,
4114        limit: Option<u32>,
4115        timestamp_on_close: bool,
4116    ) -> anyhow::Result<Vec<Bar>> {
4117        let instrument_id = bar_type.instrument_id();
4118        let instrument = self.instrument_from_cache_by_id(instrument_id)?;
4119        let bybit_symbol = BybitSymbol::new(instrument_id.symbol.as_str())?;
4120
4121        // Convert Nautilus BarSpec to Bybit interval
4122        let interval = bar_spec_to_bybit_interval(
4123            bar_type.spec().aggregation,
4124            bar_type.spec().step.get() as u64,
4125        )?;
4126
4127        let start_ms = start.map(|dt| dt.as_millisecond());
4128        let mut seen_timestamps: AHashSet<i64> = AHashSet::new();
4129        let current_time_ms = get_atomic_clock_realtime().get_time_ms() as i64;
4130
4131        // Pagination strategy: work backwards from end time
4132        // - Each page fetched is older than the previous page
4133        // - Within each page, bars are in chronological order (oldest to newest)
4134        // - We collect pages in reverse order (newest first) then reverse at the end
4135        // Example with 2 pages:
4136        //   Page 1 (most recent): bars [T=2000..2999]
4137        //   Page 2 (older):       bars [T=1000..1999]
4138        //   Collected: [[T=2000..2999], [T=1000..1999]]
4139        //   After reverse + flatten: [T=1000..1999, T=2000..2999] ✓ chronological
4140        let mut pages: Vec<Vec<Bar>> = Vec::new();
4141        let mut total_bars = 0usize;
4142        let mut current_end = end.map(|dt| dt.as_millisecond());
4143        let mut page_count = 0;
4144
4145        loop {
4146            page_count += 1;
4147
4148            let mut params_builder = BybitKlinesParamsBuilder::default();
4149            params_builder.category(product_type);
4150            params_builder.symbol(bybit_symbol.raw_symbol().to_string());
4151            params_builder.interval(interval);
4152            params_builder.limit(1000u32); // Limit for data size per page (maximum for the Bybit API)
4153
4154            if let Some(start_val) = start_ms {
4155                params_builder.start(start_val);
4156            }
4157
4158            if let Some(end_val) = current_end {
4159                params_builder.end(end_val);
4160            }
4161
4162            let params = params_builder.build().build_anyhow()?;
4163            let response = self.inner.get_klines(&params).await?;
4164
4165            let klines = response.result.list;
4166            if klines.is_empty() {
4167                break;
4168            }
4169
4170            // Parse timestamps once and pair with klines for sorting
4171            let mut klines_with_ts: Vec<(i64, _)> = klines
4172                .into_iter()
4173                .filter_map(|k| k.start.parse::<i64>().ok().map(|ts| (ts, k)))
4174                .collect();
4175
4176            klines_with_ts.sort_by_key(|(ts, _)| *ts);
4177
4178            // Check if we have any new timestamps
4179            let has_new = klines_with_ts
4180                .iter()
4181                .any(|(ts, _)| !seen_timestamps.contains(ts));
4182
4183            if !has_new {
4184                break;
4185            }
4186
4187            let mut page_bars = Vec::with_capacity(klines_with_ts.len());
4188
4189            let mut earliest_ts: Option<i64> = None;
4190
4191            for (start_time, kline) in &klines_with_ts {
4192                // Track earliest timestamp for pagination
4193                if earliest_ts.is_none_or(|ts| *start_time < ts) {
4194                    earliest_ts = Some(*start_time);
4195                }
4196
4197                let bar_end_time = interval.bar_end_time_ms(*start_time);
4198                if bar_end_time > current_time_ms {
4199                    continue;
4200                }
4201
4202                if !seen_timestamps.contains(start_time)
4203                    && let Ok(bar) =
4204                        parse_kline_bar(kline, &instrument, bar_type, timestamp_on_close, None)
4205                {
4206                    page_bars.push(bar);
4207                    seen_timestamps.insert(*start_time);
4208                }
4209            }
4210
4211            // page_bars may be empty if all klines were partial, but pagination
4212            // continues to fetch older closed bars
4213            total_bars += page_bars.len();
4214            pages.push(page_bars);
4215
4216            // Check if we've reached the requested limit
4217            if let Some(limit_val) = limit
4218                && total_bars >= limit_val as usize
4219            {
4220                break;
4221            }
4222
4223            // Move end time backwards to get earlier data
4224            // Set new end to be 1ms before the first bar of this page
4225            let Some(earliest_bar_time) = earliest_ts else {
4226                break;
4227            };
4228
4229            if let Some(start_val) = start_ms
4230                && earliest_bar_time <= start_val
4231            {
4232                break;
4233            }
4234
4235            current_end = Some(earliest_bar_time - 1);
4236
4237            // Safety check to prevent infinite loops
4238            if page_count > 100 {
4239                break;
4240            }
4241        }
4242
4243        // Reverse pages and flatten to get chronological order (oldest to newest)
4244        let mut all_bars: Vec<Bar> = Vec::with_capacity(total_bars);
4245        for page in pages.into_iter().rev() {
4246            all_bars.extend(page);
4247        }
4248
4249        // If limit is specified and we have more bars, return the last N bars (most recent)
4250        if let Some(limit_val) = limit {
4251            let limit_usize = limit_val as usize;
4252            if all_bars.len() > limit_usize {
4253                let start_idx = all_bars.len() - limit_usize;
4254                return Ok(all_bars[start_idx..].to_vec());
4255            }
4256        }
4257
4258        Ok(all_bars)
4259    }
4260
4261    fn instrument_from_cache_by_id(
4262        &self,
4263        instrument_id: InstrumentId,
4264    ) -> anyhow::Result<InstrumentAny> {
4265        self.get_instrument(&instrument_id.symbol.inner())
4266            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id).into())
4267    }
4268
4269    /// Requests trading fee rates for the specified product type and optional filters.
4270    ///
4271    /// # Errors
4272    ///
4273    /// Returns an error if:
4274    /// - The request fails.
4275    /// - Parsing fails.
4276    ///
4277    /// # References
4278    ///
4279    /// <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
4280    pub async fn request_fee_rates(
4281        &self,
4282        product_type: BybitProductType,
4283        symbol: Option<String>,
4284        base_coin: Option<String>,
4285    ) -> anyhow::Result<Vec<BybitFeeRate>> {
4286        let params = BybitFeeRateParams {
4287            category: product_type,
4288            symbol,
4289            base_coin,
4290        };
4291
4292        let response = self.inner.get_fee_rate(&params).await?;
4293        Ok(response.result.list)
4294    }
4295
4296    /// Requests the current account state for the specified account type.
4297    ///
4298    /// # Errors
4299    ///
4300    /// Returns an error if:
4301    /// - The request fails.
4302    /// - Parsing fails.
4303    ///
4304    /// # References
4305    ///
4306    /// <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
4307    pub async fn request_account_state(
4308        &self,
4309        account_type: BybitAccountType,
4310        account_id: AccountId,
4311    ) -> anyhow::Result<AccountState> {
4312        let params = BybitWalletBalanceParams {
4313            account_type,
4314            coin: None,
4315        };
4316
4317        let response = self.inner.get_wallet_balance(&params).await?;
4318        let ts_init = self.generate_ts_init();
4319
4320        // Take the first wallet balance from the list
4321        let wallet_balance = response
4322            .result
4323            .list
4324            .first()
4325            .ok_or_else(|| anyhow::anyhow!("No wallet balance found in response"))?;
4326
4327        parse_account_state(wallet_balance, account_id, ts_init)
4328    }
4329
4330    /// Request multiple order status reports.
4331    ///
4332    /// Orders for instruments not currently loaded in cache will be skipped.
4333    ///
4334    /// When `open_only` is true the realtime endpoint is queried for currently
4335    /// open orders and again for recently closed orders, so terminal reports
4336    /// are included. The closed pass fetches the most recent page only and is
4337    /// not constrained by `start` or `end`.
4338    ///
4339    /// # Errors
4340    ///
4341    /// Returns an error if:
4342    /// - Credentials are missing.
4343    /// - The request fails.
4344    /// - The API returns an error.
4345    #[expect(clippy::too_many_arguments)]
4346    pub async fn request_order_status_reports(
4347        &self,
4348        account_id: AccountId,
4349        product_type: BybitProductType,
4350        instrument_id: Option<InstrumentId>,
4351        open_only: bool,
4352        start: Option<Timestamp>,
4353        end: Option<Timestamp>,
4354        limit: Option<u32>,
4355    ) -> anyhow::Result<Vec<OrderStatusReport>> {
4356        // Extract symbol parameter from instrument_id if provided
4357        let symbol_param = if let Some(id) = instrument_id.as_ref() {
4358            let symbol_str = id.symbol.as_str();
4359            if symbol_str.is_empty() {
4360                None
4361            } else {
4362                Some(BybitSymbol::new(symbol_str)?.raw_symbol().to_string())
4363            }
4364        } else {
4365            None
4366        };
4367
4368        // For LINEAR without symbol, query all settle coins to avoid filtering
4369        // For INVERSE, never use settle_coin parameter
4370        let settle_coins_to_query: Vec<Option<String>> =
4371            if product_type == BybitProductType::Linear && symbol_param.is_none() {
4372                vec![Some("USDT".to_string()), Some("USDC".to_string())]
4373            } else {
4374                match product_type {
4375                    BybitProductType::Inverse => vec![None],
4376                    _ => vec![None],
4377                }
4378            };
4379
4380        let mut all_collected_orders = Vec::new();
4381        let mut total_collected_across_coins = 0;
4382
4383        for settle_coin in settle_coins_to_query {
4384            let remaining_limit = if let Some(limit) = limit {
4385                let remaining = (limit as usize).saturating_sub(total_collected_across_coins);
4386                if remaining == 0 {
4387                    break;
4388                }
4389                Some(remaining as u32)
4390            } else {
4391                None
4392            };
4393
4394            let orders_for_coin = if open_only {
4395                let mut all_orders = Vec::new();
4396                let mut seen_ids: AHashSet<Ustr> = AHashSet::new();
4397
4398                // Query regular orders then conditional (stop/MIT) orders.
4399                // Options do not support the StopOrder filter.
4400                let order_filters: Vec<Option<BybitOrderFilter>> =
4401                    if product_type == BybitProductType::Option {
4402                        vec![None]
4403                    } else {
4404                        vec![None, Some(BybitOrderFilter::StopOrder)]
4405                    };
4406
4407                let open_only_modes = [None, Some(BybitOpenOnly::ClosedRecent)];
4408
4409                for oo in open_only_modes {
4410                    for order_filter in &order_filters {
4411                        let mut cursor: Option<String> = None;
4412                        let mut cursor_walk = CursorWalk::default();
4413
4414                        loop {
4415                            let remaining = if let Some(limit) = remaining_limit {
4416                                (limit as usize).saturating_sub(all_orders.len())
4417                            } else {
4418                                usize::MAX
4419                            };
4420
4421                            if remaining == 0 {
4422                                break;
4423                            }
4424
4425                            // Max 50 per Bybit API
4426                            let page_limit = std::cmp::min(remaining, 50);
4427
4428                            let mut p = BybitOpenOrdersParamsBuilder::default();
4429                            p.category(product_type);
4430
4431                            if let Some(symbol) = symbol_param.clone() {
4432                                p.symbol(symbol);
4433                            }
4434
4435                            if let Some(coin) = settle_coin.clone() {
4436                                p.settle_coin(coin);
4437                            }
4438
4439                            if let Some(of) = order_filter {
4440                                p.order_filter(*of);
4441                            }
4442
4443                            if let Some(oo) = oo {
4444                                p.open_only(oo);
4445                            }
4446                            p.limit(page_limit as u32);
4447
4448                            if let Some(c) = cursor {
4449                                p.cursor(c);
4450                            }
4451                            let params = p.build().build_anyhow()?;
4452                            let response: BybitOpenOrdersResponse = self
4453                                .inner
4454                                .send_request(
4455                                    Method::GET,
4456                                    BYBIT_ORDER_REALTIME,
4457                                    Some(&params),
4458                                    None,
4459                                    true,
4460                                )
4461                                .await?;
4462
4463                            for order in response.result.list {
4464                                if seen_ids.insert(order.order_id) {
4465                                    all_orders.push(order);
4466                                }
4467                            }
4468
4469                            // The closed pass only needs the most recent page
4470                            if oo.is_some() {
4471                                break;
4472                            }
4473
4474                            cursor = cursor_walk
4475                                .advance(BYBIT_ORDER_REALTIME, response.result.next_page_cursor)?;
4476
4477                            if cursor.is_none() {
4478                                break;
4479                            }
4480                        }
4481                    }
4482                }
4483
4484                all_orders
4485            } else {
4486                // Query both realtime and history endpoints
4487                // Realtime has current open orders, history may lag for recent orders
4488                let mut all_orders = Vec::new();
4489                let mut open_orders = Vec::new();
4490                let mut seen_open_ids: AHashSet<Ustr> = AHashSet::new();
4491
4492                // Query regular orders then conditional (stop/MIT) orders.
4493                // Options do not support the StopOrder filter.
4494                let order_filters: Vec<Option<BybitOrderFilter>> =
4495                    if product_type == BybitProductType::Option {
4496                        vec![None]
4497                    } else {
4498                        vec![None, Some(BybitOrderFilter::StopOrder)]
4499                    };
4500
4501                for order_filter in &order_filters {
4502                    let mut cursor: Option<String> = None;
4503                    let mut cursor_walk = CursorWalk::default();
4504
4505                    loop {
4506                        let remaining = if let Some(limit) = remaining_limit {
4507                            (limit as usize).saturating_sub(open_orders.len())
4508                        } else {
4509                            usize::MAX
4510                        };
4511
4512                        if remaining == 0 {
4513                            break;
4514                        }
4515
4516                        // Max 50 per Bybit API
4517                        let page_limit = std::cmp::min(remaining, 50);
4518
4519                        let mut open_params = BybitOpenOrdersParamsBuilder::default();
4520                        open_params.category(product_type);
4521
4522                        if let Some(symbol) = symbol_param.clone() {
4523                            open_params.symbol(symbol);
4524                        }
4525
4526                        if let Some(coin) = settle_coin.clone() {
4527                            open_params.settle_coin(coin);
4528                        }
4529
4530                        if let Some(of) = order_filter {
4531                            open_params.order_filter(*of);
4532                        }
4533                        open_params.limit(page_limit as u32);
4534
4535                        if let Some(c) = cursor {
4536                            open_params.cursor(c);
4537                        }
4538                        let open_params = open_params.build().build_anyhow()?;
4539                        let open_response: BybitOpenOrdersResponse = self
4540                            .inner
4541                            .send_request(
4542                                Method::GET,
4543                                BYBIT_ORDER_REALTIME,
4544                                Some(&open_params),
4545                                None,
4546                                true,
4547                            )
4548                            .await?;
4549
4550                        for order in open_response.result.list {
4551                            if !seen_open_ids.contains(&order.order_id) {
4552                                seen_open_ids.insert(order.order_id);
4553                                open_orders.push(order);
4554                            }
4555                        }
4556
4557                        cursor = cursor_walk
4558                            .advance(BYBIT_ORDER_REALTIME, open_response.result.next_page_cursor)?;
4559
4560                        if cursor.is_none() {
4561                            break;
4562                        }
4563                    }
4564                }
4565
4566                let seen_order_ids: AHashSet<Ustr> = seen_open_ids;
4567                let total_open_orders = open_orders.len();
4568
4569                all_orders.extend(open_orders);
4570
4571                let mut total_history_orders = 0;
4572
4573                for order_filter in &order_filters {
4574                    let mut cursor: Option<String> = None;
4575                    let mut cursor_walk = CursorWalk::default();
4576
4577                    loop {
4578                        let total_orders = total_open_orders + total_history_orders;
4579                        let remaining = if let Some(limit) = remaining_limit {
4580                            (limit as usize).saturating_sub(total_orders)
4581                        } else {
4582                            usize::MAX
4583                        };
4584
4585                        if remaining == 0 {
4586                            break;
4587                        }
4588
4589                        // Max 50 per Bybit API
4590                        let page_limit = std::cmp::min(remaining, 50);
4591
4592                        let mut history_params = BybitOrderHistoryParamsBuilder::default();
4593                        history_params.category(product_type);
4594
4595                        if let Some(symbol) = symbol_param.clone() {
4596                            history_params.symbol(symbol);
4597                        }
4598
4599                        if let Some(coin) = settle_coin.clone() {
4600                            history_params.settle_coin(coin);
4601                        }
4602
4603                        if let Some(of) = order_filter {
4604                            history_params.order_filter(*of);
4605                        }
4606
4607                        if let Some(start) = start {
4608                            history_params.start_time(start.as_millisecond());
4609                        }
4610
4611                        if let Some(end) = end {
4612                            history_params.end_time(end.as_millisecond());
4613                        }
4614                        history_params.limit(page_limit as u32);
4615
4616                        if let Some(c) = cursor {
4617                            history_params.cursor(c);
4618                        }
4619                        let history_params = history_params.build().build_anyhow()?;
4620                        let history_response: BybitOrderHistoryResponse = self
4621                            .inner
4622                            .send_request(
4623                                Method::GET,
4624                                BYBIT_ORDER_HISTORY,
4625                                Some(&history_params),
4626                                None,
4627                                true,
4628                            )
4629                            .await?;
4630
4631                        // Open orders might appear in both realtime and history
4632                        for order in history_response.result.list {
4633                            if !seen_order_ids.contains(&order.order_id) {
4634                                all_orders.push(order);
4635                                total_history_orders += 1;
4636                            }
4637                        }
4638
4639                        cursor = cursor_walk.advance(
4640                            BYBIT_ORDER_HISTORY,
4641                            history_response.result.next_page_cursor,
4642                        )?;
4643
4644                        if cursor.is_none() {
4645                            break;
4646                        }
4647                    }
4648                }
4649
4650                all_orders
4651            };
4652
4653            total_collected_across_coins += orders_for_coin.len();
4654            all_collected_orders.extend(orders_for_coin);
4655        }
4656
4657        let ts_init = self.generate_ts_init();
4658
4659        let mut reports = Vec::new();
4660
4661        for order in all_collected_orders {
4662            if let Some(ref instrument_id) = instrument_id {
4663                let instrument = self.instrument_from_cache(&instrument_id.symbol)?;
4664
4665                if let Ok(report) =
4666                    parse_order_status_report(&order, &instrument, account_id, ts_init)
4667                {
4668                    reports.push(report);
4669                }
4670            } else {
4671                // Bybit returns raw symbol (e.g. "ETHUSDT"), need to add product suffix for cache lookup
4672                // Note: instruments are stored in cache by symbol only (without venue)
4673                if !order.symbol.is_empty() {
4674                    let symbol_with_product =
4675                        Symbol::from_ustr_unchecked(make_bybit_symbol(order.symbol, product_type));
4676
4677                    let Ok(instrument) = self.instrument_from_cache(&symbol_with_product) else {
4678                        log::debug!(
4679                            "Skipping order report for instrument not in cache: symbol={}, full_symbol={}",
4680                            order.symbol,
4681                            symbol_with_product
4682                        );
4683                        continue;
4684                    };
4685
4686                    match parse_order_status_report(&order, &instrument, account_id, ts_init) {
4687                        Ok(report) => reports.push(report),
4688                        Err(e) => {
4689                            log::error!("Failed to parse order status report: {e}");
4690                        }
4691                    }
4692                }
4693            }
4694        }
4695
4696        Ok(reports)
4697    }
4698
4699    /// Fetches execution history (fills) for the account and returns a list of [`FillReport`]s.
4700    ///
4701    /// Funding executions and executions for instruments not currently loaded in cache are skipped.
4702    ///
4703    /// # Errors
4704    ///
4705    /// Returns an error if:
4706    /// - The request fails.
4707    /// - The instrument ID is invalid.
4708    /// - Pagination cannot advance.
4709    /// - A fill for a cached instrument cannot be parsed.
4710    ///
4711    /// # References
4712    ///
4713    /// <https://bybit-exchange.github.io/docs/v5/order/execution>
4714    pub async fn request_fill_reports(
4715        &self,
4716        account_id: AccountId,
4717        product_type: BybitProductType,
4718        instrument_id: Option<InstrumentId>,
4719        start: Option<i64>,
4720        end: Option<i64>,
4721        limit: Option<u32>,
4722    ) -> anyhow::Result<Vec<FillReport>> {
4723        // Build query parameters
4724        let symbol = if let Some(id) = instrument_id {
4725            let bybit_symbol = BybitSymbol::new(id.symbol.as_str())?;
4726            Some(bybit_symbol.raw_symbol().to_string())
4727        } else {
4728            None
4729        };
4730
4731        // Fetch all executions with pagination
4732        let mut all_executions = Vec::new();
4733        let mut cursor: Option<String> = None;
4734        let mut cursor_walk = CursorWalk::default();
4735        let mut total_executions = 0;
4736
4737        loop {
4738            // Calculate how many more executions we can request
4739            let remaining = if let Some(limit) = limit {
4740                (limit as usize).saturating_sub(total_executions)
4741            } else {
4742                usize::MAX
4743            };
4744
4745            // If we've reached the limit, stop
4746            if remaining == 0 {
4747                break;
4748            }
4749
4750            // Size the page request to respect caller's limit (max 100 per Bybit API)
4751            let page_limit = std::cmp::min(remaining, 100);
4752
4753            let params = BybitTradeHistoryParams {
4754                category: product_type,
4755                symbol: symbol.clone(),
4756                base_coin: None,
4757                order_id: None,
4758                order_link_id: None,
4759                start_time: start,
4760                end_time: end,
4761                exec_type: None,
4762                limit: Some(page_limit as u32),
4763                cursor: cursor.clone(),
4764            };
4765
4766            let response = self.inner.get_trade_history(&params).await?;
4767            for execution in response.result.list {
4768                if execution.exec_type == BybitExecType::Funding {
4769                    log::debug!(
4770                        "Skipping funding execution: symbol={}, order_id={}, exec_id={}",
4771                        execution.symbol,
4772                        execution.order_id,
4773                        execution.exec_id,
4774                    );
4775                    continue;
4776                }
4777
4778                all_executions.push(execution);
4779                total_executions += 1;
4780            }
4781
4782            cursor = cursor_walk.advance(BYBIT_EXECUTION_LIST, response.result.next_page_cursor)?;
4783            if cursor.is_none() {
4784                break;
4785            }
4786        }
4787
4788        let ts_init = self.generate_ts_init();
4789        let mut reports = Vec::new();
4790
4791        for execution in all_executions {
4792            // Get instrument for this execution
4793            // Bybit returns raw symbol (e.g. "ETHUSDT"), need to add product suffix for cache lookup
4794            let symbol_with_product =
4795                Symbol::from_ustr_unchecked(make_bybit_symbol(execution.symbol, product_type));
4796
4797            let Ok(instrument) = self.instrument_from_cache(&symbol_with_product) else {
4798                log::debug!(
4799                    "Skipping fill report for instrument not in cache: symbol={}, full_symbol={}",
4800                    execution.symbol,
4801                    symbol_with_product
4802                );
4803                continue;
4804            };
4805
4806            let report = parse_fill_report(&execution, account_id, &instrument, ts_init)?;
4807            reports.push(report);
4808        }
4809
4810        Ok(reports)
4811    }
4812
4813    /// Fetches position information for the account and returns a list of [`PositionStatusReport`]s.
4814    ///
4815    /// Derivative position reports fail as a set if any row cannot be resolved or parsed.
4816    /// When SPOT position reports are enabled, an uncached instrument yields no report.
4817    ///
4818    /// # Errors
4819    ///
4820    /// Returns an error if:
4821    /// - The request fails.
4822    /// - The instrument ID is invalid.
4823    /// - Pagination cannot advance.
4824    /// - A derivative position row has no symbol.
4825    /// - A derivative position's instrument is not cached.
4826    /// - A derivative position row cannot be parsed.
4827    /// - SPOT position reports are enabled and no instrument is specified, because wallet balances
4828    ///   carry no pair identity.
4829    ///
4830    /// # References
4831    ///
4832    /// <https://bybit-exchange.github.io/docs/v5/position>
4833    pub async fn request_position_status_reports(
4834        &self,
4835        account_id: AccountId,
4836        product_type: BybitProductType,
4837        instrument_id: Option<InstrumentId>,
4838    ) -> anyhow::Result<Vec<PositionStatusReport>> {
4839        // Handle SPOT position reports via wallet balances if flag is enabled
4840        if product_type == BybitProductType::Spot {
4841            if self.use_spot_position_reports.load(Ordering::Relaxed) {
4842                let Some(instrument_id) = instrument_id else {
4843                    anyhow::bail!(
4844                        "SPOT wallet balances carry no pair identity and cannot be attributed for a bulk position report request"
4845                    );
4846                };
4847                return self
4848                    .generate_spot_position_reports_from_wallet(account_id, instrument_id)
4849                    .await;
4850            } else {
4851                // Return empty vector when SPOT position reports are disabled
4852                return Ok(Vec::new());
4853            }
4854        }
4855
4856        let ts_init = self.generate_ts_init();
4857        let mut reports = Vec::new();
4858
4859        // Build query parameters based on whether a specific instrument is requested
4860        let symbol = if let Some(id) = instrument_id {
4861            let symbol_str = id.symbol.as_str();
4862            if symbol_str.is_empty() {
4863                anyhow::bail!("InstrumentId symbol is empty");
4864            }
4865            let bybit_symbol = BybitSymbol::new(symbol_str)?;
4866            Some(bybit_symbol.raw_symbol().to_string())
4867        } else {
4868            None
4869        };
4870
4871        // For LINEAR category, the API requires either symbol OR settleCoin
4872        let settle_coins: &[Option<&str>] =
4873            if product_type == BybitProductType::Linear && symbol.is_none() {
4874                &[Some("USDT"), Some("USDC")]
4875            } else {
4876                &[None]
4877            };
4878
4879        for settle_coin in settle_coins {
4880            let params = BybitPositionListParams {
4881                category: product_type,
4882                symbol: symbol.clone(),
4883                base_coin: None,
4884                settle_coin: settle_coin.map(str::to_string),
4885                limit: Some(200), // Max 200 per request
4886                cursor: None,
4887            };
4888
4889            self.request_position_pages(account_id, params, ts_init, &mut reports)
4890                .await?;
4891        }
4892
4893        Ok(reports)
4894    }
4895
4896    async fn request_position_pages(
4897        &self,
4898        account_id: AccountId,
4899        mut params: BybitPositionListParams,
4900        ts_init: UnixNanos,
4901        reports: &mut Vec<PositionStatusReport>,
4902    ) -> anyhow::Result<()> {
4903        let mut cursor_walk = CursorWalk::default();
4904
4905        loop {
4906            let response = self.inner.get_positions(&params).await?;
4907
4908            for position in response.result.list {
4909                if position.symbol.is_empty() {
4910                    anyhow::bail!(
4911                        "Position symbol is empty, category={:?}, symbol={:?}, settle_coin={:?}",
4912                        params.category,
4913                        params.symbol,
4914                        params.settle_coin,
4915                    );
4916                }
4917
4918                let symbol = Symbol::new(format!(
4919                    "{}{}",
4920                    position.symbol.as_str(),
4921                    params.category.suffix()
4922                ));
4923                let instrument = self.instrument_from_cache(&symbol)?;
4924                let report =
4925                    parse_position_status_report(&position, account_id, &instrument, ts_init)
4926                        .with_context(|| format!("failed to parse position report for {symbol}"))?;
4927                reports.push(report);
4928            }
4929
4930            params.cursor =
4931                cursor_walk.advance(BYBIT_POSITION_LIST, response.result.next_page_cursor)?;
4932
4933            if params.cursor.is_none() {
4934                break;
4935            }
4936        }
4937
4938        Ok(())
4939    }
4940
4941    async fn query_order_by_id(
4942        &self,
4943        product_type: BybitProductType,
4944        order_id: &str,
4945        endpoint: &str,
4946        context: &str,
4947    ) -> anyhow::Result<BybitOrder> {
4948        let mut query_params = BybitOpenOrdersParamsBuilder::default();
4949        query_params.category(product_type);
4950        query_params.order_id(order_id.to_string());
4951
4952        let query_params = query_params.build().build_anyhow()?;
4953        let order_response: BybitOpenOrdersResponse = self
4954            .inner
4955            .send_request(Method::GET, endpoint, Some(&query_params), None, true)
4956            .await?;
4957
4958        order_response
4959            .result
4960            .list
4961            .into_iter()
4962            .next()
4963            .ok_or_else(|| anyhow::anyhow!("No order returned {context}"))
4964    }
4965}
4966
4967fn instrument_base_coin(
4968    product_type: BybitProductType,
4969    symbol: Option<&str>,
4970    base_coin: Option<Ustr>,
4971) -> Option<String> {
4972    base_coin.map(|coin| coin.to_string()).or_else(|| {
4973        (product_type == BybitProductType::Option && symbol.is_none()).then(|| "All".to_string())
4974    })
4975}
4976
4977fn instrument_or_warn(
4978    product_type: BybitProductType,
4979    symbol: Ustr,
4980    result: anyhow::Result<InstrumentAny>,
4981) -> Option<InstrumentAny> {
4982    result
4983        .inspect_err(|e| {
4984            let symbol = make_bybit_symbol(symbol, product_type);
4985            log::warn!("Failed to parse instrument {symbol}: {e}");
4986        })
4987        .ok()
4988}
4989
4990fn perp_status(status: MarketStatusAction, is_scheduled_perp: bool) -> MarketStatusAction {
4991    // A perp with a non-zero delivery time is scheduled for delisting
4992    if status == MarketStatusAction::Trading && is_scheduled_perp {
4993        MarketStatusAction::PreClose
4994    } else {
4995        status
4996    }
4997}
4998
4999#[cfg(test)]
5000mod tests {
5001    use nautilus_testkit::http::assert_http_redirect_rejected;
5002    use rstest::rstest;
5003
5004    use super::*;
5005
5006    #[tokio::test]
5007    async fn test_authenticated_client_rejects_redirects() {
5008        let client = BybitRawHttpClient::build_http_client(3, None).unwrap();
5009        assert_http_redirect_rejected(|url| async move {
5010            client
5011                .get(url, None, None, Some(3), None)
5012                .await
5013                .unwrap()
5014                .status
5015                .as_u16()
5016        })
5017        .await;
5018    }
5019
5020    #[rstest]
5021    fn test_client_creation() {
5022        let client = BybitHttpClient::new(None, 60, 3, 1000, 10_000, 5_000, None);
5023        assert!(client.is_ok());
5024
5025        let client = client.unwrap();
5026        assert!(client.base_url().contains("bybit.com"));
5027        assert!(client.credential().is_none());
5028    }
5029
5030    #[rstest]
5031    fn test_client_with_credentials() {
5032        let client = BybitHttpClient::with_credentials(
5033            "test_key".to_string(),
5034            "test_secret".to_string(),
5035            Some("https://api-testnet.bybit.com".to_string()),
5036            60,
5037            3,
5038            1000,
5039            10_000,
5040            5_000,
5041            None,
5042        );
5043        assert!(client.is_ok());
5044
5045        let client = client.unwrap();
5046        assert!(client.credential().is_some());
5047    }
5048
5049    #[rstest]
5050    fn test_build_path_with_params() {
5051        #[derive(Serialize)]
5052        struct TestParams {
5053            category: String,
5054            symbol: String,
5055        }
5056
5057        let params = TestParams {
5058            category: "linear".to_string(),
5059            symbol: "BTCUSDT".to_string(),
5060        };
5061
5062        let path = BybitRawHttpClient::build_path("/v5/market/test", &params);
5063        assert!(path.is_ok());
5064        assert!(path.unwrap().contains("category=linear"));
5065    }
5066
5067    #[rstest]
5068    fn test_build_path_without_params() {
5069        let params = ();
5070        let path = BybitRawHttpClient::build_path("/v5/market/time", &params);
5071        assert!(path.is_ok());
5072        assert_eq!(path.unwrap(), "/v5/market/time");
5073    }
5074
5075    #[rstest]
5076    fn test_params_serialization_matches_build_path() {
5077        // This test ensures our new serialization produces the same result as the old build_path
5078        #[derive(Serialize)]
5079        struct TestParams {
5080            category: String,
5081            limit: u32,
5082        }
5083
5084        let params = TestParams {
5085            category: "spot".to_string(),
5086            limit: 50,
5087        };
5088
5089        // Old way: build_path serialized params
5090        let old_path = BybitRawHttpClient::build_path(BYBIT_ORDER_REALTIME, &params).unwrap();
5091        let old_query = old_path.split('?').nth(1).unwrap_or("");
5092
5093        // New way: direct serialization
5094        let new_query = serde_urlencoded::to_string(&params).unwrap();
5095
5096        // They must match for signatures to work
5097        assert_eq!(old_query, new_query);
5098    }
5099
5100    #[rstest]
5101    fn test_params_serialization_order() {
5102        // Verify that serialization order is deterministic
5103        #[derive(Serialize)]
5104        struct OrderParams {
5105            category: String,
5106            symbol: String,
5107            limit: u32,
5108        }
5109
5110        let params = OrderParams {
5111            category: "spot".to_string(),
5112            symbol: "BTCUSDT".to_string(),
5113            limit: 50,
5114        };
5115
5116        // Serialize multiple times to ensure consistent ordering
5117        let query1 = serde_urlencoded::to_string(&params).unwrap();
5118        let query2 = serde_urlencoded::to_string(&params).unwrap();
5119        let query3 = serde_urlencoded::to_string(&params).unwrap();
5120
5121        assert_eq!(query1, query2);
5122        assert_eq!(query2, query3);
5123
5124        // The query should contain all params
5125        assert!(query1.contains("category=spot"));
5126        assert!(query1.contains("symbol=BTCUSDT"));
5127        assert!(query1.contains("limit=50"));
5128    }
5129
5130    #[rstest]
5131    #[case(403, "Access too frequent", true)]
5132    #[case(403, "Forbidden", false)]
5133    #[case(429, "Access too frequent", false)]
5134    fn test_rate_limit_403_detection(
5135        #[case] status: u16,
5136        #[case] body: &str,
5137        #[case] expected: bool,
5138    ) {
5139        assert_eq!(
5140            BybitRawHttpClient::is_rate_limit_403(status, body),
5141            expected
5142        );
5143    }
5144
5145    #[rstest]
5146    fn test_cursor_walk_stops_on_absent_or_empty_cursor() {
5147        let mut walk = CursorWalk::default();
5148
5149        assert_eq!(walk.advance("/endpoint", None).unwrap(), None);
5150        assert_eq!(
5151            walk.advance("/endpoint", Some(String::new())).unwrap(),
5152            None
5153        );
5154        assert!(walk.followed.is_empty());
5155    }
5156
5157    #[rstest]
5158    fn test_cursor_walk_follows_advancing_cursors() {
5159        let mut walk = CursorWalk::default();
5160
5161        for page in ["page-2", "page-3", "page-4"] {
5162            assert_eq!(
5163                walk.advance("/endpoint", Some(page.to_string())).unwrap(),
5164                Some(page.to_string())
5165            );
5166        }
5167    }
5168
5169    #[rstest]
5170    fn test_cursor_walk_rejects_a_cursor_that_does_not_advance() {
5171        let mut walk = CursorWalk::default();
5172        walk.advance("/endpoint", Some("page-2".to_string()))
5173            .unwrap();
5174
5175        let error = walk
5176            .advance("/endpoint", Some("page-2".to_string()))
5177            .expect_err("a cursor that addresses the page it came with has no next page");
5178
5179        assert_eq!(
5180            error.to_string(),
5181            r#"/endpoint pagination cursor did not advance from "page-2""#
5182        );
5183    }
5184
5185    #[rstest]
5186    #[case::two_cycle(vec!["page-2", "page-3"], "page-2")]
5187    #[case::long_cycle(vec!["page-2", "page-3", "page-4", "page-5"], "page-3")]
5188    fn test_cursor_walk_rejects_a_cursor_already_followed(
5189        #[case] followed: Vec<&str>,
5190        #[case] repeated: &str,
5191    ) {
5192        let mut walk = CursorWalk::default();
5193        for cursor in followed {
5194            walk.advance("/endpoint", Some(cursor.to_string())).unwrap();
5195        }
5196
5197        let error = walk
5198            .advance("/endpoint", Some(repeated.to_string()))
5199            .expect_err("a cursor already followed has no further page to offer");
5200
5201        assert_eq!(
5202            error.to_string(),
5203            format!(r#"/endpoint pagination repeated cursor "{repeated}""#)
5204        );
5205    }
5206}