Skip to main content

nautilus_okx/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 an ergonomic wrapper around the **OKX v5 REST API** -
17//! <https://www.okx.com/docs-v5/en/>.
18//!
19//! The core type exported by this module is [`OKXHttpClient`].  It offers an
20//! interface to all exchange endpoints currently required by NautilusTrader.
21//!
22//! Key responsibilities handled internally:
23//! • Request signing and header composition for private routes (HMAC-SHA256).
24//! • Rate-limiting based on the public OKX specification.
25//! • Deserialization of JSON payloads into domain models.
26//! • Conversion of raw exchange errors into the rich [`OKXHttpError`] enum.
27//!
28//! # Official Documentation
29//!
30//! | Endpoint                 | Reference                                              |
31//! |--------------------------|--------------------------------------------------------|
32//! | Market data              | <https://www.okx.com/docs-v5/en/#rest-api-market-data> |
33//! | Account & positions      | <https://www.okx.com/docs-v5/en/#rest-api-account>     |
34//! | Funding & asset balances | <https://www.okx.com/docs-v5/en/#rest-api-funding>     |
35
36use std::{
37    collections::HashMap,
38    fmt::Debug,
39    num::NonZeroU32,
40    str::FromStr,
41    sync::{
42        Arc, LazyLock, Mutex,
43        atomic::{AtomicBool, Ordering},
44    },
45    time::Duration,
46};
47
48use ahash::{AHashMap, AHashSet};
49use anyhow::Context;
50use indexmap::IndexMap;
51use jiff::Timestamp;
52use nautilus_common::{cache::InstrumentLookupError, live::dst::time};
53use nautilus_core::{
54    AtomicMap, AtomicTime, Params, UnixNanos, datetime::NANOSECONDS_IN_MILLISECOND,
55    env::get_or_env_var, string::secret::REDACTED, time::get_atomic_clock_realtime,
56};
57use nautilus_model::{
58    data::{
59        Bar, BarType, BookOrder, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate,
60        OrderBookDelta, OrderBookDeltas, TradeTick,
61        bar::{get_bar_interval_ns, get_time_bar_bounds},
62    },
63    enums::{
64        AccountType, AggregationSource, BarAggregation, BookAction, BookType, OrderSide,
65        OrderStatus, OrderType, PositionSide, RecordFlag, TimeInForce, TriggerType,
66    },
67    events::{AccountState, account::state::BALANCES_SNAPSHOT_COMPLETE_INFO_KEY},
68    identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
69    instruments::{Instrument, InstrumentAny},
70    orderbook::OrderBook,
71    reports::{FillReport, OrderStatusReport, PositionStatusReport},
72    types::{Currency, Price, Quantity},
73};
74use nautilus_network::{
75    http::{
76        HttpClient, HttpRedirectPolicy, Method, StatusCode, create_standard_nautilus_headers,
77        parse_retry_after,
78    },
79    ratelimiter::quota::Quota,
80    retry::{RetryConfig, RetryError, RetryManager},
81};
82use rust_decimal::Decimal;
83use serde::{Deserialize, Serialize, de::DeserializeOwned};
84use thiserror::Error;
85use tokio_util::sync::CancellationToken;
86use ustr::Ustr;
87
88use super::{
89    error::OKXHttpError,
90    models::{
91        OKXAccount, OKXAccountBill, OKXAccountConfiguration, OKXAmendAlgoOrderRequest,
92        OKXAmendAlgoOrderResponse, OKXAmendOrderRequest, OKXAttachAlgoOrdRequest,
93        OKXCancelAlgoOrderRequest, OKXCancelAlgoOrderResponse, OKXCancelAllSpreadOrdersRequest,
94        OKXCancelOrderRequest, OKXCancelOrderResponse, OKXCancelSpreadOrderRequest,
95        OKXEventContractEvent, OKXEventContractMarket, OKXEventContractSeries, OKXFeeRate,
96        OKXFundingRateHistory, OKXIndexTicker, OKXMarkPrice, OKXOptionSummary, OKXOrderAlgo,
97        OKXOrderBookSnapshot, OKXOrderHistory, OKXPlaceAlgoOrderRequest, OKXPlaceAlgoOrderResponse,
98        OKXPlaceOrderRequest, OKXPlaceOrderResponse, OKXPlaceSpreadOrderRequest, OKXPosition,
99        OKXPositionHistory, OKXPositionTier, OKXPriceLimit, OKXRpiOrderBookSnapshot, OKXServerTime,
100        OKXSpread, OKXSpreadOrder, OKXSpreadTrade, OKXTransactionDetail,
101    },
102    query::{
103        ActivateFeatureParams, GetAccountBillsParams, GetAlgoOrderParams,
104        GetAlgoOrderParamsBuilder, GetAlgoOrdersParams, GetAlgoOrdersParamsBuilder,
105        GetCandlesticksParams, GetCandlesticksParamsBuilder, GetEventContractEventsParams,
106        GetEventContractMarketsParams, GetEventContractSeriesParams, GetFundingRateHistoryParams,
107        GetIndexTickerParams, GetIndexTickerParamsBuilder, GetInstrumentsParams,
108        GetInstrumentsParamsBuilder, GetMarkPriceParams, GetMarkPriceParamsBuilder,
109        GetOptionSummaryParams, GetOrderBookParams, GetOrderHistoryParams,
110        GetOrderHistoryParamsBuilder, GetOrderListParams, GetOrderListParamsBuilder,
111        GetOrderParams, GetOrderParamsBuilder, GetPositionTiersParams, GetPositionsHistoryParams,
112        GetPositionsParams, GetPositionsParamsBuilder, GetPriceLimitParams,
113        GetPriceLimitParamsBuilder, GetRpiOrderBookParams, GetSpreadOrderParams,
114        GetSpreadOrderParamsBuilder, GetSpreadOrdersParams, GetSpreadOrdersParamsBuilder,
115        GetSpreadTradesParams, GetSpreadTradesParamsBuilder, GetSpreadsParams, GetTradeFeeParams,
116        GetTradesParams, GetTradesParamsBuilder, GetTransactionDetailsParams,
117        GetTransactionDetailsParamsBuilder, SetPositionModeParams, SetPositionModeParamsBuilder,
118    },
119};
120use crate::{
121    common::{
122        consts::{
123            OKX_FIELD_SCODE, OKX_FIELD_SMSG, OKX_HTTP_URL, OKX_NAUTILUS_BROKER_ID,
124            OKX_POST_ONLY_CANCEL_REASON, OKX_POST_ONLY_CANCEL_SOURCE, OKX_SUPPORTED_ORDER_TYPES,
125            okx_algo_target_currency, okx_market_target_currency, okx_reduce_only_wire_value,
126            spot_trade_quote_ccy_wire_value, validate_algo_trigger_type,
127            validate_order_time_in_force, validate_regular_order_params,
128        },
129        credential::Credential,
130        enums::{
131            OKXAlgoOrderStatus, OKXAlgoOrderType, OKXEnvironment, OKXInstrumentStatus,
132            OKXInstrumentType, OKXMarginMode, OKXOrderStatus, OKXOrderType, OKXPositionMode,
133            OKXPositionSide, OKXSide, OKXTradeMode, OKXTriggerType, conditional_order_to_algo_type,
134        },
135        models::OKXInstrument,
136        parse::{
137            extract_inst_family, is_okx_spread_symbol, is_order_status_report_more_advanced,
138            okx_instrument_type, okx_instrument_type_from_symbol,
139            parse_account_state_with_completeness, parse_base_quote_from_symbol, parse_candlestick,
140            parse_fill_report, parse_funding_rate, parse_index_price_update, parse_instrument_any,
141            parse_mark_price_update, parse_millisecond_timestamp, parse_order_status_report,
142            parse_position_status_report, parse_price, parse_quantity,
143            parse_spot_position_quantity, parse_spread_fill_report, parse_spread_instrument,
144            parse_spread_order_status_report, parse_trade_tick, prefer_rpi_response_fields,
145        },
146    },
147    http::models::{OKXCandlestick, OKXTrade},
148    websocket::{messages::OKXAlgoOrderMsg, parse::parse_algo_order_status_report},
149};
150
151const OKX_SUCCESS_CODE: &str = "0";
152const OKX_PARTIAL_SUCCESS_CODE: &str = "2";
153const RETRY_AFTER_HEADER: &str = "Retry-After";
154
155#[derive(Debug, Error)]
156#[error("Failed to parse instrument {symbol}: {source}")]
157pub(crate) struct OKXInstrumentDefinitionError {
158    symbol: String,
159    #[source]
160    source: anyhow::Error,
161}
162
163impl OKXInstrumentDefinitionError {
164    fn new(symbol: &str, source: anyhow::Error) -> Self {
165        Self {
166            symbol: symbol.to_string(),
167            source,
168        }
169    }
170}
171
172#[derive(Debug, Error)]
173#[error("Failed to parse active order report: {0}")]
174pub(crate) struct OKXActiveOrderReportError(#[source] anyhow::Error);
175
176#[derive(Debug, Error)]
177#[error("Failed to fetch pending algo order reports: {source}")]
178pub(crate) struct OKXPendingAlgoOrderReportsError {
179    #[source]
180    source: anyhow::Error,
181}
182
183impl OKXPendingAlgoOrderReportsError {
184    fn new(source: anyhow::Error) -> Self {
185        Self { source }
186    }
187}
188
189// OKX omits `data` from gateway errors such as authentication failures
190#[derive(Deserialize)]
191struct OKXErrorEnvelope {
192    code: String,
193    msg: String,
194}
195
196fn resolve_okx_error_code(response_body: &[u8], envelope_code: &str) -> String {
197    if let Ok(payload) = serde_json::from_slice::<serde_json::Value>(response_body)
198        && let Some(s_code) = payload
199            .get("data")
200            .and_then(serde_json::Value::as_array)
201            .and_then(|items| items.first())
202            .and_then(|item| item.get(OKX_FIELD_SCODE))
203            .and_then(serde_json::Value::as_str)
204    {
205        let s_code = s_code.trim();
206        if !s_code.is_empty() {
207            return s_code.to_string();
208        }
209    }
210
211    envelope_code.to_string()
212}
213
214fn resolve_okx_error_message(response_body: &[u8], top_level_msg: &str) -> String {
215    let message = top_level_msg.trim();
216    let is_generic_top_level = message.eq_ignore_ascii_case("All operations failed");
217    if !message.is_empty() && !is_generic_top_level {
218        return message.to_string();
219    }
220
221    if let Ok(payload) = serde_json::from_slice::<serde_json::Value>(response_body)
222        && let Some(first_item) = payload
223            .get("data")
224            .and_then(serde_json::Value::as_array)
225            .and_then(|items| items.first())
226    {
227        if let Some(s_msg) = first_item
228            .get(OKX_FIELD_SMSG)
229            .and_then(serde_json::Value::as_str)
230        {
231            let s_msg = s_msg.trim();
232            if !s_msg.is_empty() {
233                return s_msg.to_string();
234            }
235        }
236
237        if let Some(s_code) = first_item
238            .get(OKX_FIELD_SCODE)
239            .and_then(serde_json::Value::as_str)
240        {
241            let s_code = s_code.trim();
242            if !s_code.is_empty() {
243                return s_code.to_string();
244            }
245        }
246    }
247
248    String::new()
249}
250
251fn deserialize_okx_response<T: DeserializeOwned>(
252    response_body: &[u8],
253) -> Result<OKXResponse<T>, OKXHttpError> {
254    if response_body.is_empty() {
255        return Err(OKXHttpError::EmptyResponse);
256    }
257
258    let contains_legacy_rpi_name = [br#""elp""#.as_slice(), br#""elpMaker""#.as_slice()]
259        .iter()
260        .any(|name| {
261            response_body
262                .windows(name.len())
263                .any(|window| window == *name)
264        });
265
266    if !contains_legacy_rpi_name {
267        return serde_json::from_slice(response_body)
268            .map_err(|e| classify_response_decode_error(&e));
269    }
270
271    let mut value: serde_json::Value =
272        serde_json::from_slice(response_body).map_err(|e| classify_response_decode_error(&e))?;
273    prefer_rpi_response_fields(&mut value);
274    serde_json::from_value(value).map_err(|e| classify_response_decode_error(&e))
275}
276
277fn classify_response_decode_error(error: &serde_json::Error) -> OKXHttpError {
278    if error.is_data() {
279        OKXHttpError::ResponseDecoding(error.to_string())
280    } else {
281        OKXHttpError::MalformedResponse(error.to_string())
282    }
283}
284
285fn retry_after(headers: &HashMap<String, String>, now: Timestamp) -> Option<Duration> {
286    let value = headers.get(RETRY_AFTER_HEADER)?;
287    let delay = parse_retry_after(value, now);
288    if delay.is_none() {
289        log::warn!("Invalid OKX response header {RETRY_AFTER_HEADER}={value:?}");
290    }
291    delay
292}
293
294#[cfg(test)]
295mod tests {
296    use std::{collections::HashMap, time::Duration};
297
298    use anyhow::Context;
299    use nautilus_core::UnixNanos;
300    use nautilus_model::{
301        data::BarType,
302        identifiers::{InstrumentId, Symbol},
303        instruments::{
304            CryptoFuture, CryptoFuturesSpread, InstrumentAny,
305            stubs::{crypto_future_btcusdt, crypto_futures_spread_btc_deribit},
306        },
307    };
308    use rstest::rstest;
309    use rust_decimal::Decimal;
310    use serde::{Serialize, Serializer, ser::Error as _};
311
312    use super::{
313        Method, OKX_GLOBAL_RATE_KEY, OKXEnvironment, OKXHistoryCoverage, OKXHttpClient,
314        OKXHttpError, OKXInstrumentDefinitionError, OKXInstrumentType, OKXRawHttpClient, Timestamp,
315        Ustr, deserialize_okx_response, parse_retry_after, reconciliation_history_page_limit,
316        resolve_okx_error_code, resolve_okx_error_message,
317    };
318    use crate::http::models::OKXFeeRate;
319
320    #[rstest]
321    #[case::empty("")]
322    #[case::blank(" \t")]
323    #[tokio::test]
324    async fn test_current_report_rejects_invalid_instrument_symbol(#[case] symbol: &str) {
325        let client = OKXHttpClient::new(
326            Some("http://127.0.0.1:1".into()),
327            1,
328            0,
329            1,
330            1,
331            OKXEnvironment::Demo,
332            None,
333        )
334        .unwrap();
335
336        let Err(e) = client
337            .resolve_report_instrument(
338                Ustr::from(symbol),
339                OKXInstrumentType::Swap,
340                false,
341                true,
342                None,
343            )
344            .await
345        else {
346            panic!("invalid active report symbol must fail");
347        };
348
349        assert_eq!(e.to_string(), "invalid report instrument symbol");
350    }
351
352    #[rstest]
353    #[case::default(None, 50)]
354    #[case::disabled(Some(0), 0)]
355    #[case::below_cap(Some(49), 49)]
356    #[case::at_cap(Some(50), 50)]
357    #[case::above_cap(Some(51), 50)]
358    #[case::maximum(Some(u32::MAX), 50)]
359    fn test_reconciliation_history_page_limit(
360        #[case] max_pages: Option<u32>,
361        #[case] expected: usize,
362    ) {
363        assert_eq!(reconciliation_history_page_limit(max_pages), expected);
364    }
365
366    #[rstest]
367    fn test_is_spread_prefers_cached_future(mut crypto_future_btcusdt: CryptoFuture) {
368        let client = OKXHttpClient::default();
369        let instrument_id = InstrumentId::from("BTC-USDT_BTC-USDT-SWAP.OKX");
370        crypto_future_btcusdt.id = instrument_id;
371        crypto_future_btcusdt.raw_symbol = instrument_id.symbol;
372        let uncached = client.is_spread(instrument_id);
373
374        client.cache_instrument(InstrumentAny::CryptoFuture(crypto_future_btcusdt));
375
376        assert!(uncached);
377        assert!(!client.is_spread(instrument_id));
378    }
379
380    #[rstest]
381    fn test_is_spread_prefers_cached_spread(
382        mut crypto_futures_spread_btc_deribit: CryptoFuturesSpread,
383    ) {
384        let client = OKXHttpClient::default();
385        let instrument_id = InstrumentId::from("BTC-USD_UM_XPERP-310404.OKX");
386        crypto_futures_spread_btc_deribit.id = instrument_id;
387        crypto_futures_spread_btc_deribit.raw_symbol = Symbol::from("BTC-USD_UM_XPERP-310404");
388        let uncached = client.is_spread(instrument_id);
389
390        client.cache_instrument(InstrumentAny::CryptoFuturesSpread(
391            crypto_futures_spread_btc_deribit,
392        ));
393
394        assert!(!uncached);
395        assert!(client.is_spread(instrument_id));
396    }
397
398    struct UnserializableParams;
399
400    impl Serialize for UnserializableParams {
401        fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
402        where
403            S: Serializer,
404        {
405            Err(S::Error::custom("intentional serialization failure"))
406        }
407    }
408
409    #[rstest]
410    fn test_instrument_definition_error_survives_anyhow_context_downcast() {
411        let result: anyhow::Result<()> = Err(OKXInstrumentDefinitionError::new(
412            "USDG-SGD",
413            anyhow::anyhow!("`tick_sz` is empty"),
414        )
415        .into());
416
417        let err = result.context("fetch instrument from API").unwrap_err();
418
419        assert!(err.downcast_ref::<OKXInstrumentDefinitionError>().is_some());
420    }
421
422    #[rstest]
423    fn test_resolve_okx_error_message_prefers_detailed_s_msg_over_generic_top_level() {
424        let body = br#"{
425            "code": "1",
426            "msg": "All operations failed",
427            "data": [
428                {
429                    "sCode": "51046",
430                    "sMsg": "Test detailed failure"
431                }
432            ]
433        }"#;
434
435        assert_eq!(
436            resolve_okx_error_message(body, "All operations failed"),
437            "Test detailed failure",
438        );
439    }
440
441    #[rstest]
442    fn test_resolve_okx_error_code_prefers_item_s_code_over_envelope() {
443        let body = br#"{
444            "code": "1",
445            "msg": "All operations failed",
446            "data": [
447                {
448                    "sCode": "50013",
449                    "sMsg": "System busy, please retry later"
450                }
451            ]
452        }"#;
453
454        assert_eq!(resolve_okx_error_code(body, "1"), "50013");
455    }
456
457    #[rstest]
458    #[case("/api/v5/account/bills", 200)]
459    #[case("/api/v5/account/bills-archive", 400)]
460    fn test_account_bills_quotas(#[case] endpoint: &str, #[case] interval_ms: u64) {
461        let keys = OKXRawHttpClient::rate_limit_keys(&format!("{endpoint}?ccy=USDT"));
462        assert_eq!(keys[0].as_str(), OKX_GLOBAL_RATE_KEY);
463        assert_eq!(keys[1].as_str(), format!("okx:{endpoint}"));
464        let quota = OKXRawHttpClient::rate_limiter_quotas()
465            .into_iter()
466            .find_map(|(key, quota)| (key == keys[1].as_str()).then_some(quota))
467            .expect("account bills quota");
468
469        // Pace requests without a burst to stay within each endpoint's five-request window
470        assert_eq!(quota.burst_size().get(), 1);
471        assert_eq!(
472            quota.replenish_interval(),
473            Duration::from_millis(interval_ms)
474        );
475    }
476
477    #[rstest]
478    fn test_activate_feature_quota_fits_five_per_two_seconds() {
479        let keys = OKXRawHttpClient::rate_limit_keys("/api/v5/account/activate-feature");
480        let quota = OKXRawHttpClient::rate_limiter_quotas()
481            .into_iter()
482            .find_map(|(key, quota)| (key == keys[1].as_str()).then_some(quota))
483            .expect("activate-feature quota");
484
485        assert_eq!(quota.burst_size().get(), 2);
486        assert_eq!(quota.replenish_interval(), Duration::from_millis(500));
487    }
488
489    #[rstest]
490    fn test_rpi_response_fields_prefer_current_names_over_transition_aliases() {
491        let response = br#"{
492            "code": "0",
493            "msg": "",
494            "data": [{
495                "level": "VIP1",
496                "taker": "-0.0005",
497                "maker": "-0.0002",
498                "takerU": "-0.0005",
499                "makerU": "-0.0002",
500                "rpiMaker": "-0.00015",
501                "elpMaker": "-0.00016",
502                "instType": "SPOT",
503                "category": "1",
504                "ts": "1785406500000"
505            }]
506        }"#;
507
508        let parsed = deserialize_okx_response::<OKXFeeRate>(response).unwrap();
509
510        assert_eq!(parsed.data.len(), 1);
511        assert_eq!(parsed.data[0].rpi_maker, Some(Decimal::new(-15, 5)));
512    }
513
514    #[rstest]
515    fn test_parse_retry_after_supports_delay_seconds_and_http_date() {
516        let now: Timestamp = "1994-11-06T08:49:36Z".parse().unwrap();
517
518        assert_eq!(
519            parse_retry_after("5", now),
520            Some(std::time::Duration::from_secs(5))
521        );
522        assert_eq!(
523            parse_retry_after("Sun, 06 Nov 1994 08:51:36 GMT", now),
524            Some(std::time::Duration::from_secs(120))
525        );
526        assert_eq!(
527            parse_retry_after("Sun, 06 Nov 1994 08:47:36 GMT", now),
528            Some(std::time::Duration::ZERO)
529        );
530        assert_eq!(parse_retry_after("soon", now), None);
531    }
532
533    #[rstest]
534    fn test_empty_response_is_distinct_from_malformed_json() {
535        let empty = deserialize_okx_response::<serde_json::Value>(b"").unwrap_err();
536        let malformed = deserialize_okx_response::<serde_json::Value>(b"{").unwrap_err();
537
538        assert!(matches!(empty, OKXHttpError::EmptyResponse));
539        assert!(matches!(malformed, OKXHttpError::MalformedResponse(_)));
540    }
541
542    #[rstest]
543    #[tokio::test]
544    async fn test_request_serialization_failure_is_typed_before_transport() {
545        let client = OKXRawHttpClient::new(
546            Some("http://127.0.0.1:1".to_string()),
547            1,
548            0,
549            1,
550            1,
551            OKXEnvironment::Live,
552            None,
553        )
554        .unwrap();
555
556        let error = client
557            .send_request::<serde_json::Value, _>(
558                Method::GET,
559                "/api/v5/test",
560                Some(&UnserializableParams),
561                None,
562                false,
563            )
564            .await
565            .unwrap_err();
566
567        assert!(matches!(
568            error,
569            OKXHttpError::RequestSerialization(message)
570                if message.contains("intentional serialization failure")
571        ));
572    }
573
574    #[rstest]
575    #[case("BTC-USD")]
576    #[case("BTC-USD-241217")]
577    #[case("BTC-USD-241217-92000")]
578    fn test_option_summary_exp_time_rejects_short_symbol(#[case] symbol: &str) {
579        let result = super::OKXHttpClient::option_summary_exp_time(symbol);
580        assert!(result.is_err());
581        let err = result.unwrap_err().to_string();
582        assert!(
583            err.contains("Expected OKX option symbol with expiry"),
584            "unexpected error: {err}"
585        );
586    }
587
588    #[rstest]
589    fn test_option_summary_exp_time_extracts_expiry() {
590        let result =
591            super::OKXHttpClient::option_summary_exp_time("BTC-USD-241217-92000-C").unwrap();
592        assert_eq!(result, Some("241217".to_string()));
593    }
594
595    fn spot_instruments() -> Vec<InstrumentAny> {
596        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
597            .join("test_data")
598            .join("http_get_instruments_spot.json");
599        let response: super::OKXResponse<crate::common::models::OKXInstrument> =
600            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
601        response
602            .data
603            .iter()
604            .filter_map(|raw| {
605                crate::common::parse::parse_instrument_any(raw, None, None, UnixNanos::default())
606                    .ok()
607                    .flatten()
608            })
609            .collect()
610    }
611
612    #[rstest]
613    #[case::no_limit(None, OKXHistoryCoverage::Truncated)]
614    #[case::limit_met_on_the_last_page(Some(300), OKXHistoryCoverage::Unverified)]
615    #[tokio::test]
616    async fn test_request_trades_paged_at_the_page_cap(
617        #[case] limit: Option<u32>,
618        #[case] expected: OKXHistoryCoverage,
619    ) {
620        // One trade a millisecond: three pages reach 300 ms back, the start is a day back
621        let now_ms = Timestamp::now().as_millisecond();
622        let router = axum::Router::new().route(
623            "/api/v5/market/history-trades",
624            axum::routing::get(
625                move |axum::extract::Query(params): axum::extract::Query<
626                    HashMap<String, String>,
627                >| async move {
628                    let below = params
629                        .get("after")
630                        .and_then(|s| s.parse::<i64>().ok())
631                        .unwrap_or(1_000_001);
632                    let data: Vec<serde_json::Value> = (1..=100)
633                        .map(|i| below - i)
634                        .map(|id| {
635                            serde_json::json!({
636                                "instId": "BTC-USD",
637                                "side": "buy",
638                                "sz": "0.01",
639                                "px": "100000.0",
640                                "tradeId": id.to_string(),
641                                "ts": (now_ms - (1_000_001 - id)).to_string(),
642                            })
643                        })
644                        .collect();
645                    axum::Json(serde_json::json!({"code": "0", "msg": "", "data": data}))
646                },
647            ),
648        );
649        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
650        let addr = listener.local_addr().unwrap();
651        tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
652        let client = OKXHttpClient::new(
653            Some(format!("http://{addr}")),
654            60,
655            3,
656            1000,
657            10_000,
658            OKXEnvironment::Live,
659            None,
660        )
661        .unwrap();
662
663        for instrument in spot_instruments() {
664            client.cache_instrument(instrument);
665        }
666
667        let (trades, coverage) = client
668            .request_trades_paged(
669                InstrumentId::from("BTC-USD.OKX"),
670                Some(Timestamp::now() - jiff::SignedDuration::from_hours(24)),
671                None,
672                limit,
673                3,
674            )
675            .await
676            .unwrap();
677
678        assert_eq!(coverage, expected);
679        assert_eq!(trades.len(), 300);
680    }
681
682    #[rstest]
683    #[tokio::test]
684    async fn test_request_bars_paged_is_truncated_at_the_page_cap() {
685        // A day of minute candles, a window ten days long: two history pages of 100 cannot reach the start
686        let first: Timestamp = "2026-09-01T00:00:00Z".parse().unwrap();
687        let candles: Vec<serde_json::Value> = (0..1_440i64)
688            .rev()
689            .map(|index| {
690                let ts = first.as_millisecond() + index * 60_000;
691                serde_json::json!([
692                    ts.to_string(),
693                    "33528.6",
694                    "33870.0",
695                    "33500.1",
696                    "33783.9",
697                    "778.838",
698                    "26291398.9",
699                    "26291398.9",
700                    "1"
701                ])
702            })
703            .collect();
704        let route = axum::routing::get(
705            move |axum::extract::Query(params): axum::extract::Query<HashMap<String, String>>| {
706                let candles = candles.clone();
707                async move {
708                    let after = params.get("after").map(|v| v.parse::<i64>().unwrap());
709                    let before = params.get("before").map(|v| v.parse::<i64>().unwrap());
710                    let limit = params
711                        .get("limit")
712                        .map_or(100, |v| v.parse::<usize>().unwrap());
713                    let data: Vec<serde_json::Value> = candles
714                        .into_iter()
715                        .filter(|c| {
716                            let ts = c[0].as_str().unwrap().parse::<i64>().unwrap();
717                            after.is_none_or(|a| ts < a) && before.is_none_or(|b| ts > b)
718                        })
719                        .take(limit)
720                        .collect();
721                    axum::Json(serde_json::json!({"code": "0", "msg": "", "data": data}))
722                }
723            },
724        );
725        let router = axum::Router::new()
726            .route("/api/v5/market/candles", route.clone())
727            .route("/api/v5/market/history-candles", route);
728        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
729        let addr = listener.local_addr().unwrap();
730        tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
731        let client = OKXHttpClient::new(
732            Some(format!("http://{addr}")),
733            60,
734            3,
735            1000,
736            10_000,
737            OKXEnvironment::Live,
738            None,
739        )
740        .unwrap();
741
742        for instrument in spot_instruments() {
743            client.cache_instrument(instrument);
744        }
745
746        let (bars, coverage) = client
747            .request_bars_paged(
748                BarType::from("BTC-USD.OKX-1-MINUTE-LAST-EXTERNAL"),
749                Some(first - jiff::SignedDuration::from_hours(216)),
750                Some(first + jiff::SignedDuration::from_hours(24)),
751                None,
752                2,
753            )
754            .await
755            .unwrap();
756
757        assert_eq!(coverage, OKXHistoryCoverage::Truncated);
758        assert_eq!(bars.len(), 200);
759    }
760}
761
762/// Default OKX REST API rate limit: 500 requests per 2 seconds.
763///
764/// - Sub-account order limit: 1000 requests per 2 seconds.
765/// - Account balance: 10 requests per 2 seconds.
766/// - Account instruments: 20 requests per 2 seconds.
767///
768/// We use a conservative 250 requests per second (500 per 2 seconds) as a general limit
769/// that should accommodate most use cases while respecting OKX's documented limits.
770pub static OKX_REST_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
771    Quota::per_second(NonZeroU32::new(250).expect("non-zero")).expect("valid constant")
772});
773
774const OKX_GLOBAL_RATE_KEY: &str = "okx:global";
775
776// OKX returns at most 100 records per page for order, fill, and algo endpoints
777const OKX_PAGE_SIZE: usize = 100;
778
779// Safety cap on paginated reconciliation fetches to avoid unbounded loops
780const MAX_RECONCILIATION_PAGES: usize = 50;
781
782#[derive(Clone, Copy, Debug)]
783pub(crate) struct ReportInstrumentScope<'a> {
784    pub instrument_types: &'a [OKXInstrumentType],
785    pub load_spreads: bool,
786    pub margin_mode: Option<OKXMarginMode>,
787}
788
789impl ReportInstrumentScope<'_> {
790    pub(crate) fn validate_position_margin(&self, position: &OKXPosition) -> anyhow::Result<()> {
791        if let Some(expected) = self.margin_mode
792            && matches!(
793                position.inst_type,
794                OKXInstrumentType::Swap | OKXInstrumentType::Futures
795            )
796            && matches!(
797                position.pos_side,
798                OKXPositionSide::Long | OKXPositionSide::Short
799            )
800            && position.mgn_mode != expected
801            && !Decimal::from_str(&position.pos)?.is_zero()
802        {
803            anyhow::bail!(
804                "OKX long/short position {} uses margin mode {}, expected {expected}; mixed margin modes are not supported",
805                position.inst_id,
806                position.mgn_mode,
807            );
808        }
809
810        Ok(())
811    }
812}
813
814#[derive(Debug)]
815pub(crate) struct ReportSweep<T> {
816    pub reports: Vec<T>,
817    pub complete: bool,
818}
819
820#[derive(Clone, Copy)]
821pub(crate) enum FillHistory {
822    Recent,
823    Extended,
824}
825
826#[derive(Debug)]
827pub(crate) struct AlgoOrderReportSweep {
828    pub reports: Vec<OrderStatusReport>,
829    pub complete: bool,
830    pub ambiguous_triggered_child_ids: AHashSet<VenueOrderId>,
831}
832
833struct PageSweep<T> {
834    items: Vec<T>,
835    complete: bool,
836}
837
838impl<T> PageSweep<T> {
839    fn from_pages(items: Vec<T>, exhausted: bool) -> Self {
840        Self {
841            complete: !exhausted,
842            items,
843        }
844    }
845}
846
847enum InstrumentResolution {
848    Found(Box<InstrumentAny>),
849    Skip,
850    Incomplete,
851}
852
853/// Represents an OKX HTTP response.
854#[derive(Debug, Serialize, Deserialize)]
855pub struct OKXResponse<T> {
856    /// The OKX response code, which is `"0"` for success.
857    pub code: String,
858    /// A message string which can be informational or describe an error cause.
859    pub msg: String,
860    /// The typed data returned by the OKX endpoint.
861    pub data: Vec<T>,
862}
863
864/// Provides a raw HTTP client for interacting with the [OKX](https://okx.com) REST API.
865///
866/// This client wraps the underlying [`HttpClient`] to handle functionality
867/// specific to OKX, such as request signing (for authenticated endpoints),
868/// forming request URLs, and deserializing responses into OKX specific data models.
869pub struct OKXRawHttpClient {
870    clock: &'static AtomicTime,
871    base_url: String,
872    client: HttpClient,
873    credential: Option<Credential>,
874    retry_manager: RetryManager<OKXHttpError>,
875    cancellation_token: CancellationToken,
876    environment: OKXEnvironment,
877}
878
879impl Default for OKXRawHttpClient {
880    fn default() -> Self {
881        Self::new(None, 60, 3, 1000, 10_000, OKXEnvironment::Live, None)
882            .expect("Failed to create default OKXRawHttpClient")
883    }
884}
885
886impl Debug for OKXRawHttpClient {
887    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
888        let credential = self.credential.as_ref().map(|_| REDACTED);
889        f.debug_struct(stringify!(OKXRawHttpClient))
890            .field("base_url", &self.base_url)
891            .field("credential", &credential)
892            .finish_non_exhaustive()
893    }
894}
895
896impl OKXRawHttpClient {
897    fn rate_limiter_quotas() -> Vec<(String, Quota)> {
898        vec![
899            (OKX_GLOBAL_RATE_KEY.to_string(), *OKX_REST_QUOTA),
900            (
901                "okx:/api/v5/account/config".to_string(),
902                Quota::per_second(NonZeroU32::new(2).expect("non-zero")).expect("valid constant"),
903            ),
904            (
905                "okx:/api/v5/account/set-position-mode".to_string(),
906                Quota::per_second(NonZeroU32::new(2).expect("non-zero")).expect("valid constant"),
907            ),
908            (
909                "okx:/api/v5/account/activate-feature".to_string(),
910                Quota::per_second(NonZeroU32::new(2).expect("non-zero")).expect("valid constant"),
911            ),
912            (
913                "okx:/api/v5/account/balance".to_string(),
914                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
915            ),
916            (
917                "okx:/api/v5/account/bills".to_string(),
918                Quota::with_period(Duration::from_millis(200)).expect("valid constant"),
919            ),
920            (
921                "okx:/api/v5/account/bills-archive".to_string(),
922                Quota::with_period(Duration::from_millis(400)).expect("valid constant"),
923            ),
924            (
925                "okx:/api/v5/account/trade-fee".to_string(),
926                Quota::per_second(NonZeroU32::new(2).expect("non-zero")).expect("valid constant"),
927            ),
928            (
929                "okx:/api/v5/account/instruments".to_string(),
930                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
931            ),
932            (
933                "okx:/api/v5/account/positions".to_string(),
934                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
935            ),
936            (
937                "okx:/api/v5/account/positions-history".to_string(),
938                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
939            ),
940            (
941                "okx:/api/v5/public/instruments".to_string(),
942                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
943            ),
944            (
945                "okx:/api/v5/public/position-tiers".to_string(),
946                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
947            ),
948            (
949                "okx:/api/v5/public/event-contract/series".to_string(),
950                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
951            ),
952            (
953                "okx:/api/v5/public/event-contract/events".to_string(),
954                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
955            ),
956            (
957                "okx:/api/v5/public/event-contract/markets".to_string(),
958                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
959            ),
960            (
961                "okx:/api/v5/public/opt-summary".to_string(),
962                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
963            ),
964            (
965                "okx:/api/v5/public/time".to_string(),
966                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
967            ),
968            (
969                "okx:/api/v5/public/mark-price".to_string(),
970                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
971            ),
972            (
973                "okx:/api/v5/public/price-limit".to_string(),
974                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
975            ),
976            (
977                "okx:/api/v5/sprd/spreads".to_string(),
978                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
979            ),
980            (
981                "okx:/api/v5/sprd/order".to_string(),
982                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
983            ),
984            (
985                "okx:/api/v5/sprd/cancel-order".to_string(),
986                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
987            ),
988            (
989                "okx:/api/v5/sprd/mass-cancel".to_string(),
990                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
991            ),
992            (
993                "okx:/api/v5/sprd/orders-pending".to_string(),
994                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
995            ),
996            (
997                "okx:/api/v5/sprd/orders-history".to_string(),
998                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
999            ),
1000            (
1001                "okx:/api/v5/sprd/trades".to_string(),
1002                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
1003            ),
1004            (
1005                "okx:/api/v5/market/index-tickers".to_string(),
1006                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
1007            ),
1008            (
1009                "okx:/api/v5/market/books".to_string(),
1010                Quota::per_second(NonZeroU32::new(20).expect("non-zero")).expect("valid constant"),
1011            ),
1012            (
1013                "okx:/api/v5/market/books-rpi".to_string(),
1014                Quota::per_second(NonZeroU32::new(20).expect("non-zero")).expect("valid constant"),
1015            ),
1016            (
1017                "okx:/api/v5/market/candles".to_string(),
1018                Quota::per_second(NonZeroU32::new(20).expect("non-zero")).expect("valid constant"),
1019            ),
1020            (
1021                "okx:/api/v5/market/history-candles".to_string(),
1022                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
1023            ),
1024            (
1025                "okx:/api/v5/market/history-trades".to_string(),
1026                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
1027            ),
1028            (
1029                "okx:/api/v5/public/funding-rate-history".to_string(),
1030                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
1031            ),
1032            (
1033                "okx:/api/v5/trade/order".to_string(),
1034                Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant"),
1035            ),
1036            (
1037                "okx:/api/v5/trade/batch-orders".to_string(),
1038                Quota::per_second(NonZeroU32::new(7).expect("non-zero")).expect("valid constant"),
1039            ),
1040            (
1041                "okx:/api/v5/trade/amend-order".to_string(),
1042                Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant"),
1043            ),
1044            (
1045                "okx:/api/v5/trade/amend-batch-orders".to_string(),
1046                Quota::per_second(NonZeroU32::new(7).expect("non-zero")).expect("valid constant"),
1047            ),
1048            (
1049                "okx:/api/v5/trade/cancel-batch-orders".to_string(),
1050                Quota::per_second(NonZeroU32::new(7).expect("non-zero")).expect("valid constant"),
1051            ),
1052            (
1053                "okx:/api/v5/trade/orders-pending".to_string(),
1054                Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant"),
1055            ),
1056            (
1057                "okx:/api/v5/trade/orders-history".to_string(),
1058                Quota::per_second(NonZeroU32::new(20).expect("non-zero")).expect("valid constant"),
1059            ),
1060            (
1061                "okx:/api/v5/trade/fills".to_string(),
1062                Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant"),
1063            ),
1064            (
1065                "okx:/api/v5/trade/fills-history".to_string(),
1066                Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
1067            ),
1068            (
1069                "okx:/api/v5/trade/order-algo".to_string(),
1070                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
1071            ),
1072            (
1073                "okx:/api/v5/trade/cancel-algos".to_string(),
1074                Quota::per_second(NonZeroU32::new(1).expect("non-zero")).expect("valid constant"),
1075            ),
1076            (
1077                "okx:/api/v5/trade/cancel-advance-algos".to_string(),
1078                Quota::per_second(NonZeroU32::new(1).expect("non-zero")).expect("valid constant"),
1079            ),
1080            (
1081                "okx:/api/v5/trade/amend-algos".to_string(),
1082                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
1083            ),
1084            (
1085                "okx:/api/v5/trade/orders-algo-pending".to_string(),
1086                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
1087            ),
1088            (
1089                "okx:/api/v5/trade/orders-algo-history".to_string(),
1090                Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
1091            ),
1092        ]
1093    }
1094
1095    fn rate_limit_keys(endpoint: &str) -> Vec<Ustr> {
1096        let normalized = endpoint.split('?').next().unwrap_or(endpoint);
1097        let route = format!("okx:{normalized}");
1098
1099        vec![Ustr::from(OKX_GLOBAL_RATE_KEY), Ustr::from(route.as_str())]
1100    }
1101
1102    /// Cancel all pending HTTP requests.
1103    pub fn cancel_all_requests(&self) {
1104        self.cancellation_token.cancel();
1105    }
1106
1107    /// Get the cancellation token for this client.
1108    pub fn cancellation_token(&self) -> &CancellationToken {
1109        &self.cancellation_token
1110    }
1111
1112    /// Creates a new [`OKXHttpClient`] using the default OKX HTTP URL,
1113    /// optionally overridden with a custom base URL.
1114    ///
1115    /// This version of the client has **no credentials**, so it can only
1116    /// call publicly accessible endpoints.
1117    ///
1118    /// # Errors
1119    ///
1120    /// Returns an error if retry delays are invalid or the HTTP transport cannot be created.
1121    pub fn new(
1122        base_url: Option<String>,
1123        timeout_secs: u64,
1124        max_retries: u32,
1125        retry_delay_ms: u64,
1126        retry_delay_max_ms: u64,
1127        environment: OKXEnvironment,
1128        proxy_url: Option<String>,
1129    ) -> anyhow::Result<Self> {
1130        crate::config::validate_retry_delays(retry_delay_ms, retry_delay_max_ms)?;
1131
1132        let retry_config = RetryConfig {
1133            max_retries,
1134            initial_delay_ms: retry_delay_ms,
1135            max_delay_ms: retry_delay_max_ms,
1136            backoff_factor: 2.0,
1137            jitter_ms: 1000,
1138            operation_timeout_ms: Some(timeout_secs.saturating_mul(1_000)),
1139            immediate_first: false,
1140            max_elapsed_ms: Some(timeout_secs.saturating_mul(1_000).max(180_000)),
1141        };
1142
1143        let retry_manager = RetryManager::new(retry_config);
1144
1145        Ok(Self {
1146            clock: get_atomic_clock_realtime(),
1147            base_url: base_url.unwrap_or(OKX_HTTP_URL.to_string()),
1148            client: HttpClient::builder()
1149                .headers(Self::default_headers(environment))
1150                .header_keys(vec![RETRY_AFTER_HEADER.to_string()])
1151                .keyed_quotas(Self::rate_limiter_quotas())
1152                .default_quota(*OKX_REST_QUOTA)
1153                .timeout_secs(timeout_secs)
1154                .maybe_proxy_url(proxy_url)
1155                .build()
1156                .map_err(|e| {
1157                    OKXHttpError::ValidationError(format!("Failed to create HTTP client: {e}"))
1158                })?,
1159            credential: None,
1160            retry_manager,
1161            cancellation_token: CancellationToken::new(),
1162            environment,
1163        })
1164    }
1165
1166    /// Creates a new [`OKXHttpClient`] configured with credentials
1167    /// for authenticated requests, optionally using a custom base URL.
1168    ///
1169    /// # Errors
1170    ///
1171    /// Returns an error if retry delays are invalid or the HTTP transport cannot be created.
1172    #[expect(clippy::too_many_arguments)]
1173    pub fn with_credentials(
1174        api_key: String,
1175        api_secret: String,
1176        api_passphrase: String,
1177        base_url: String,
1178        timeout_secs: u64,
1179        max_retries: u32,
1180        retry_delay_ms: u64,
1181        retry_delay_max_ms: u64,
1182        environment: OKXEnvironment,
1183        proxy_url: Option<String>,
1184    ) -> anyhow::Result<Self> {
1185        crate::config::validate_retry_delays(retry_delay_ms, retry_delay_max_ms)?;
1186
1187        let retry_config = RetryConfig {
1188            max_retries,
1189            initial_delay_ms: retry_delay_ms,
1190            max_delay_ms: retry_delay_max_ms,
1191            backoff_factor: 2.0,
1192            jitter_ms: 1000,
1193            operation_timeout_ms: Some(timeout_secs.saturating_mul(1_000)),
1194            immediate_first: false,
1195            max_elapsed_ms: Some(timeout_secs.saturating_mul(1_000).max(180_000)),
1196        };
1197
1198        let retry_manager = RetryManager::new(retry_config);
1199
1200        Ok(Self {
1201            clock: get_atomic_clock_realtime(),
1202            base_url,
1203            client: HttpClient::builder()
1204                .redirect_policy(HttpRedirectPolicy::Reject)
1205                .headers(Self::default_headers(environment))
1206                .header_keys(vec![RETRY_AFTER_HEADER.to_string()])
1207                .keyed_quotas(Self::rate_limiter_quotas())
1208                .default_quota(*OKX_REST_QUOTA)
1209                .timeout_secs(timeout_secs)
1210                .maybe_proxy_url(proxy_url)
1211                .build()
1212                .map_err(|e| {
1213                    OKXHttpError::ValidationError(format!("Failed to create HTTP client: {e}"))
1214                })?,
1215            credential: Some(Credential::new(api_key, api_secret, api_passphrase)),
1216            retry_manager,
1217            cancellation_token: CancellationToken::new(),
1218            environment,
1219        })
1220    }
1221
1222    /// Builds the default headers to include with each request (e.g., `User-Agent`).
1223    fn default_headers(environment: OKXEnvironment) -> HashMap<String, String> {
1224        let mut headers: HashMap<String, String> =
1225            create_standard_nautilus_headers().into_iter().collect();
1226
1227        if environment == OKXEnvironment::Demo {
1228            headers.insert("x-simulated-trading".to_string(), "1".to_string());
1229        }
1230
1231        headers
1232    }
1233
1234    /// Signs an OKX request with timestamp, API key, passphrase, and signature.
1235    ///
1236    /// # Errors
1237    ///
1238    /// Returns an error if no credentials are set but the request requires authentication.
1239    fn sign_request(
1240        &self,
1241        method: &Method,
1242        path: &str,
1243        body: Option<&[u8]>,
1244        now: Timestamp,
1245    ) -> Result<HashMap<String, String>, OKXHttpError> {
1246        let credential = match self.credential.as_ref() {
1247            Some(c) => c,
1248            None => return Err(OKXHttpError::MissingCredentials),
1249        };
1250
1251        let api_key = credential.api_key().to_string();
1252        let api_passphrase = credential.api_passphrase().to_string();
1253
1254        // OKX requires milliseconds in the timestamp (ISO 8601 with milliseconds)
1255        let timestamp = format!("{now:.3}");
1256        let signature = credential.sign_bytes(&timestamp, method.as_str(), path, body);
1257
1258        let mut headers = HashMap::new();
1259        headers.insert("OK-ACCESS-KEY".to_string(), api_key);
1260        headers.insert("OK-ACCESS-PASSPHRASE".to_string(), api_passphrase);
1261        headers.insert("OK-ACCESS-TIMESTAMP".to_string(), timestamp);
1262        headers.insert("OK-ACCESS-SIGN".to_string(), signature);
1263
1264        Ok(headers)
1265    }
1266
1267    /// Sends an HTTP request to OKX and parses the response into `Vec<T>`.
1268    ///
1269    /// Internally, this method handles:
1270    /// - Building the URL from `base_url` + `path`.
1271    /// - Optionally signing the request.
1272    /// - Deserializing JSON responses into typed models, or returning a [`OKXHttpError`].
1273    /// - Retrying with exponential backoff on transient errors.
1274    ///
1275    /// # Errors
1276    ///
1277    /// Returns an error if:
1278    /// - The HTTP request fails.
1279    /// - Authentication is required but credentials are missing.
1280    /// - The response cannot be deserialized into the expected type.
1281    /// - The OKX API returns an error response.
1282    async fn send_request<T: DeserializeOwned, P: Serialize>(
1283        &self,
1284        method: Method,
1285        path: &str,
1286        params: Option<&P>,
1287        body: Option<Vec<u8>>,
1288        authenticate: bool,
1289    ) -> Result<Vec<T>, OKXHttpError> {
1290        let query_string = params
1291            .map(serde_urlencoded::to_string)
1292            .transpose()
1293            .map_err(|e| {
1294                OKXHttpError::RequestSerialization(format!("Failed to serialize params: {e}"))
1295            })?
1296            .unwrap_or_default();
1297        let full_path = if query_string.is_empty() {
1298            path.to_string()
1299        } else {
1300            format!("{path}?{query_string}")
1301        };
1302        let url = format!("{}{full_path}", self.base_url);
1303        let accepts_partial_success = matches!(
1304            path,
1305            "/api/v5/trade/batch-orders"
1306                | "/api/v5/trade/amend-batch-orders"
1307                | "/api/v5/trade/cancel-batch-orders"
1308        );
1309
1310        // Pre-compute rate limit keys once outside the retry closure
1311        let rate_keys: Vec<String> = Self::rate_limit_keys(path)
1312            .into_iter()
1313            .map(|k| k.to_string())
1314            .collect();
1315
1316        let operation = || {
1317            let url = url.clone();
1318            let method = method.clone();
1319            let body = body.clone();
1320            let rate_keys = rate_keys.clone();
1321            let full_path = full_path.clone();
1322
1323            async move {
1324                let mut headers = if authenticate {
1325                    let now = self.clock.get_time_ns().to_datetime_utc();
1326                    self.sign_request(&method, &full_path, body.as_deref(), now)?
1327                } else {
1328                    HashMap::new()
1329                };
1330
1331                // Always set Content-Type header when body is present
1332                if body.is_some() {
1333                    headers.insert("Content-Type".to_string(), "application/json".to_string());
1334                }
1335
1336                let resp = self
1337                    .client
1338                    .request_with_params::<()>(
1339                        method.clone(),
1340                        url,
1341                        None,
1342                        Some(headers),
1343                        body,
1344                        None,
1345                        Some(rate_keys),
1346                    )
1347                    .await?;
1348
1349                log::trace!("Response: {resp:?}");
1350                let now = self.clock.get_time_ns().to_datetime_utc();
1351                let retry_after = retry_after(&resp.headers, now);
1352
1353                if resp.status.is_success() {
1354                    let okx_response: OKXResponse<T> = deserialize_okx_response(&resp.body)?;
1355
1356                    if okx_response.code != OKX_SUCCESS_CODE
1357                        && !(accepts_partial_success
1358                            && okx_response.code == OKX_PARTIAL_SUCCESS_CODE)
1359                    {
1360                        let error_code = resolve_okx_error_code(&resp.body, &okx_response.code);
1361                        let message = resolve_okx_error_message(&resp.body, &okx_response.msg);
1362                        return Err(OKXHttpError::from_venue_response(
1363                            error_code,
1364                            message,
1365                            retry_after,
1366                        ));
1367                    }
1368
1369                    Ok(okx_response.data)
1370                } else {
1371                    let status = StatusCode::from_u16(resp.status.as_u16())
1372                        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1373                    let error_body = String::from_utf8_lossy(&resp.body);
1374                    if status == StatusCode::NOT_FOUND {
1375                        log::debug!("HTTP 404 with body: {error_body}");
1376                    } else {
1377                        log::debug!(
1378                            "HTTP error {} with body: {error_body}",
1379                            resp.status.as_str()
1380                        );
1381                    }
1382
1383                    if let Ok(envelope) = serde_json::from_slice::<OKXErrorEnvelope>(&resp.body) {
1384                        let error_code = resolve_okx_error_code(&resp.body, &envelope.code);
1385                        let message = resolve_okx_error_message(&resp.body, &envelope.msg);
1386                        return Err(OKXHttpError::from_venue_response(
1387                            error_code,
1388                            message,
1389                            retry_after,
1390                        ));
1391                    }
1392
1393                    if status.as_u16() >= 500 || status == StatusCode::TOO_MANY_REQUESTS {
1394                        Err(OKXHttpError::RetryableStatus {
1395                            status,
1396                            body: error_body.to_string(),
1397                            retry_after,
1398                        })
1399                    } else {
1400                        Err(OKXHttpError::UnexpectedStatus {
1401                            status,
1402                            body: error_body.to_string(),
1403                        })
1404                    }
1405                }
1406            }
1407        };
1408
1409        // Retry strategy based on OKX error responses and HTTP status codes:
1410        //
1411        // 1. Network errors: always retry (transient connection issues)
1412        // 2. Undecoded HTTP 5xx/429: server errors and rate limiting should be retried
1413        // 3. OKX specific retryable error codes (defined in common::consts)
1414        //
1415        // Note: OKX returns many permanent errors which should NOT be retried
1416        // (e.g., "Invalid instrument", "Insufficient balance", "Invalid API Key")
1417        //
1418        // Submit POSTs are exempt: OKX rejects a duplicate `clOrdId` only while
1419        // the first order rests open, so an attempt whose response was lost can
1420        // already have filled and freed the client order ID. Retrying could then
1421        // place a second live order, so submits are sent once and an ambiguous
1422        // outcome is left for stream updates and reconciliation to resolve.
1423        // Algo amendments also run once: a retry can reject after an earlier
1424        // attempt applied and the order triggered, leaving the original outcome ambiguous.
1425        // Cancel retries can reject after the first attempt applied, obscuring its outcome.
1426        let is_order_mutation = method == Method::POST
1427            && matches!(
1428                path,
1429                "/api/v5/trade/order"
1430                    | "/api/v5/trade/batch-orders"
1431                    | "/api/v5/trade/order-algo"
1432                    | "/api/v5/trade/amend-algos"
1433                    | "/api/v5/trade/cancel-algos"
1434                    | "/api/v5/trade/cancel-advance-algos"
1435                    | "/api/v5/sprd/order"
1436                    | "/api/v5/sprd/cancel-order"
1437                    | "/api/v5/sprd/mass-cancel"
1438            );
1439        let should_retry = |error: &OKXHttpError| !is_order_mutation && error.is_retryable();
1440
1441        let create_error = |error: RetryError| -> OKXHttpError {
1442            match error {
1443                RetryError::Canceled => {
1444                    OKXHttpError::Canceled("Adapter disconnecting or shutting down".to_string())
1445                }
1446                RetryError::OperationTimeout { timeout_ms } => {
1447                    OKXHttpError::OperationTimeout { timeout_ms }
1448                }
1449                RetryError::InvalidConfiguration { message } => {
1450                    OKXHttpError::ValidationError(message)
1451                }
1452                error @ RetryError::ElapsedBudgetExceeded { .. } => {
1453                    OKXHttpError::RetryBudgetExceeded(error.to_string())
1454                }
1455            }
1456        };
1457
1458        self.retry_manager
1459            .invocation(path, operation, should_retry, create_error)
1460            .retry_delay(&OKXHttpError::retry_after)
1461            .cancellation_token(&self.cancellation_token)
1462            .execute()
1463            .await
1464    }
1465
1466    /// Sets the position mode for an account.
1467    ///
1468    /// # Errors
1469    ///
1470    /// Returns an error if JSON serialization of `params` fails, if the HTTP
1471    /// request fails, or if the response body cannot be deserialized.
1472    ///
1473    /// # References
1474    ///
1475    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-set-position-mode>
1476    pub async fn set_position_mode(
1477        &self,
1478        params: SetPositionModeParams,
1479    ) -> Result<Vec<serde_json::Value>, OKXHttpError> {
1480        let path = "/api/v5/account/set-position-mode";
1481        let body = serde_json::to_vec(&params)?;
1482        self.send_request::<_, ()>(Method::POST, path, None, Some(body), true)
1483            .await
1484    }
1485
1486    /// Activates an account feature such as USDC order book trading.
1487    ///
1488    /// This method does not run implicitly. Call it only after order placement
1489    /// returns error code `54109`. Activation is shared between a master account and
1490    /// its sub-accounts, so one successful call covers all of them. Error code
1491    /// `51773` means the account does not support activation, not that USDC trading
1492    /// is unavailable.
1493    ///
1494    /// # Errors
1495    ///
1496    /// Returns an error if JSON serialization of `params` fails, if the HTTP
1497    /// request fails, or if the response body cannot be deserialized.
1498    ///
1499    /// # References
1500    ///
1501    /// <https://www.okx.com/docs-v5/log_en/#upcoming-changes-okx-to-migrate-usd-spot-trading-pairs-new-endpoint-activate-usdc-trading>
1502    pub async fn activate_feature(
1503        &self,
1504        params: ActivateFeatureParams,
1505    ) -> Result<Vec<serde_json::Value>, OKXHttpError> {
1506        let path = "/api/v5/account/activate-feature";
1507        let body = serde_json::to_vec(&params)?;
1508        self.send_request::<_, ()>(Method::POST, path, None, Some(body), true)
1509            .await
1510    }
1511
1512    /// Requests position tiers information, maximum leverage depends on your borrowings and margin ratio.
1513    ///
1514    /// # Errors
1515    ///
1516    /// Returns an error if the HTTP request fails, authentication is rejected
1517    /// or the response cannot be deserialized.
1518    ///
1519    /// # References
1520    ///
1521    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-position-tiers>
1522    pub async fn get_position_tiers(
1523        &self,
1524        params: GetPositionTiersParams,
1525    ) -> Result<Vec<OKXPositionTier>, OKXHttpError> {
1526        self.send_request(
1527            Method::GET,
1528            "/api/v5/public/position-tiers",
1529            Some(&params),
1530            None,
1531            false,
1532        )
1533        .await
1534    }
1535
1536    /// Requests a list of instruments with open contracts.
1537    ///
1538    /// # Errors
1539    ///
1540    /// Returns an error if JSON serialization of `params` fails, if the HTTP
1541    /// request fails, or if the response body cannot be deserialized.
1542    ///
1543    /// # References
1544    ///
1545    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-instruments>
1546    pub async fn get_instruments(
1547        &self,
1548        params: GetInstrumentsParams,
1549    ) -> Result<Vec<OKXInstrument>, OKXHttpError> {
1550        self.send_request(
1551            Method::GET,
1552            "/api/v5/public/instruments",
1553            Some(&params),
1554            None,
1555            false,
1556        )
1557        .await
1558    }
1559
1560    /// Requests account instrument configuration and trading permissions.
1561    ///
1562    /// # Errors
1563    ///
1564    /// Returns an error if authentication fails, the HTTP request fails, or the
1565    /// response cannot be deserialized.
1566    ///
1567    /// # References
1568    ///
1569    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-instruments>
1570    pub async fn get_account_instruments(
1571        &self,
1572        params: GetInstrumentsParams,
1573    ) -> Result<Vec<OKXInstrument>, OKXHttpError> {
1574        self.send_request(
1575            Method::GET,
1576            "/api/v5/account/instruments",
1577            Some(&params),
1578            None,
1579            true,
1580        )
1581        .await
1582    }
1583
1584    /// Requests a list of spread trading instruments.
1585    ///
1586    /// # Errors
1587    ///
1588    /// Returns an error if the HTTP request fails or if the response body cannot
1589    /// be deserialized.
1590    ///
1591    /// # References
1592    ///
1593    /// <https://www.okx.com/docs-v5/en/#spread-trading-rest-api-get-spreads-public>
1594    pub async fn get_spreads(
1595        &self,
1596        params: GetSpreadsParams,
1597    ) -> Result<Vec<OKXSpread>, OKXHttpError> {
1598        self.send_request(
1599            Method::GET,
1600            "/api/v5/sprd/spreads",
1601            Some(&params),
1602            None,
1603            false,
1604        )
1605        .await
1606    }
1607
1608    /// Places a spread order.
1609    ///
1610    /// # Errors
1611    ///
1612    /// Returns an error if the request fails or the response cannot be deserialized.
1613    ///
1614    /// # References
1615    ///
1616    /// <https://www.okx.com/docs-v5/en/#spread-trading-rest-api-post-place-order>
1617    pub async fn place_spread_order(
1618        &self,
1619        request: OKXPlaceSpreadOrderRequest,
1620    ) -> Result<Vec<OKXPlaceOrderResponse>, OKXHttpError> {
1621        let request = OKXPlaceSpreadOrderRequest {
1622            tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
1623            ..request
1624        };
1625
1626        let body = serde_json::to_vec(&request)?;
1627
1628        self.send_request(
1629            Method::POST,
1630            "/api/v5/sprd/order",
1631            None::<&()>,
1632            Some(body),
1633            true,
1634        )
1635        .await
1636    }
1637
1638    /// Cancels a spread order.
1639    ///
1640    /// # Errors
1641    ///
1642    /// Returns an error if the request fails or the response cannot be deserialized.
1643    ///
1644    /// # References
1645    ///
1646    /// <https://www.okx.com/docs-v5/en/#spread-trading-rest-api-post-cancel-order>
1647    pub async fn cancel_spread_order(
1648        &self,
1649        request: OKXCancelSpreadOrderRequest,
1650    ) -> Result<Vec<OKXCancelOrderResponse>, OKXHttpError> {
1651        let body = serde_json::to_vec(&request)?;
1652
1653        self.send_request(
1654            Method::POST,
1655            "/api/v5/sprd/cancel-order",
1656            None::<&()>,
1657            Some(body),
1658            true,
1659        )
1660        .await
1661    }
1662
1663    /// Cancels all orders for a spread.
1664    ///
1665    /// # Errors
1666    ///
1667    /// Returns an error if the request fails or the response cannot be deserialized.
1668    ///
1669    /// # References
1670    ///
1671    /// <https://www.okx.com/docs-v5/en/#spread-trading-rest-api-post-mass-cancel>
1672    pub async fn cancel_all_spread_orders(
1673        &self,
1674        request: OKXCancelAllSpreadOrdersRequest,
1675    ) -> Result<Vec<OKXCancelOrderResponse>, OKXHttpError> {
1676        let body = serde_json::to_vec(&request)?;
1677
1678        self.send_request(
1679            Method::POST,
1680            "/api/v5/sprd/mass-cancel",
1681            None::<&()>,
1682            Some(body),
1683            true,
1684        )
1685        .await
1686    }
1687
1688    /// Requests spread order details.
1689    ///
1690    /// # Errors
1691    ///
1692    /// Returns an error if the request fails or the response cannot be deserialized.
1693    ///
1694    /// # References
1695    ///
1696    /// <https://www.okx.com/docs-v5/en/#spread-trading-rest-api-get-order-details>
1697    pub async fn get_spread_order(
1698        &self,
1699        params: GetSpreadOrderParams,
1700    ) -> Result<Vec<OKXSpreadOrder>, OKXHttpError> {
1701        self.send_request(Method::GET, "/api/v5/sprd/order", Some(&params), None, true)
1702            .await
1703    }
1704
1705    /// Requests pending spread orders.
1706    ///
1707    /// # Errors
1708    ///
1709    /// Returns an error if the request fails or the response cannot be deserialized.
1710    ///
1711    /// # References
1712    ///
1713    /// <https://www.okx.com/docs-v5/en/#spread-trading-rest-api-get-active-orders>
1714    pub async fn get_spread_orders_pending(
1715        &self,
1716        params: GetSpreadOrdersParams,
1717    ) -> Result<Vec<OKXSpreadOrder>, OKXHttpError> {
1718        self.send_request(
1719            Method::GET,
1720            "/api/v5/sprd/orders-pending",
1721            Some(&params),
1722            None,
1723            true,
1724        )
1725        .await
1726    }
1727
1728    /// Requests historical spread orders.
1729    ///
1730    /// # Errors
1731    ///
1732    /// Returns an error if the request fails or the response cannot be deserialized.
1733    ///
1734    /// # References
1735    ///
1736    /// <https://www.okx.com/docs-v5/en/#spread-trading-rest-api-get-orders-history-last-3-months>
1737    pub async fn get_spread_orders_history(
1738        &self,
1739        params: GetSpreadOrdersParams,
1740    ) -> Result<Vec<OKXSpreadOrder>, OKXHttpError> {
1741        self.send_request(
1742            Method::GET,
1743            "/api/v5/sprd/orders-history",
1744            Some(&params),
1745            None,
1746            true,
1747        )
1748        .await
1749    }
1750
1751    /// Requests spread trades.
1752    ///
1753    /// # Errors
1754    ///
1755    /// Returns an error if the request fails or the response cannot be deserialized.
1756    ///
1757    /// # References
1758    ///
1759    /// <https://www.okx.com/docs-v5/en/#spread-trading-rest-api-get-trades-last-7-days>
1760    pub async fn get_spread_trades(
1761        &self,
1762        params: GetSpreadTradesParams,
1763    ) -> Result<Vec<OKXSpreadTrade>, OKXHttpError> {
1764        self.send_request(
1765            Method::GET,
1766            "/api/v5/sprd/trades",
1767            Some(&params),
1768            None,
1769            true,
1770        )
1771        .await
1772    }
1773
1774    /// Requests OKX event contract series.
1775    ///
1776    /// # Errors
1777    ///
1778    /// Returns an error if the HTTP request fails or the response cannot be deserialized.
1779    ///
1780    /// # References
1781    ///
1782    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-series>.
1783    pub async fn get_event_contract_series(
1784        &self,
1785        params: GetEventContractSeriesParams,
1786    ) -> Result<Vec<OKXEventContractSeries>, OKXHttpError> {
1787        self.send_request(
1788            Method::GET,
1789            "/api/v5/public/event-contract/series",
1790            Some(&params),
1791            None,
1792            false,
1793        )
1794        .await
1795    }
1796
1797    /// Requests OKX event contract events for a series.
1798    ///
1799    /// # Errors
1800    ///
1801    /// Returns an error if the HTTP request fails or the response cannot be deserialized.
1802    ///
1803    /// # References
1804    ///
1805    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-events>.
1806    pub async fn get_event_contract_events(
1807        &self,
1808        params: GetEventContractEventsParams,
1809    ) -> Result<Vec<OKXEventContractEvent>, OKXHttpError> {
1810        self.send_request(
1811            Method::GET,
1812            "/api/v5/public/event-contract/events",
1813            Some(&params),
1814            None,
1815            false,
1816        )
1817        .await
1818    }
1819
1820    /// Requests OKX event contract markets for a series.
1821    ///
1822    /// # Errors
1823    ///
1824    /// Returns an error if the HTTP request fails or the response cannot be deserialized.
1825    ///
1826    /// # References
1827    ///
1828    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-markets>.
1829    pub async fn get_event_contract_markets(
1830        &self,
1831        params: GetEventContractMarketsParams,
1832    ) -> Result<Vec<OKXEventContractMarket>, OKXHttpError> {
1833        self.send_request(
1834            Method::GET,
1835            "/api/v5/public/event-contract/markets",
1836            Some(&params),
1837            None,
1838            false,
1839        )
1840        .await
1841    }
1842
1843    /// Requests option market data for an instrument family.
1844    ///
1845    /// # Errors
1846    ///
1847    /// Returns an error if the HTTP request fails or the response cannot be deserialized.
1848    ///
1849    /// # References
1850    ///
1851    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-option-market-data>
1852    pub async fn get_option_summary(
1853        &self,
1854        params: GetOptionSummaryParams,
1855    ) -> Result<Vec<OKXOptionSummary>, OKXHttpError> {
1856        self.send_request(
1857            Method::GET,
1858            "/api/v5/public/opt-summary",
1859            Some(&params),
1860            None,
1861            false,
1862        )
1863        .await
1864    }
1865
1866    /// Requests the current server time from OKX.
1867    ///
1868    /// Retrieves the OKX system time in Unix timestamp (milliseconds). This is useful for
1869    /// synchronizing local clocks with the exchange server and logging time drift.
1870    ///
1871    /// # Errors
1872    ///
1873    /// Returns an error if the HTTP request fails or if the response body
1874    /// cannot be parsed into [`OKXServerTime`].
1875    ///
1876    /// # References
1877    ///
1878    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-system-time>
1879    pub async fn get_server_time(&self) -> Result<u64, OKXHttpError> {
1880        let response: Vec<OKXServerTime> = self
1881            .send_request::<_, ()>(Method::GET, "/api/v5/public/time", None, None, false)
1882            .await?;
1883        response
1884            .first()
1885            .map(|t| t.ts)
1886            .ok_or(OKXHttpError::EmptyResponse)
1887    }
1888
1889    /// Requests a mark price.
1890    ///
1891    /// We set the mark price based on the SPOT index and at a reasonable basis to prevent individual
1892    /// users from manipulating the market and causing the contract price to fluctuate.
1893    ///
1894    /// # Errors
1895    ///
1896    /// Returns an error if the HTTP request fails or if the response body
1897    /// cannot be parsed into [`OKXMarkPrice`].
1898    ///
1899    /// # References
1900    ///
1901    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-mark-price>
1902    pub async fn get_mark_price(
1903        &self,
1904        params: GetMarkPriceParams,
1905    ) -> Result<Vec<OKXMarkPrice>, OKXHttpError> {
1906        self.send_request(
1907            Method::GET,
1908            "/api/v5/public/mark-price",
1909            Some(&params),
1910            None,
1911            false,
1912        )
1913        .await
1914    }
1915
1916    /// Requests the current price limits for an instrument.
1917    ///
1918    /// # Errors
1919    ///
1920    /// Returns an error if the HTTP request fails or if the response body
1921    /// cannot be parsed into [`OKXPriceLimit`].
1922    ///
1923    /// # References
1924    ///
1925    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-limit-price>
1926    pub async fn get_price_limit(
1927        &self,
1928        params: GetPriceLimitParams,
1929    ) -> Result<Vec<OKXPriceLimit>, OKXHttpError> {
1930        self.send_request(
1931            Method::GET,
1932            "/api/v5/public/price-limit",
1933            Some(&params),
1934            None,
1935            false,
1936        )
1937        .await
1938    }
1939
1940    /// Requests the latest index price.
1941    ///
1942    /// # Errors
1943    ///
1944    /// Returns an error if the operation fails.
1945    ///
1946    /// # References
1947    ///
1948    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-index-tickers>
1949    pub async fn get_index_tickers(
1950        &self,
1951        params: GetIndexTickerParams,
1952    ) -> Result<Vec<OKXIndexTicker>, OKXHttpError> {
1953        self.send_request(
1954            Method::GET,
1955            "/api/v5/market/index-tickers",
1956            Some(&params),
1957            None,
1958            false,
1959        )
1960        .await
1961    }
1962
1963    /// Requests trades history.
1964    ///
1965    /// # Errors
1966    ///
1967    /// Returns an error if the operation fails.
1968    ///
1969    /// # References
1970    ///
1971    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-trades-history>
1972    pub async fn get_history_trades(
1973        &self,
1974        params: GetTradesParams,
1975    ) -> Result<Vec<OKXTrade>, OKXHttpError> {
1976        self.send_request(
1977            Method::GET,
1978            "/api/v5/market/history-trades",
1979            Some(&params),
1980            None,
1981            false,
1982        )
1983        .await
1984    }
1985
1986    /// Requests order book snapshot.
1987    ///
1988    /// # Errors
1989    ///
1990    /// Returns an error if the operation fails.
1991    ///
1992    /// # References
1993    ///
1994    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-order-book>
1995    pub async fn get_order_book(
1996        &self,
1997        params: GetOrderBookParams,
1998    ) -> Result<Vec<OKXOrderBookSnapshot>, OKXHttpError> {
1999        self.send_request(
2000            Method::GET,
2001            "/api/v5/market/books",
2002            Some(&params),
2003            None,
2004            false,
2005        )
2006        .await
2007    }
2008
2009    /// Requests a Retail Price Improvement order book snapshot.
2010    ///
2011    /// # Errors
2012    ///
2013    /// Returns an error if the operation fails.
2014    ///
2015    /// # References
2016    ///
2017    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-rpi-order-book>
2018    pub async fn get_rpi_order_book(
2019        &self,
2020        params: GetRpiOrderBookParams,
2021    ) -> Result<Vec<OKXRpiOrderBookSnapshot>, OKXHttpError> {
2022        self.send_request(
2023            Method::GET,
2024            "/api/v5/market/books-rpi",
2025            Some(&params),
2026            None,
2027            false,
2028        )
2029        .await
2030    }
2031
2032    /// Requests funding rate history.
2033    ///
2034    /// # Errors
2035    ///
2036    /// Returns an error if the operation fails.
2037    ///
2038    /// # References
2039    ///
2040    /// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate-history>
2041    pub async fn get_funding_rate_history(
2042        &self,
2043        params: GetFundingRateHistoryParams,
2044    ) -> Result<Vec<OKXFundingRateHistory>, OKXHttpError> {
2045        self.send_request(
2046            Method::GET,
2047            "/api/v5/public/funding-rate-history",
2048            Some(&params),
2049            None,
2050            false,
2051        )
2052        .await
2053    }
2054
2055    /// Requests recent candlestick data.
2056    ///
2057    /// # Errors
2058    ///
2059    /// Returns an error if the operation fails.
2060    ///
2061    /// # References
2062    ///
2063    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks>
2064    pub async fn get_candles(
2065        &self,
2066        params: GetCandlesticksParams,
2067    ) -> Result<Vec<OKXCandlestick>, OKXHttpError> {
2068        self.send_request(
2069            Method::GET,
2070            "/api/v5/market/candles",
2071            Some(&params),
2072            None,
2073            false,
2074        )
2075        .await
2076    }
2077
2078    /// Requests historical candlestick data.
2079    ///
2080    /// # Errors
2081    ///
2082    /// Returns an error if the operation fails.
2083    ///
2084    /// # References
2085    ///
2086    /// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks-history>
2087    pub async fn get_history_candles(
2088        &self,
2089        params: GetCandlesticksParams,
2090    ) -> Result<Vec<OKXCandlestick>, OKXHttpError> {
2091        self.send_request(
2092            Method::GET,
2093            "/api/v5/market/history-candles",
2094            Some(&params),
2095            None,
2096            false,
2097        )
2098        .await
2099    }
2100
2101    /// Requests the authenticated account's configuration.
2102    ///
2103    /// Returns the response data array, which is empty if OKX returns no configuration.
2104    /// This query exposes exchange configuration without applying account or permission policy.
2105    ///
2106    /// # Errors
2107    ///
2108    /// Returns an error if credentials are missing, the request fails, OKX returns an error,
2109    /// or required configuration fields are missing or invalid.
2110    ///
2111    /// # References
2112    ///
2113    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-account-configuration>
2114    pub async fn get_account_configuration(
2115        &self,
2116    ) -> Result<Vec<OKXAccountConfiguration>, OKXHttpError> {
2117        let path = "/api/v5/account/config";
2118        self.send_request::<_, ()>(Method::GET, path, None, None, true)
2119            .await
2120    }
2121
2122    /// Requests a list of assets (with non-zero balance), remaining balance, and available amount
2123    /// in the trading account.
2124    ///
2125    /// # Errors
2126    ///
2127    /// Returns an error if the operation fails.
2128    ///
2129    /// # References
2130    ///
2131    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-balance>
2132    pub async fn get_balance(&self) -> Result<Vec<OKXAccount>, OKXHttpError> {
2133        let path = "/api/v5/account/balance";
2134        self.send_request::<_, ()>(Method::GET, path, None, None, true)
2135            .await
2136    }
2137
2138    /// Requests one page of trading-account bills from the last seven days.
2139    ///
2140    /// Returns bills in venue order (most recent first), including non-trade balance changes.
2141    /// Pagination and historical coverage remain the caller's responsibility.
2142    ///
2143    /// # Errors
2144    ///
2145    /// Returns an error if credentials are missing, the request fails, OKX returns an error,
2146    /// or the response cannot be decoded.
2147    ///
2148    /// # References
2149    ///
2150    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-7-days>
2151    pub async fn get_account_bills(
2152        &self,
2153        params: GetAccountBillsParams,
2154    ) -> Result<Vec<OKXAccountBill>, OKXHttpError> {
2155        self.send_request(
2156            Method::GET,
2157            "/api/v5/account/bills",
2158            Some(&params),
2159            None,
2160            true,
2161        )
2162        .await
2163    }
2164
2165    /// Requests one page of trading-account bills from the last three months.
2166    ///
2167    /// Returns bills in venue order (most recent first), including non-trade balance changes.
2168    /// Pagination and historical coverage remain the caller's responsibility.
2169    ///
2170    /// # Errors
2171    ///
2172    /// Returns an error if credentials are missing, the request fails, OKX returns an error,
2173    /// or the response cannot be decoded.
2174    ///
2175    /// # References
2176    ///
2177    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-3-months>
2178    pub async fn get_account_bills_archive(
2179        &self,
2180        params: GetAccountBillsParams,
2181    ) -> Result<Vec<OKXAccountBill>, OKXHttpError> {
2182        self.send_request(
2183            Method::GET,
2184            "/api/v5/account/bills-archive",
2185            Some(&params),
2186            None,
2187            true,
2188        )
2189        .await
2190    }
2191
2192    /// Requests fee rates for the account.
2193    ///
2194    /// Returns fee rates for the specified instrument type and the user's VIP level.
2195    /// Incentive-program rates require `inst_id` for SPOT/MARGIN or `inst_family` for
2196    /// FUTURES/SWAP/OPTION; a `group_id` query alone does not provide equivalent rates.
2197    /// Fee selection remains with the caller. The endpoint does not reflect zero-fee promotions.
2198    ///
2199    /// # Errors
2200    ///
2201    /// Returns an error if the operation fails.
2202    ///
2203    /// # References
2204    ///
2205    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-fee-rates>
2206    pub async fn get_trade_fee(
2207        &self,
2208        params: GetTradeFeeParams,
2209    ) -> Result<Vec<OKXFeeRate>, OKXHttpError> {
2210        if params.group_id.is_some() && (params.inst_id.is_some() || params.inst_family.is_some()) {
2211            return Err(OKXHttpError::ValidationError(
2212                "group_id cannot be combined with inst_id or inst_family".to_string(),
2213            ));
2214        }
2215
2216        self.send_request(
2217            Method::GET,
2218            "/api/v5/account/trade-fee",
2219            Some(&params),
2220            None,
2221            true,
2222        )
2223        .await
2224    }
2225
2226    /// Retrieves a single order's details.
2227    ///
2228    /// # Errors
2229    ///
2230    /// Returns an error if the operation fails.
2231    ///
2232    /// # References
2233    ///
2234    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order>
2235    pub async fn get_order(
2236        &self,
2237        params: GetOrderParams,
2238    ) -> Result<Vec<OKXOrderHistory>, OKXHttpError> {
2239        self.send_request(
2240            Method::GET,
2241            "/api/v5/trade/order",
2242            Some(&params),
2243            None,
2244            true,
2245        )
2246        .await
2247    }
2248
2249    /// Retrieves a single algo order's details.
2250    ///
2251    /// # Errors
2252    ///
2253    /// Returns an error if the operation fails.
2254    ///
2255    /// # References
2256    ///
2257    /// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-details>
2258    pub async fn get_algo_order(
2259        &self,
2260        params: GetAlgoOrderParams,
2261    ) -> Result<Vec<OKXOrderAlgo>, OKXHttpError> {
2262        self.send_request(
2263            Method::GET,
2264            "/api/v5/trade/order-algo",
2265            Some(&params),
2266            None,
2267            true,
2268        )
2269        .await
2270    }
2271
2272    /// Requests order list (pending orders).
2273    ///
2274    /// # Errors
2275    ///
2276    /// Returns an error if the operation fails.
2277    ///
2278    /// # References
2279    ///
2280    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-list>
2281    pub async fn get_orders_pending(
2282        &self,
2283        params: GetOrderListParams,
2284    ) -> Result<Vec<OKXOrderHistory>, OKXHttpError> {
2285        self.send_request(
2286            Method::GET,
2287            "/api/v5/trade/orders-pending",
2288            Some(&params),
2289            None,
2290            true,
2291        )
2292        .await
2293    }
2294
2295    /// Requests historical order records.
2296    ///
2297    /// # Errors
2298    ///
2299    /// Returns an error if the operation fails.
2300    ///
2301    /// # References
2302    ///
2303    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-orders-history>
2304    pub async fn get_orders_history(
2305        &self,
2306        params: GetOrderHistoryParams,
2307    ) -> Result<Vec<OKXOrderHistory>, OKXHttpError> {
2308        self.send_request(
2309            Method::GET,
2310            "/api/v5/trade/orders-history",
2311            Some(&params),
2312            None,
2313            true,
2314        )
2315        .await
2316    }
2317
2318    /// Requests pending algo orders.
2319    ///
2320    /// # Errors
2321    ///
2322    /// Returns an error if the operation fails.
2323    pub async fn get_order_algo_pending(
2324        &self,
2325        params: GetAlgoOrdersParams,
2326    ) -> Result<Vec<OKXOrderAlgo>, OKXHttpError> {
2327        self.send_request(
2328            Method::GET,
2329            "/api/v5/trade/orders-algo-pending",
2330            Some(&params),
2331            None,
2332            true,
2333        )
2334        .await
2335    }
2336
2337    /// Requests historical algo orders.
2338    ///
2339    /// # Errors
2340    ///
2341    /// Returns an error if the operation fails.
2342    pub async fn get_order_algo_history(
2343        &self,
2344        params: GetAlgoOrdersParams,
2345    ) -> Result<Vec<OKXOrderAlgo>, OKXHttpError> {
2346        self.send_request(
2347            Method::GET,
2348            "/api/v5/trade/orders-algo-history",
2349            Some(&params),
2350            None,
2351            true,
2352        )
2353        .await
2354    }
2355
2356    /// Requests transaction details (fills) for the given parameters.
2357    ///
2358    /// # Errors
2359    ///
2360    /// Returns an error if the operation fails.
2361    ///
2362    /// # References
2363    ///
2364    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-days>
2365    pub async fn get_fills(
2366        &self,
2367        params: GetTransactionDetailsParams,
2368    ) -> Result<Vec<OKXTransactionDetail>, OKXHttpError> {
2369        self.send_request(
2370            Method::GET,
2371            "/api/v5/trade/fills",
2372            Some(&params),
2373            None,
2374            true,
2375        )
2376        .await
2377    }
2378
2379    /// Requests transaction details (fills) from the extended history.
2380    ///
2381    /// # Errors
2382    ///
2383    /// Returns an error if the operation fails.
2384    ///
2385    /// # References
2386    ///
2387    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-months>
2388    pub async fn get_fills_history(
2389        &self,
2390        params: GetTransactionDetailsParams,
2391    ) -> Result<Vec<OKXTransactionDetail>, OKXHttpError> {
2392        self.send_request(
2393            Method::GET,
2394            "/api/v5/trade/fills-history",
2395            Some(&params),
2396            None,
2397            true,
2398        )
2399        .await
2400    }
2401
2402    /// Requests information on your positions. When the account is in net mode, net positions will
2403    /// be displayed, and when the account is in long/short mode, long or short positions will be
2404    /// displayed. Returns in reverse chronological order using ctime.
2405    ///
2406    /// # Errors
2407    ///
2408    /// Returns an error if the operation fails.
2409    ///
2410    /// # References
2411    ///
2412    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions>
2413    pub async fn get_positions(
2414        &self,
2415        params: GetPositionsParams,
2416    ) -> Result<Vec<OKXPosition>, OKXHttpError> {
2417        self.send_request(
2418            Method::GET,
2419            "/api/v5/account/positions",
2420            Some(&params),
2421            None,
2422            true,
2423        )
2424        .await
2425    }
2426
2427    /// Requests closed or historical position data.
2428    ///
2429    /// # Errors
2430    ///
2431    /// Returns an error if the operation fails.
2432    ///
2433    /// # References
2434    ///
2435    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions-history>
2436    pub async fn get_positions_history(
2437        &self,
2438        params: GetPositionsHistoryParams,
2439    ) -> Result<Vec<OKXPositionHistory>, OKXHttpError> {
2440        self.send_request(
2441            Method::GET,
2442            "/api/v5/account/positions-history",
2443            Some(&params),
2444            None,
2445            true,
2446        )
2447        .await
2448    }
2449}
2450
2451/// Whether a paginated history request covered its whole window.
2452///
2453/// The data client reports a [`Complete`](Self::Complete) request as a completed response
2454/// envelope, which lets the data engine write the window back to a catalog.
2455#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2456pub enum OKXHistoryCoverage {
2457    /// The pagination reached the start of the requested window.
2458    Complete,
2459    /// The page cap stopped the pagination before the start of the window.
2460    Truncated,
2461    /// The window cannot be confirmed: no start was given, a limit ended the request,
2462    /// or OKX returned nothing older before the start.
2463    Unverified,
2464}
2465
2466/// Provides a higher-level HTTP client for the [OKX](https://okx.com) REST API.
2467///
2468/// This client wraps the underlying `OKXHttpInnerClient` to handle conversions
2469/// into the Nautilus domain model.
2470#[derive(Debug)]
2471#[cfg_attr(
2472    feature = "python",
2473    pyo3::pyclass(module = "nautilus_trader.adapters.okx", from_py_object)
2474)]
2475#[cfg_attr(
2476    feature = "python",
2477    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.okx")
2478)]
2479pub struct OKXHttpClient {
2480    pub(crate) inner: Arc<OKXRawHttpClient>,
2481    pub(crate) instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
2482    inst_id_codes: Arc<AtomicMap<Ustr, u64>>,
2483    trade_quote_ccy_lists: Arc<AtomicMap<Ustr, Vec<Ustr>>>,
2484    spot_trade_quote_ccy: Arc<Mutex<Option<Ustr>>>,
2485    cache_initialized: AtomicBool,
2486}
2487
2488impl Clone for OKXHttpClient {
2489    fn clone(&self) -> Self {
2490        let cache_initialized = AtomicBool::new(false);
2491
2492        let is_initialized = self.cache_initialized.load(Ordering::Acquire);
2493        if is_initialized {
2494            cache_initialized.store(true, Ordering::Release);
2495        }
2496
2497        Self {
2498            inner: self.inner.clone(),
2499            instruments_cache: self.instruments_cache.clone(),
2500            inst_id_codes: self.inst_id_codes.clone(),
2501            trade_quote_ccy_lists: self.trade_quote_ccy_lists.clone(),
2502            spot_trade_quote_ccy: self.spot_trade_quote_ccy.clone(),
2503            cache_initialized,
2504        }
2505    }
2506}
2507
2508impl Default for OKXHttpClient {
2509    fn default() -> Self {
2510        Self::new(None, 60, 3, 1000, 10_000, OKXEnvironment::Live, None)
2511            .expect("Failed to create default OKXHttpClient")
2512    }
2513}
2514
2515impl OKXHttpClient {
2516    /// Creates a new [`OKXHttpClient`] using the default OKX HTTP URL,
2517    /// optionally overridden with a custom base url.
2518    ///
2519    /// This version of the client has **no credentials**, so it can only
2520    /// call publicly accessible endpoints.
2521    ///
2522    /// # Errors
2523    ///
2524    /// Returns an error if retry delays are invalid or the HTTP transport cannot be created.
2525    pub fn new(
2526        base_url: Option<String>,
2527        timeout_secs: u64,
2528        max_retries: u32,
2529        retry_delay_ms: u64,
2530        retry_delay_max_ms: u64,
2531        environment: OKXEnvironment,
2532        proxy_url: Option<String>,
2533    ) -> anyhow::Result<Self> {
2534        crate::config::validate_retry_delays(retry_delay_ms, retry_delay_max_ms)?;
2535        Ok(Self {
2536            inner: Arc::new(OKXRawHttpClient::new(
2537                base_url,
2538                timeout_secs,
2539                max_retries,
2540                retry_delay_ms,
2541                retry_delay_max_ms,
2542                environment,
2543                proxy_url,
2544            )?),
2545            instruments_cache: Arc::new(AtomicMap::new()),
2546            inst_id_codes: Arc::new(AtomicMap::new()),
2547            trade_quote_ccy_lists: Arc::new(AtomicMap::new()),
2548            spot_trade_quote_ccy: Arc::new(Mutex::new(None)),
2549            cache_initialized: AtomicBool::new(false),
2550        })
2551    }
2552
2553    /// Generates a timestamp for initialization.
2554    fn generate_ts_init(&self) -> UnixNanos {
2555        self.inner.clock.get_time_ns()
2556    }
2557
2558    /// Creates a new authenticated [`OKXHttpClient`] using environment variables and
2559    /// the default OKX HTTP base url.
2560    ///
2561    /// # Errors
2562    ///
2563    /// Returns an error if the operation fails.
2564    pub fn from_env() -> anyhow::Result<Self> {
2565        Self::with_credentials(
2566            None,
2567            None,
2568            None,
2569            None,
2570            60,
2571            3,
2572            1000,
2573            10_000,
2574            OKXEnvironment::Live,
2575            None,
2576        )
2577    }
2578
2579    /// Creates a new [`OKXHttpClient`] configured with credentials
2580    /// for authenticated requests, optionally using a custom base url.
2581    ///
2582    /// # Errors
2583    ///
2584    /// Returns an error if retry delays are invalid, credentials are missing, or transport setup fails.
2585    #[expect(clippy::too_many_arguments)]
2586    pub fn with_credentials(
2587        api_key: Option<String>,
2588        api_secret: Option<String>,
2589        api_passphrase: Option<String>,
2590        base_url: Option<String>,
2591        timeout_secs: u64,
2592        max_retries: u32,
2593        retry_delay_ms: u64,
2594        retry_delay_max_ms: u64,
2595        environment: OKXEnvironment,
2596        proxy_url: Option<String>,
2597    ) -> anyhow::Result<Self> {
2598        crate::config::validate_retry_delays(retry_delay_ms, retry_delay_max_ms)?;
2599        let api_key = get_or_env_var(api_key, "OKX_API_KEY")?;
2600        let api_secret = get_or_env_var(api_secret, "OKX_API_SECRET")?;
2601        let api_passphrase = get_or_env_var(api_passphrase, "OKX_API_PASSPHRASE")?;
2602        let base_url = base_url.unwrap_or(OKX_HTTP_URL.to_string());
2603
2604        Ok(Self {
2605            inner: Arc::new(OKXRawHttpClient::with_credentials(
2606                api_key,
2607                api_secret,
2608                api_passphrase,
2609                base_url,
2610                timeout_secs,
2611                max_retries,
2612                retry_delay_ms,
2613                retry_delay_max_ms,
2614                environment,
2615                proxy_url,
2616            )?),
2617            instruments_cache: Arc::new(AtomicMap::new()),
2618            inst_id_codes: Arc::new(AtomicMap::new()),
2619            trade_quote_ccy_lists: Arc::new(AtomicMap::new()),
2620            spot_trade_quote_ccy: Arc::new(Mutex::new(None)),
2621            cache_initialized: AtomicBool::new(false),
2622        })
2623    }
2624
2625    /// Retrieves an instrument from the cache.
2626    ///
2627    /// # Errors
2628    ///
2629    /// Returns an error if the instrument is not found in the cache.
2630    fn instrument_from_cache(&self, symbol: Ustr) -> anyhow::Result<InstrumentAny> {
2631        self.instruments_cache
2632            .get_cloned(&symbol)
2633            .ok_or_else(|| anyhow::anyhow!("Instrument {symbol} not in cache"))
2634    }
2635
2636    fn instrument_from_cache_by_id(
2637        &self,
2638        instrument_id: InstrumentId,
2639    ) -> anyhow::Result<InstrumentAny> {
2640        self.instruments_cache
2641            .get_cloned(&instrument_id.symbol.inner())
2642            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id).into())
2643    }
2644
2645    /// Cancel all pending HTTP requests.
2646    pub fn cancel_all_requests(&self) {
2647        self.inner.cancel_all_requests();
2648    }
2649
2650    /// Get the cancellation token for this client.
2651    pub fn cancellation_token(&self) -> &CancellationToken {
2652        self.inner.cancellation_token()
2653    }
2654
2655    /// Requests order list (pending orders).
2656    ///
2657    /// # Errors
2658    ///
2659    /// Returns an error if the operation fails.
2660    pub async fn get_orders_pending(
2661        &self,
2662        params: GetOrderListParams,
2663    ) -> Result<Vec<OKXOrderHistory>, OKXHttpError> {
2664        self.inner.get_orders_pending(params).await
2665    }
2666
2667    /// Requests pending algo orders.
2668    ///
2669    /// # Errors
2670    ///
2671    /// Returns an error if the operation fails.
2672    pub async fn get_order_algo_pending(
2673        &self,
2674        params: GetAlgoOrdersParams,
2675    ) -> Result<Vec<OKXOrderAlgo>, OKXHttpError> {
2676        self.inner.get_order_algo_pending(params).await
2677    }
2678
2679    /// Requests information on current account positions.
2680    ///
2681    /// # Errors
2682    ///
2683    /// Returns an error if the operation fails.
2684    pub async fn get_positions(
2685        &self,
2686        params: GetPositionsParams,
2687    ) -> Result<Vec<OKXPosition>, OKXHttpError> {
2688        self.inner.get_positions(params).await
2689    }
2690
2691    /// Returns the base url being used by the client.
2692    pub fn base_url(&self) -> &str {
2693        self.inner.base_url.as_str()
2694    }
2695
2696    /// Returns the public API key being used by the client.
2697    pub fn api_key(&self) -> Option<&str> {
2698        self.inner.credential.as_ref().map(Credential::api_key)
2699    }
2700
2701    /// Returns a masked version of the API key for logging purposes.
2702    #[must_use]
2703    pub fn api_key_masked(&self) -> Option<String> {
2704        self.inner
2705            .credential
2706            .as_ref()
2707            .map(Credential::api_key_masked)
2708    }
2709
2710    /// Returns whether the client is configured for demo trading.
2711    #[must_use]
2712    pub fn is_demo(&self) -> bool {
2713        self.inner.environment == OKXEnvironment::Demo
2714    }
2715
2716    /// Requests the current server time from OKX.
2717    ///
2718    /// Returns the OKX system time as a Unix timestamp in milliseconds.
2719    ///
2720    /// # Errors
2721    ///
2722    /// Returns an error if the HTTP request fails or if the response cannot be parsed.
2723    pub async fn get_server_time(&self) -> Result<u64, OKXHttpError> {
2724        self.inner.get_server_time().await
2725    }
2726
2727    /// Checks if the client is initialized.
2728    ///
2729    /// The client is considered initialized if any instruments have been cached from the venue.
2730    #[must_use]
2731    pub fn is_initialized(&self) -> bool {
2732        self.cache_initialized.load(Ordering::Acquire)
2733    }
2734
2735    /// Returns a snapshot of all instrument symbols currently held in the
2736    /// internal cache.
2737    #[must_use]
2738    pub fn get_cached_symbols(&self) -> Vec<String> {
2739        self.instruments_cache
2740            .load()
2741            .keys()
2742            .map(ToString::to_string)
2743            .collect()
2744    }
2745
2746    /// Caches multiple instruments.
2747    ///
2748    /// Any existing instruments with the same symbols will be replaced.
2749    pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
2750        self.instruments_cache.rcu(|m| {
2751            for inst in instruments {
2752                m.insert(inst.raw_symbol().inner(), inst.clone());
2753            }
2754        });
2755        self.cache_initialized.store(true, Ordering::Release);
2756    }
2757
2758    /// Caches a single instrument.
2759    ///
2760    /// Any existing instrument with the same symbol will be replaced.
2761    pub fn cache_instrument(&self, instrument: InstrumentAny) {
2762        self.instruments_cache
2763            .insert(instrument.raw_symbol().inner(), instrument);
2764        self.cache_initialized.store(true, Ordering::Release);
2765    }
2766
2767    /// Gets an instrument from the cache by symbol.
2768    pub fn get_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
2769        self.instruments_cache.get_cloned(symbol)
2770    }
2771
2772    pub(crate) fn inst_id_code(&self, symbol: &Ustr) -> Option<u64> {
2773        self.inst_id_codes.get_cloned(symbol)
2774    }
2775
2776    pub(crate) fn is_spread(&self, instrument_id: InstrumentId) -> bool {
2777        self.instruments_cache
2778            .load()
2779            .get(&instrument_id.symbol.inner())
2780            .map_or_else(
2781                || is_okx_spread_symbol(instrument_id.symbol.as_str()),
2782                InstrumentAny::is_spread,
2783            )
2784    }
2785
2786    /// Sets the optional SPOT `tradeQuoteCcy` override for subsequent order placement.
2787    pub fn set_spot_trade_quote_ccy(&self, ccy: Option<String>) {
2788        *self
2789            .spot_trade_quote_ccy
2790            .lock()
2791            .unwrap_or_else(std::sync::PoisonError::into_inner) =
2792            ccy.map(|value| Ustr::from(value.as_str()));
2793    }
2794
2795    /// Caches `tradeQuoteCcyList` values keyed by instrument ID.
2796    pub fn cache_trade_quote_ccy_lists(
2797        &self,
2798        mappings: impl IntoIterator<Item = (Ustr, Vec<Ustr>)>,
2799    ) {
2800        let entries: Vec<_> = mappings.into_iter().collect();
2801        self.trade_quote_ccy_lists.rcu(|m| {
2802            for (inst_id, list) in &entries {
2803                m.insert(*inst_id, list.clone());
2804            }
2805        });
2806    }
2807
2808    /// Returns a snapshot of cached `tradeQuoteCcyList` values.
2809    #[must_use]
2810    pub fn trade_quote_ccy_lists_snapshot(&self) -> Vec<(Ustr, Vec<Ustr>)> {
2811        self.trade_quote_ccy_lists
2812            .load()
2813            .iter()
2814            .map(|(inst_id, list)| (*inst_id, list.clone()))
2815            .collect()
2816    }
2817
2818    fn cache_trade_quote_ccy_list_from_instrument(&self, instrument: &OKXInstrument) {
2819        if !instrument.trade_quote_ccy_list.is_empty() {
2820            self.trade_quote_ccy_lists
2821                .insert(instrument.inst_id, instrument.trade_quote_ccy_list.clone());
2822        }
2823    }
2824
2825    fn resolve_spot_trade_quote_ccy(
2826        &self,
2827        instrument_type: OKXInstrumentType,
2828        inst_id: Ustr,
2829    ) -> Result<Option<Ustr>, OKXHttpError> {
2830        let configured = *self
2831            .spot_trade_quote_ccy
2832            .lock()
2833            .unwrap_or_else(std::sync::PoisonError::into_inner);
2834        let available = self
2835            .trade_quote_ccy_lists
2836            .load()
2837            .get(&inst_id)
2838            .cloned()
2839            .unwrap_or_default();
2840        spot_trade_quote_ccy_wire_value(
2841            instrument_type,
2842            configured.as_ref().map(Ustr::as_str),
2843            &available,
2844        )
2845        .map_err(OKXHttpError::ValidationError)
2846    }
2847
2848    /// Requests the account state for the `account_id` from OKX.
2849    ///
2850    /// Pass the execution client's configured account type; the OKX balance payload carries
2851    /// no account-mode field.
2852    ///
2853    /// # Errors
2854    ///
2855    /// Returns an error if the HTTP request fails or no account state is returned.
2856    pub async fn request_account_state(
2857        &self,
2858        account_id: AccountId,
2859        account_type: AccountType,
2860    ) -> anyhow::Result<AccountState> {
2861        let resp = self
2862            .inner
2863            .get_balance()
2864            .await
2865            .map_err(|e| anyhow::anyhow!(e))?;
2866
2867        let ts_init = self.generate_ts_init();
2868        let raw = resp
2869            .first()
2870            .ok_or_else(|| anyhow::anyhow!("No account state returned from OKX"))?;
2871        let (account_state, balances_complete) =
2872            parse_account_state_with_completeness(raw, account_id, account_type, ts_init);
2873
2874        // Only a fully parsed, unfiltered REST response authoritatively zeros omitted currencies
2875        let info = balances_complete.then(|| {
2876            Params::new(IndexMap::from([(
2877                BALANCES_SNAPSHOT_COMPLETE_INFO_KEY.to_string(),
2878                serde_json::Value::Bool(true),
2879            )]))
2880        });
2881
2882        let account_state = account_state.with_info(info);
2883
2884        Ok(account_state)
2885    }
2886
2887    /// Sets the position mode for the account.
2888    ///
2889    /// Defaults to `NetMode` if no position mode is provided.
2890    ///
2891    /// # Errors
2892    ///
2893    /// Returns an error if the HTTP request fails or the position mode cannot be set.
2894    ///
2895    /// # Note
2896    ///
2897    /// This endpoint only works for accounts with derivatives trading enabled.
2898    /// If the account only has spot trading, this will return an error.
2899    pub async fn set_position_mode(&self, position_mode: OKXPositionMode) -> anyhow::Result<()> {
2900        let mut params = SetPositionModeParamsBuilder::default();
2901        params.pos_mode(position_mode);
2902        let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
2903
2904        match self.inner.set_position_mode(params).await {
2905            Ok(_) => Ok(()),
2906            Err(e) => {
2907                if let OKXHttpError::OkxError {
2908                    error_code,
2909                    message,
2910                } = &e
2911                    && error_code == "50115"
2912                {
2913                    log::warn!(
2914                        "Account does not support position mode setting (derivatives trading not enabled): {message}"
2915                    );
2916                    return Ok(()); // Gracefully handle this case
2917                }
2918                anyhow::bail!(e)
2919            }
2920        }
2921    }
2922
2923    /// Activates an account feature such as USDC order book trading.
2924    ///
2925    /// This does not run at client start. Call it only after OKX rejects a
2926    /// `Crypto-USDC` order with error code `54109`. Activation is shared between a
2927    /// master account and its sub-accounts, so one successful call covers all of
2928    /// them. Error code `51773` means the account does not support activation, not
2929    /// that USDC trading is unavailable; a successful order confirms the account can
2930    /// trade the instrument.
2931    ///
2932    /// # Errors
2933    ///
2934    /// Returns an error if the HTTP request fails.
2935    ///
2936    /// # References
2937    ///
2938    /// <https://www.okx.com/docs-v5/log_en/#upcoming-changes-okx-to-migrate-usd-spot-trading-pairs-new-endpoint-activate-usdc-trading>
2939    pub async fn activate_feature(&self, feature: &str) -> anyhow::Result<()> {
2940        let params = ActivateFeatureParams {
2941            feature: feature.to_string(),
2942        };
2943
2944        self.inner
2945            .activate_feature(params)
2946            .await
2947            .map(|_| ())
2948            .map_err(Into::into)
2949    }
2950
2951    /// Refreshes cached `tradeQuoteCcyList` values from private instruments.
2952    ///
2953    /// # Errors
2954    ///
2955    /// Returns an error if the authenticated instruments request fails.
2956    pub async fn refresh_account_trade_quote_ccy_lists(
2957        &self,
2958        instrument_type: OKXInstrumentType,
2959        instrument_family: Option<String>,
2960    ) -> anyhow::Result<()> {
2961        let mut params = GetInstrumentsParamsBuilder::default();
2962        params.inst_type(instrument_type);
2963        if let Some(family) = instrument_family {
2964            params.inst_family(family);
2965        }
2966
2967        let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
2968        let instruments = self
2969            .inner
2970            .get_account_instruments(params)
2971            .await
2972            .map_err(|e| anyhow::anyhow!(e))?;
2973        self.cache_trade_quote_ccy_lists(
2974            instruments
2975                .iter()
2976                .filter(|instrument| !instrument.trade_quote_ccy_list.is_empty())
2977                .map(|instrument| (instrument.inst_id, instrument.trade_quote_ccy_list.clone())),
2978        );
2979
2980        Ok(())
2981    }
2982
2983    /// Requests all instruments for the `instrument_type` from OKX.
2984    ///
2985    /// Option requests require `instrument_family` (OKX `instFamily`), for example `BTC-USD`.
2986    /// A definition that fails to parse is logged and left out.
2987    ///
2988    /// # Errors
2989    ///
2990    /// Returns an error if:
2991    /// - The `instrument_type` is option and `instrument_family` is missing.
2992    /// - The HTTP request fails.
2993    ///
2994    /// # Returns
2995    ///
2996    /// A tuple containing:
2997    /// - `Vec<InstrumentAny>`: The parsed instruments
2998    /// - `Vec<(Ustr, u64)>`: Mappings of `inst_id` to `inst_id_code` for WebSocket order operations
2999    pub async fn request_instruments(
3000        &self,
3001        instrument_type: OKXInstrumentType,
3002        instrument_family: Option<String>,
3003    ) -> anyhow::Result<(Vec<InstrumentAny>, Vec<(Ustr, u64)>)> {
3004        let (instruments, inst_id_codes, parse_failures) = self
3005            .request_instruments_with_parse_failures(instrument_type, instrument_family)
3006            .await?;
3007
3008        for failure in parse_failures {
3009            log::warn!("{failure}");
3010        }
3011
3012        Ok((instruments, inst_id_codes))
3013    }
3014
3015    pub(crate) async fn request_instruments_with_parse_failures(
3016        &self,
3017        instrument_type: OKXInstrumentType,
3018        instrument_family: Option<String>,
3019    ) -> anyhow::Result<(Vec<InstrumentAny>, Vec<(Ustr, u64)>, Vec<String>)> {
3020        if instrument_type == OKXInstrumentType::Option && instrument_family.is_none() {
3021            anyhow::bail!(
3022                "option instruments require instrument_family (OKX instFamily), for example BTC-USD"
3023            );
3024        }
3025
3026        let resp = if instrument_type == OKXInstrumentType::Events {
3027            let series_ids = if let Some(series_id) = instrument_family.clone() {
3028                vec![series_id]
3029            } else {
3030                self.inner
3031                    .get_event_contract_series(GetEventContractSeriesParams::default())
3032                    .await
3033                    .map_err(|e| anyhow::anyhow!(e))?
3034                    .into_iter()
3035                    .map(|series| series.series_id)
3036                    .collect()
3037            };
3038
3039            let mut event_instruments = Vec::new();
3040
3041            for series_id in series_ids {
3042                let mut params = GetInstrumentsParamsBuilder::default();
3043                params.inst_type(OKXInstrumentType::Events);
3044                params.series_id(series_id);
3045                let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
3046                let mut page = self
3047                    .inner
3048                    .get_instruments(params)
3049                    .await
3050                    .map_err(|e| anyhow::anyhow!(e))?;
3051                event_instruments.append(&mut page);
3052            }
3053            event_instruments
3054        } else {
3055            let mut params = GetInstrumentsParamsBuilder::default();
3056            params.inst_type(instrument_type);
3057
3058            if let Some(family) = instrument_family.clone() {
3059                params.inst_family(family);
3060            }
3061
3062            let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
3063
3064            self.inner
3065                .get_instruments(params)
3066                .await
3067                .map_err(|e| anyhow::anyhow!(e))?
3068        };
3069
3070        let ts_init = self.generate_ts_init();
3071
3072        let mut instruments: Vec<InstrumentAny> = Vec::new();
3073        let mut inst_id_codes: Vec<(Ustr, u64)> = Vec::new();
3074        let mut trade_quote_ccy_lists: Vec<(Ustr, Vec<Ustr>)> = Vec::new();
3075        let mut parse_failures: Vec<String> = Vec::new();
3076
3077        for inst in &resp {
3078            // Collect inst_id_code mappings for WebSocket order operations
3079            if let Some(code) = inst.inst_id_code {
3080                inst_id_codes.push((inst.inst_id, code));
3081            }
3082
3083            if !inst.trade_quote_ccy_list.is_empty() {
3084                trade_quote_ccy_lists.push((inst.inst_id, inst.trade_quote_ccy_list.clone()));
3085            }
3086
3087            // Skip pre-open instruments which have incomplete/empty field values
3088            // Keep suspended instruments as they have valid metadata and may return to live
3089            if inst.state == OKXInstrumentStatus::Preopen {
3090                continue;
3091            }
3092
3093            match parse_instrument_any(inst, None, None, ts_init) {
3094                Ok(Some(instrument_any)) => {
3095                    instruments.push(instrument_any);
3096                }
3097                Ok(None) => {
3098                    // Unsupported instrument type, skip silently
3099                }
3100                Err(e) => {
3101                    parse_failures
3102                        .push(format!("Failed to parse instrument {}: {e}", inst.inst_id));
3103                }
3104            }
3105        }
3106
3107        self.cache_trade_quote_ccy_lists(trade_quote_ccy_lists);
3108        self.inst_id_codes
3109            .rcu(|codes| codes.extend(inst_id_codes.iter().copied()));
3110
3111        Ok((instruments, inst_id_codes, parse_failures))
3112    }
3113
3114    /// Requests spread instruments from OKX.
3115    ///
3116    /// A definition that fails to parse is logged and left out.
3117    ///
3118    /// # Errors
3119    ///
3120    /// Returns an error if the HTTP request fails.
3121    pub async fn request_spread_instruments(
3122        &self,
3123        params: GetSpreadsParams,
3124    ) -> anyhow::Result<Vec<InstrumentAny>> {
3125        let (instruments, parse_failures) = self
3126            .request_spread_instruments_with_parse_failures(params)
3127            .await?;
3128
3129        for failure in parse_failures {
3130            log::warn!("{failure}");
3131        }
3132
3133        Ok(instruments)
3134    }
3135
3136    pub(crate) async fn request_spread_instruments_with_parse_failures(
3137        &self,
3138        params: GetSpreadsParams,
3139    ) -> anyhow::Result<(Vec<InstrumentAny>, Vec<String>)> {
3140        let resp = self
3141            .inner
3142            .get_spreads(params)
3143            .await
3144            .map_err(|e| anyhow::anyhow!(e))?;
3145
3146        let ts_init = self.generate_ts_init();
3147        let mut instruments = Vec::new();
3148        let mut parse_failures = Vec::new();
3149
3150        for spread in &resp {
3151            match parse_spread_instrument(spread, None, None, ts_init) {
3152                Ok(instrument) => instruments.push(instrument),
3153                Err(e) => {
3154                    parse_failures.push(format!("Failed to parse spread {}: {e}", spread.sprd_id));
3155                }
3156            }
3157        }
3158
3159        Ok((instruments, parse_failures))
3160    }
3161
3162    /// Requests a single instrument by `instrument_id` from OKX.
3163    ///
3164    /// Fetches the instrument from the API, caches it, and returns it.
3165    ///
3166    /// # Errors
3167    ///
3168    /// Returns an error if:
3169    /// - The API request fails.
3170    /// - The instrument is not found.
3171    /// - Failed to parse instrument data.
3172    pub async fn request_instrument(
3173        &self,
3174        instrument_id: InstrumentId,
3175    ) -> anyhow::Result<InstrumentAny> {
3176        let symbol = instrument_id.symbol.as_str();
3177        if self.is_spread(instrument_id) {
3178            let instrument = self.request_spread_instrument(symbol).await?;
3179            self.cache_instrument(instrument.clone());
3180            return Ok(instrument);
3181        }
3182
3183        let instrument_type = okx_instrument_type_from_symbol(symbol);
3184
3185        let resp = if instrument_type == OKXInstrumentType::Events {
3186            let series = self
3187                .inner
3188                .get_event_contract_series(GetEventContractSeriesParams::default())
3189                .await
3190                .map_err(|e| anyhow::anyhow!(e))?;
3191
3192            let mut matched = Vec::new();
3193
3194            for series in series {
3195                let mut params = GetInstrumentsParamsBuilder::default();
3196                params.inst_type(OKXInstrumentType::Events);
3197                params.series_id(series.series_id);
3198                params.inst_id(symbol);
3199                let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
3200
3201                let mut page = self
3202                    .inner
3203                    .get_instruments(params)
3204                    .await
3205                    .map_err(|e| anyhow::anyhow!(e))?;
3206                matched.append(&mut page);
3207                if !matched.is_empty() {
3208                    break;
3209                }
3210            }
3211            matched
3212        } else {
3213            let mut params = GetInstrumentsParamsBuilder::default();
3214            params.inst_type(instrument_type);
3215            params.inst_id(symbol);
3216            if instrument_type == OKXInstrumentType::Option {
3217                params.inst_family(extract_inst_family(symbol)?.to_string());
3218            }
3219
3220            let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
3221
3222            self.inner
3223                .get_instruments(params)
3224                .await
3225                .map_err(|e| anyhow::anyhow!(e))?
3226        };
3227
3228        let raw_inst = resp
3229            .first()
3230            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
3231        self.cache_trade_quote_ccy_list_from_instrument(raw_inst);
3232        if let Some(code) = raw_inst.inst_id_code {
3233            self.inst_id_codes.insert(raw_inst.inst_id, code);
3234        }
3235
3236        // Skip pre-open instruments which have incomplete/empty field values
3237        if raw_inst.state == OKXInstrumentStatus::Preopen {
3238            return Err(OKXInstrumentDefinitionError::new(
3239                symbol,
3240                anyhow::anyhow!("instrument is in pre-open state"),
3241            )
3242            .into());
3243        }
3244
3245        let ts_init = self.generate_ts_init();
3246        let Some(instrument) = parse_instrument_any(raw_inst, None, None, ts_init)
3247            .map_err(|e| OKXInstrumentDefinitionError::new(symbol, e))?
3248        else {
3249            return Err(OKXInstrumentDefinitionError::new(
3250                symbol,
3251                anyhow::anyhow!("unsupported instrument type"),
3252            )
3253            .into());
3254        };
3255
3256        self.cache_instrument(instrument.clone());
3257
3258        Ok(instrument)
3259    }
3260
3261    async fn request_spread_instrument(&self, symbol: &str) -> anyhow::Result<InstrumentAny> {
3262        let resp = self
3263            .inner
3264            .get_spreads(GetSpreadsParams {
3265                sprd_id: Some(symbol.to_string()),
3266                ..Default::default()
3267            })
3268            .await
3269            .map_err(|e| anyhow::anyhow!(e))?;
3270
3271        let raw_spread = resp
3272            .first()
3273            .ok_or_else(|| anyhow::anyhow!("Spread instrument {symbol} not found"))?;
3274        let ts_init = self.generate_ts_init();
3275
3276        parse_spread_instrument(raw_spread, None, None, ts_init)
3277            .map_err(|e| OKXInstrumentDefinitionError::new(symbol, e).into())
3278    }
3279
3280    /// Requests event contract series metadata from OKX.
3281    ///
3282    /// # Errors
3283    ///
3284    /// Returns an error if the HTTP request fails or the response cannot be deserialized.
3285    pub async fn request_event_contract_series(
3286        &self,
3287        params: GetEventContractSeriesParams,
3288    ) -> Result<Vec<OKXEventContractSeries>, OKXHttpError> {
3289        self.inner.get_event_contract_series(params).await
3290    }
3291
3292    /// Requests event metadata for an event contract series from OKX.
3293    ///
3294    /// # Errors
3295    ///
3296    /// Returns an error if the HTTP request fails or the response cannot be deserialized.
3297    pub async fn request_event_contract_events(
3298        &self,
3299        params: GetEventContractEventsParams,
3300    ) -> Result<Vec<OKXEventContractEvent>, OKXHttpError> {
3301        self.inner.get_event_contract_events(params).await
3302    }
3303
3304    /// Requests event contract market metadata from OKX.
3305    ///
3306    /// # Errors
3307    ///
3308    /// Returns an error if the HTTP request fails or the response cannot be deserialized.
3309    pub async fn request_event_contract_markets(
3310        &self,
3311        params: GetEventContractMarketsParams,
3312    ) -> Result<Vec<OKXEventContractMarket>, OKXHttpError> {
3313        self.inner.get_event_contract_markets(params).await
3314    }
3315
3316    /// Requests the reference price for an OKX option-chain bootstrap.
3317    ///
3318    /// # Errors
3319    ///
3320    /// Returns an error if the HTTP request fails or the option symbol is invalid.
3321    pub(crate) async fn request_option_chain_reference_price(
3322        &self,
3323        instrument_id: InstrumentId,
3324    ) -> anyhow::Result<Option<Price>> {
3325        let symbol = instrument_id.symbol.inner().as_str();
3326        let inst_family = extract_inst_family(symbol)?.to_string();
3327        let exp_time = Self::option_summary_exp_time(symbol)?;
3328        let summaries = self
3329            .inner
3330            .get_option_summary(GetOptionSummaryParams {
3331                inst_family,
3332                exp_time,
3333            })
3334            .await
3335            .map_err(|e| anyhow::anyhow!(e))?;
3336
3337        for summary in summaries {
3338            if summary.inst_type != OKXInstrumentType::Option || summary.inst_id != symbol {
3339                continue;
3340            }
3341
3342            let decimal = match Decimal::from_str(&summary.fwd_px) {
3343                Ok(decimal) if decimal > Decimal::ZERO => decimal,
3344                Ok(_) => return Ok(None),
3345                Err(e) => {
3346                    log::warn!("Invalid OKX option-chain reference price for {instrument_id}: {e}");
3347                    return Ok(None);
3348                }
3349            };
3350            return Price::from_decimal(decimal).map(Some).map_err(Into::into);
3351        }
3352
3353        Ok(None)
3354    }
3355
3356    /// Requests the latest mark price for the `instrument_type` from OKX.
3357    ///
3358    /// # Errors
3359    ///
3360    /// Returns an error if the HTTP request fails or no mark price is returned.
3361    pub async fn request_mark_price(
3362        &self,
3363        instrument_id: InstrumentId,
3364    ) -> anyhow::Result<MarkPriceUpdate> {
3365        let inst = self.instrument_from_cache(instrument_id.symbol.inner())?;
3366        let mut params = GetMarkPriceParamsBuilder::default();
3367        params.inst_type(okx_instrument_type(&inst)?);
3368        params.inst_id(instrument_id.symbol.inner());
3369        let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
3370
3371        let resp = self
3372            .inner
3373            .get_mark_price(params)
3374            .await
3375            .map_err(|e| anyhow::anyhow!(e))?;
3376
3377        let raw = resp
3378            .first()
3379            .ok_or_else(|| anyhow::anyhow!("No mark price returned from OKX"))?;
3380        let ts_init = self.generate_ts_init();
3381
3382        let mark_price =
3383            parse_mark_price_update(raw, instrument_id, inst.price_precision(), ts_init)
3384                .map_err(|e| anyhow::anyhow!(e))?;
3385        Ok(mark_price)
3386    }
3387
3388    /// Requests the current price limits for the `instrument_id` from OKX.
3389    ///
3390    /// # Errors
3391    ///
3392    /// Returns an error if the HTTP request fails or no price limit is returned.
3393    pub async fn request_price_limit(
3394        &self,
3395        instrument_id: InstrumentId,
3396    ) -> anyhow::Result<OKXPriceLimit> {
3397        let mut params = GetPriceLimitParamsBuilder::default();
3398        params.inst_id(instrument_id.symbol.inner());
3399        let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
3400
3401        let resp = self
3402            .inner
3403            .get_price_limit(params)
3404            .await
3405            .map_err(|e| anyhow::anyhow!(e))?;
3406
3407        resp.first()
3408            .cloned()
3409            .ok_or_else(|| anyhow::anyhow!("No price limit returned from OKX"))
3410    }
3411
3412    fn option_summary_exp_time(symbol: &str) -> anyhow::Result<Option<String>> {
3413        let parts: Vec<&str> = symbol.split('-').collect();
3414        anyhow::ensure!(
3415            parts.len() >= 5,
3416            "Expected OKX option symbol with expiry, received {symbol}"
3417        );
3418        Ok(Some(parts[2].to_string()))
3419    }
3420
3421    /// Requests the latest index price for the `instrument_id` from OKX.
3422    ///
3423    /// # Errors
3424    ///
3425    /// Returns an error if the HTTP request fails or no index price is returned.
3426    pub async fn request_index_price(
3427        &self,
3428        instrument_id: InstrumentId,
3429    ) -> anyhow::Result<IndexPriceUpdate> {
3430        // Index tickers endpoint requires base pair format (e.g., BTC-USDT)
3431        let symbol = instrument_id.symbol.inner();
3432        let (base, quote) = parse_base_quote_from_symbol(symbol.as_str())?;
3433        let inst_id = format!("{base}-{quote}");
3434
3435        let mut params = GetIndexTickerParamsBuilder::default();
3436        params.inst_id(Ustr::from(&inst_id));
3437        let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
3438
3439        let resp = self
3440            .inner
3441            .get_index_tickers(params)
3442            .await
3443            .map_err(|e| anyhow::anyhow!(e))?;
3444
3445        let raw = resp
3446            .first()
3447            .ok_or_else(|| anyhow::anyhow!("No index price returned from OKX"))?;
3448        let inst = self.instrument_from_cache(instrument_id.symbol.inner())?;
3449        let ts_init = self.generate_ts_init();
3450
3451        let index_price =
3452            parse_index_price_update(raw, instrument_id, inst.price_precision(), ts_init)
3453                .map_err(|e| anyhow::anyhow!(e))?;
3454        Ok(index_price)
3455    }
3456
3457    /// Requests an order book snapshot for the `instrument_id`.
3458    ///
3459    /// # Errors
3460    ///
3461    /// Returns an error if the HTTP request fails or book parsing fails.
3462    pub async fn request_book_snapshot(
3463        &self,
3464        instrument_id: InstrumentId,
3465        depth: Option<u32>,
3466    ) -> anyhow::Result<OrderBook> {
3467        let inst = self.instrument_from_cache_by_id(instrument_id)?;
3468        let price_precision = inst.price_precision();
3469        let size_precision = inst.size_precision();
3470
3471        let params = GetOrderBookParams {
3472            inst_id: instrument_id.symbol.to_string(),
3473            sz: depth,
3474        };
3475
3476        let resp = self
3477            .inner
3478            .get_order_book(params)
3479            .await
3480            .map_err(|e| anyhow::anyhow!(e))?;
3481
3482        let snapshot = resp
3483            .first()
3484            .ok_or_else(|| anyhow::anyhow!("No order book returned from OKX"))?;
3485
3486        let ts_event = UnixNanos::from(snapshot.ts * NANOSECONDS_IN_MILLISECOND);
3487        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
3488
3489        for (i, level) in snapshot.bids.iter().enumerate() {
3490            let price = parse_price(&level.0, price_precision)?;
3491            let size = parse_quantity(&level.1, size_precision)?;
3492            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
3493            book.add(order, 0, i as u64, ts_event);
3494        }
3495
3496        let bids_len = snapshot.bids.len();
3497
3498        for (i, level) in snapshot.asks.iter().enumerate() {
3499            let price = parse_price(&level.0, price_precision)?;
3500            let size = parse_quantity(&level.1, size_precision)?;
3501            let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
3502            book.add(order, 0, (bids_len + i) as u64, ts_event);
3503        }
3504
3505        log::debug!(
3506            "Fetched order book for {} with {} bids and {} asks",
3507            instrument_id,
3508            snapshot.bids.len(),
3509            snapshot.asks.len(),
3510        );
3511
3512        Ok(book)
3513    }
3514
3515    /// Requests an RPI order book snapshot for the `instrument_id`.
3516    ///
3517    /// # Errors
3518    ///
3519    /// Returns an error if the HTTP request fails or book parsing fails.
3520    pub async fn request_rpi_book_snapshot(
3521        &self,
3522        instrument_id: InstrumentId,
3523        depth: Option<u32>,
3524    ) -> anyhow::Result<OrderBook> {
3525        let inst = self.instrument_from_cache_by_id(instrument_id)?;
3526        let price_precision = inst.price_precision();
3527        let size_precision = inst.size_precision();
3528        let params = GetRpiOrderBookParams {
3529            inst_id: instrument_id.symbol.to_string(),
3530            sz: depth,
3531        };
3532        let resp = self
3533            .inner
3534            .get_rpi_order_book(params)
3535            .await
3536            .map_err(|e| anyhow::anyhow!(e))?;
3537        let snapshot = resp
3538            .first()
3539            .ok_or_else(|| anyhow::anyhow!("No RPI order book returned from OKX"))?;
3540        let ts_event = UnixNanos::from(snapshot.ts * NANOSECONDS_IN_MILLISECOND);
3541        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
3542
3543        for (i, level) in snapshot.bids.iter().enumerate() {
3544            let price = Price::from_decimal_dp(level.0, price_precision)?;
3545            let size = Quantity::from_decimal_dp(level.1, size_precision)?;
3546            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
3547            book.add(order, 0, i as u64, ts_event);
3548        }
3549
3550        let bids_len = snapshot.bids.len();
3551        for (i, level) in snapshot.asks.iter().enumerate() {
3552            let price = Price::from_decimal_dp(level.0, price_precision)?;
3553            let size = Quantity::from_decimal_dp(level.1, size_precision)?;
3554            let index = (bids_len + i) as u64;
3555            let order = BookOrder::new(OrderSide::Sell, price, size, index);
3556            book.add(order, 0, index, ts_event);
3557        }
3558
3559        log::debug!(
3560            "Fetched RPI order book for {} with {} bids and {} asks",
3561            instrument_id,
3562            snapshot.bids.len(),
3563            snapshot.asks.len(),
3564        );
3565
3566        Ok(book)
3567    }
3568
3569    /// Requests an order book snapshot as `OrderBookDeltas` for the `instrument_id`.
3570    ///
3571    /// # Errors
3572    ///
3573    /// Returns an error if the HTTP request fails or parsing fails.
3574    pub async fn request_orderbook_snapshot(
3575        &self,
3576        instrument_id: InstrumentId,
3577        depth: Option<u32>,
3578    ) -> anyhow::Result<OrderBookDeltas> {
3579        let inst = self.instrument_from_cache_by_id(instrument_id)?;
3580        let price_precision = inst.price_precision();
3581        let size_precision = inst.size_precision();
3582
3583        let params = GetOrderBookParams {
3584            inst_id: instrument_id.symbol.to_string(),
3585            sz: depth,
3586        };
3587
3588        let resp = self
3589            .inner
3590            .get_order_book(params)
3591            .await
3592            .map_err(|e| anyhow::anyhow!(e))?;
3593
3594        let snapshot = resp
3595            .first()
3596            .ok_or_else(|| anyhow::anyhow!("No order book returned from OKX"))?;
3597
3598        let ts_event = UnixNanos::from(snapshot.ts * NANOSECONDS_IN_MILLISECOND);
3599        let total_levels = snapshot.bids.len() + snapshot.asks.len();
3600        let mut deltas = Vec::with_capacity(total_levels + 1);
3601
3602        let mut clear = OrderBookDelta::clear(instrument_id, 0, ts_event, ts_event);
3603
3604        if total_levels == 0 {
3605            clear.flags |= RecordFlag::F_LAST as u8;
3606        }
3607        deltas.push(clear);
3608
3609        let mut processed = 0_usize;
3610
3611        for (i, level) in snapshot.bids.iter().enumerate() {
3612            let price = parse_price(&level.0, price_precision)?;
3613            let size = parse_quantity(&level.1, size_precision)?;
3614            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
3615            processed += 1;
3616            let mut flags = RecordFlag::F_SNAPSHOT as u8;
3617
3618            if processed == total_levels {
3619                flags |= RecordFlag::F_LAST as u8;
3620            }
3621            deltas.push(OrderBookDelta::new(
3622                instrument_id,
3623                BookAction::Add,
3624                order,
3625                flags,
3626                0,
3627                ts_event,
3628                ts_event,
3629            ));
3630        }
3631
3632        let bids_len = snapshot.bids.len();
3633
3634        for (i, level) in snapshot.asks.iter().enumerate() {
3635            let price = parse_price(&level.0, price_precision)?;
3636            let size = parse_quantity(&level.1, size_precision)?;
3637            let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
3638            processed += 1;
3639            let mut flags = RecordFlag::F_SNAPSHOT as u8;
3640
3641            if processed == total_levels {
3642                flags |= RecordFlag::F_LAST as u8;
3643            }
3644            deltas.push(OrderBookDelta::new(
3645                instrument_id,
3646                BookAction::Add,
3647                order,
3648                flags,
3649                0,
3650                ts_event,
3651                ts_event,
3652            ));
3653        }
3654
3655        log::debug!(
3656            "Fetched order book snapshot for {} with {} bids and {} asks",
3657            instrument_id,
3658            snapshot.bids.len(),
3659            snapshot.asks.len(),
3660        );
3661
3662        OrderBookDeltas::new_checked(instrument_id, deltas)
3663            .context("failed to assemble OrderBookDeltas from OKX snapshot")
3664    }
3665
3666    /// Requests historical funding rates for the `instrument_id`.
3667    ///
3668    /// # Errors
3669    ///
3670    /// Returns an error if the HTTP request fails or parsing fails.
3671    pub async fn request_funding_rates(
3672        &self,
3673        instrument_id: InstrumentId,
3674        start: Option<Timestamp>,
3675        end: Option<Timestamp>,
3676        limit: Option<u32>,
3677    ) -> anyhow::Result<Vec<FundingRateUpdate>> {
3678        self.request_funding_rates_with_coverage(instrument_id, start, end, limit)
3679            .await
3680            .map(|(rates, _)| rates)
3681    }
3682
3683    /// Requests funding rates like [`Self::request_funding_rates`] and reports whether the
3684    /// single page covered the window down to `start`: the page is not full and its oldest
3685    /// record is within one funding interval of `start`. A full page that ends after `start`
3686    /// is truncated.
3687    ///
3688    /// # Errors
3689    ///
3690    /// Returns an error if the HTTP request fails or parsing fails.
3691    pub async fn request_funding_rates_with_coverage(
3692        &self,
3693        instrument_id: InstrumentId,
3694        start: Option<Timestamp>,
3695        end: Option<Timestamp>,
3696        limit: Option<u32>,
3697    ) -> anyhow::Result<(Vec<FundingRateUpdate>, OKXHistoryCoverage)> {
3698        // OKX returns at most 400 records a page, which is also its default when no limit is set
3699        const OKX_FUNDING_PAGE_SIZE: usize = 400;
3700
3701        let mut params = GetFundingRateHistoryParams {
3702            inst_id: instrument_id.symbol.to_string(),
3703            ..Default::default()
3704        };
3705
3706        // OKX uses "before" for newer-than and "after" for older-than, both exclusive, so widen
3707        // each bound by 1 ms to keep records that fall exactly on the window bounds
3708        if let Some(start) = start {
3709            params.before = Some(start.as_millisecond().saturating_sub(1).max(0).to_string());
3710        }
3711
3712        if let Some(end) = end {
3713            params.after = Some(end.as_millisecond().saturating_add(1).to_string());
3714        }
3715
3716        params.limit = limit;
3717
3718        let resp = self
3719            .inner
3720            .get_funding_rate_history(params)
3721            .await
3722            .map_err(|e| anyhow::anyhow!(e))?;
3723
3724        let mut rates = Vec::with_capacity(resp.len());
3725
3726        for window in resp.windows(2) {
3727            let raw = &window[0];
3728            let interval_millis = raw
3729                .funding_time
3730                .checked_sub(window[1].funding_time)
3731                .context("funding interval negative, funding rates out of order")?;
3732            let rate = parse_funding_rate(raw, instrument_id, Some(interval_millis))?;
3733            rates.push(rate);
3734        }
3735
3736        if let Some(last_raw) = resp.last() {
3737            // oldest funding update has no previous one to compute interval
3738            let rate = parse_funding_rate(last_raw, instrument_id, None)?;
3739            rates.push(rate);
3740        }
3741
3742        // OKX returns newest-first; reverse to chronological order so that
3743        // cache.add_funding_rates (which push_fronts) leaves the newest at front
3744        rates.reverse();
3745
3746        log::debug!(
3747            "Fetched {} funding rates for {}",
3748            rates.len(),
3749            instrument_id,
3750        );
3751
3752        let coverage = match (start, rates.first()) {
3753            (Some(start), Some(oldest)) if limit.is_none() => {
3754                let start_ns = start.as_nanosecond();
3755                let oldest_ns = i128::from(oldest.ts_event.as_u64());
3756
3757                if resp.len() >= OKX_FUNDING_PAGE_SIZE && oldest_ns > start_ns {
3758                    OKXHistoryCoverage::Truncated
3759                } else if let Some(interval_mins) = rates.get(1).and_then(|rate| rate.interval)
3760                    && oldest_ns < start_ns + i128::from(interval_mins) * 60_000_000_000
3761                {
3762                    OKXHistoryCoverage::Complete
3763                } else {
3764                    OKXHistoryCoverage::Unverified
3765                }
3766            }
3767            _ => OKXHistoryCoverage::Unverified,
3768        };
3769
3770        // A start with sub-millisecond precision lets the settlement just before it through the
3771        // widened lower bound. That record shows the page reached the start, so it is dropped
3772        // only after the coverage check above
3773        if let Some(start) = start {
3774            let start_ns = start.as_nanosecond();
3775            rates.retain(|rate| i128::from(rate.ts_event.as_u64()) >= start_ns);
3776        }
3777
3778        Ok((rates, coverage))
3779    }
3780
3781    /// Requests trades for the `instrument_id` and `start` -> `end` time range.
3782    ///
3783    /// Each trade uses its own time as `ts_init`, since the data engine trims responses to the
3784    /// requested window on `ts_init`.
3785    ///
3786    /// # Errors
3787    ///
3788    /// Returns an error if the HTTP request fails or trade parsing fails.
3789    pub async fn request_trades(
3790        &self,
3791        instrument_id: InstrumentId,
3792        start: Option<Timestamp>,
3793        end: Option<Timestamp>,
3794        limit: Option<u32>,
3795    ) -> anyhow::Result<Vec<TradeTick>> {
3796        self.request_trades_with_coverage(instrument_id, start, end, limit)
3797            .await
3798            .map(|(trades, _)| trades)
3799    }
3800
3801    /// Requests trades like [`Self::request_trades`] and reports whether the backward
3802    /// pagination covered the window down to `start`.
3803    ///
3804    /// # Errors
3805    ///
3806    /// Returns an error if the HTTP request fails or trade parsing fails.
3807    pub async fn request_trades_with_coverage(
3808        &self,
3809        instrument_id: InstrumentId,
3810        start: Option<Timestamp>,
3811        end: Option<Timestamp>,
3812        limit: Option<u32>,
3813    ) -> anyhow::Result<(Vec<TradeTick>, OKXHistoryCoverage)> {
3814        const MAX_PAGES: usize = 500;
3815
3816        self.request_trades_paged(instrument_id, start, end, limit, MAX_PAGES)
3817            .await
3818    }
3819
3820    async fn request_trades_paged(
3821        &self,
3822        instrument_id: InstrumentId,
3823        start: Option<Timestamp>,
3824        end: Option<Timestamp>,
3825        limit: Option<u32>,
3826        max_pages: usize,
3827    ) -> anyhow::Result<(Vec<TradeTick>, OKXHistoryCoverage)> {
3828        const OKX_TRADES_MAX_LIMIT: u32 = 100;
3829        const MAX_CONSECUTIVE_EMPTY: usize = 3;
3830
3831        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
3832        enum Mode {
3833            Latest,
3834            Backward,
3835            Range,
3836        }
3837
3838        let limit = if limit == Some(0) { None } else { limit };
3839
3840        if let (Some(s), Some(e)) = (start, end) {
3841            anyhow::ensure!(s < e, "Invalid time range: start={s:?} end={e:?}");
3842        }
3843
3844        let now = self.inner.clock.get_time_ns().to_datetime_utc();
3845
3846        if let Some(s) = start
3847            && s > now
3848        {
3849            return Ok((Vec::new(), OKXHistoryCoverage::Unverified));
3850        }
3851
3852        let end = if let Some(e) = end
3853            && e > now
3854        {
3855            Some(now)
3856        } else {
3857            end
3858        };
3859
3860        let mode = match (start, end) {
3861            (None, None) => Mode::Latest,
3862            (Some(_), None) => Mode::Backward,
3863            (None, Some(_)) => Mode::Backward,
3864            (Some(_), Some(_)) => Mode::Range,
3865        };
3866
3867        let start_ms = start.map(jiff::Timestamp::as_millisecond);
3868        let end_ms = end.map(jiff::Timestamp::as_millisecond);
3869
3870        let inst = self.instrument_from_cache_by_id(instrument_id)?;
3871
3872        // Historical pagination walks backwards using trade IDs, OKX does not honor timestamps for
3873        // standalone `before` requests (type=2)
3874        if matches!(mode, Mode::Backward | Mode::Range) {
3875            let mut before_trade_id: Option<String> = None;
3876            let mut pages = 0usize;
3877            let mut page_results: Vec<Vec<TradeTick>> = Vec::new();
3878            let mut seen_trades: AHashSet<(String, i64)> = AHashSet::new();
3879            let mut unique_count = 0usize;
3880            let mut consecutive_empty_pages = 0usize;
3881            let mut coverage = OKXHistoryCoverage::Unverified;
3882            let mut parse_failures = 0usize;
3883
3884            // Only apply default limit when there's no start boundary
3885            // (start provides a natural stopping point, end alone allows infinite backward pagination)
3886            let effective_limit = if start.is_some() {
3887                limit.unwrap_or(u32::MAX)
3888            } else {
3889                limit.unwrap_or(OKX_TRADES_MAX_LIMIT)
3890            };
3891
3892            log::debug!(
3893                "Starting trades pagination: mode={mode:?}, start={start:?}, end={end:?}, limit={limit:?}, effective_limit={effective_limit}"
3894            );
3895
3896            loop {
3897                // A limit met on the last allowed page is a complete answer, not a cut one
3898                if effective_limit < u32::MAX && unique_count >= effective_limit as usize {
3899                    log::debug!("Reached effective limit: unique_count={unique_count}");
3900                    break;
3901                }
3902
3903                if pages >= max_pages {
3904                    log::warn!("Hit page limit of {max_pages}");
3905                    coverage = OKXHistoryCoverage::Truncated;
3906                    break;
3907                }
3908
3909                let remaining = (effective_limit as usize).saturating_sub(unique_count);
3910                let page_cap = remaining.min(OKX_TRADES_MAX_LIMIT as usize) as u32;
3911
3912                log::debug!(
3913                    "Requesting page {}: before_id={:?}, page_cap={}, unique_count={}",
3914                    pages + 1,
3915                    before_trade_id,
3916                    page_cap,
3917                    unique_count
3918                );
3919
3920                let mut params_builder = GetTradesParamsBuilder::default();
3921                params_builder
3922                    .inst_id(instrument_id.symbol.inner())
3923                    .limit(page_cap)
3924                    .pagination_type(1);
3925
3926                // Use 'after' to get older trades (OKX API: after=cursor means < cursor)
3927                if let Some(ref before_id) = before_trade_id {
3928                    params_builder.after(before_id.clone());
3929                }
3930
3931                let params = params_builder.build().map_err(anyhow::Error::new)?;
3932                let raw = self
3933                    .inner
3934                    .get_history_trades(params)
3935                    .await
3936                    .map_err(anyhow::Error::new)?;
3937
3938                log::debug!("Received {} raw trades from API", raw.len());
3939
3940                if let (Some(first), Some(last)) = (raw.first(), raw.last()) {
3941                    log::debug!(
3942                        "Raw response trade ID range: first={} (newest), last={} (oldest)",
3943                        first.trade_id,
3944                        last.trade_id,
3945                    );
3946                }
3947
3948                if raw.is_empty() {
3949                    log::debug!("API returned empty page, stopping pagination");
3950                    break;
3951                }
3952
3953                pages += 1;
3954
3955                let mut page_trades: Vec<TradeTick> = Vec::with_capacity(raw.len());
3956                let mut hit_start_boundary = false;
3957                let mut filtered_out = 0usize;
3958                let mut duplicates = 0usize;
3959
3960                for r in &raw {
3961                    // Historical trades use their own time as ts_init: the data engine trims
3962                    // responses to the requested window on ts_init
3963                    match parse_trade_tick(
3964                        r,
3965                        instrument_id,
3966                        inst.price_precision(),
3967                        inst.size_precision(),
3968                        parse_millisecond_timestamp(r.ts),
3969                    ) {
3970                        Ok(trade) => {
3971                            let ts_ms = trade.ts_event.as_i64() / 1_000_000;
3972
3973                            if let Some(e_ms) = end_ms
3974                                && ts_ms > e_ms
3975                            {
3976                                filtered_out += 1;
3977                                continue;
3978                            }
3979
3980                            if let Some(s_ms) = start_ms
3981                                && ts_ms < s_ms
3982                            {
3983                                hit_start_boundary = true;
3984                                filtered_out += 1;
3985                                break;
3986                            }
3987
3988                            let trade_key = (trade.trade_id.to_string(), trade.ts_event.as_i64());
3989                            if seen_trades.insert(trade_key) {
3990                                unique_count += 1;
3991                                page_trades.push(trade);
3992                            } else {
3993                                duplicates += 1;
3994                            }
3995                        }
3996                        Err(e) => {
3997                            parse_failures += 1;
3998                            log::error!("{e}");
3999                        }
4000                    }
4001                }
4002
4003                log::debug!(
4004                    "Page {} processed: {} trades kept, {} filtered out, {} duplicates, hit_start_boundary={}",
4005                    pages,
4006                    page_trades.len(),
4007                    filtered_out,
4008                    duplicates,
4009                    hit_start_boundary
4010                );
4011
4012                if hit_start_boundary {
4013                    coverage = OKXHistoryCoverage::Complete;
4014                }
4015
4016                // Extract oldest unique trade ID for next page cursor
4017                let oldest_trade_id = if page_trades.is_empty() {
4018                    // Only apply consecutive empty guard if we've already collected some trades
4019                    // This allows historical backfills to paginate through empty prelude
4020                    if unique_count > 0 {
4021                        consecutive_empty_pages += 1;
4022                        if consecutive_empty_pages >= MAX_CONSECUTIVE_EMPTY {
4023                            log::debug!(
4024                                "Stopping: {consecutive_empty_pages} consecutive pages with no trades in range after collecting {unique_count} trades"
4025                            );
4026                            break;
4027                        }
4028                    }
4029                    // No unique trades on page, use raw response for cursor
4030                    raw.last().map(|t| {
4031                        let id = t.trade_id.to_string();
4032                        log::debug!(
4033                            "Setting cursor from raw response (no unique trades): oldest_id={id}"
4034                        );
4035                        id
4036                    })
4037                } else {
4038                    // Use oldest deduplicated trade ID before reversing
4039                    let oldest_id = page_trades.last().map(|t| {
4040                        let id = t.trade_id.to_string();
4041                        log::debug!(
4042                            "Setting cursor from deduplicated trades: oldest_id={}, ts_event={}",
4043                            id,
4044                            t.ts_event.as_i64()
4045                        );
4046                        id
4047                    });
4048                    page_trades.reverse();
4049                    page_results.push(page_trades);
4050                    consecutive_empty_pages = 0;
4051                    oldest_id
4052                };
4053
4054                if let Some(ref old_id) = before_trade_id
4055                    && oldest_trade_id.as_ref() == Some(old_id)
4056                {
4057                    break;
4058                }
4059
4060                if oldest_trade_id.is_none() {
4061                    break;
4062                }
4063
4064                before_trade_id = oldest_trade_id;
4065
4066                if hit_start_boundary {
4067                    break;
4068                }
4069
4070                time::sleep(time::Duration::from_millis(50)).await;
4071            }
4072
4073            log::debug!(
4074                "Pagination complete: {pages} pages, {unique_count} unique trades collected"
4075            );
4076
4077            let mut out: Vec<TradeTick> = Vec::new();
4078
4079            for page in page_results.into_iter().rev() {
4080                out.extend(page);
4081            }
4082
4083            // Deduplicate by (trade_id, ts_event) composite key
4084            let mut dedup_keys = AHashSet::new();
4085            let pre_dedup_len = out.len();
4086            out.retain(|trade| {
4087                dedup_keys.insert((trade.trade_id.to_string(), trade.ts_event.as_i64()))
4088            });
4089
4090            if out.len() < pre_dedup_len {
4091                log::debug!(
4092                    "Removed {} duplicate trades during final dedup",
4093                    pre_dedup_len - out.len()
4094                );
4095            }
4096
4097            if let Some(lim) = limit
4098                && lim > 0
4099                && out.len() > lim as usize
4100            {
4101                let excess = out.len() - lim as usize;
4102                log::debug!("Trimming {excess} oldest trades to respect limit={lim}");
4103                out.drain(0..excess);
4104            }
4105
4106            // A trade dropped on a parse error leaves a gap the window cannot vouch for
4107            if parse_failures > 0 && coverage == OKXHistoryCoverage::Complete {
4108                coverage = OKXHistoryCoverage::Unverified;
4109            }
4110
4111            log::debug!("Returning {} trades, coverage={coverage:?}", out.len());
4112            return Ok((out, coverage));
4113        }
4114
4115        let req_limit = limit
4116            .unwrap_or(OKX_TRADES_MAX_LIMIT)
4117            .min(OKX_TRADES_MAX_LIMIT);
4118        let params = GetTradesParamsBuilder::default()
4119            .inst_id(instrument_id.symbol.inner())
4120            .limit(req_limit)
4121            .build()
4122            .map_err(anyhow::Error::new)?;
4123
4124        let raw = self
4125            .inner
4126            .get_history_trades(params)
4127            .await
4128            .map_err(anyhow::Error::new)?;
4129
4130        let mut trades: Vec<TradeTick> = Vec::with_capacity(raw.len());
4131
4132        for r in &raw {
4133            match parse_trade_tick(
4134                r,
4135                instrument_id,
4136                inst.price_precision(),
4137                inst.size_precision(),
4138                parse_millisecond_timestamp(r.ts),
4139            ) {
4140                Ok(trade) => trades.push(trade),
4141                Err(e) => log::error!("{e}"),
4142            }
4143        }
4144
4145        // OKX returns newest-first, reverse to oldest-first
4146        trades.reverse();
4147
4148        if let Some(lim) = limit
4149            && lim > 0
4150            && trades.len() > lim as usize
4151        {
4152            trades.drain(0..trades.len() - lim as usize);
4153        }
4154
4155        Ok((trades, OKXHistoryCoverage::Unverified))
4156    }
4157
4158    /// Requests historical bars for the given bar type and time range.
4159    ///
4160    /// The aggregation source must be `EXTERNAL`. Time range validation ensures start < end.
4161    /// Returns bars sorted oldest to newest.
4162    /// Each bar uses the candle open time as `ts_event` and its close time as `ts_init`.
4163    /// Requests without an end may include an unconfirmed candle with a future `ts_init`.
4164    /// With bounds, candle close times (`ts_init`) are within `[start, end]`, the window the data
4165    /// engine trims responses to, so the first candle may open before `start`.
4166    ///
4167    /// # Errors
4168    ///
4169    /// Returns an error if the request fails.
4170    ///
4171    /// # Endpoint Selection
4172    ///
4173    /// Normal pagination selects between endpoints with different limits:
4174    /// - Regular endpoint (`/api/v5/market/candles`): ≤ 300 rows/call, ≤ 40 req/2s
4175    ///   - Used when the pagination cursor is less than two hours old
4176    /// - History endpoint (`/api/v5/market/history-candles`): ≤ 100 rows/call, ≤ 20 req/2s
4177    ///   - Used when the pagination cursor is at least two hours old
4178    ///
4179    /// Cursor age uses the clock time captured when the request starts. Empty-page fallbacks
4180    /// can select a different endpoint.
4181    ///
4182    /// # Supported Aggregations
4183    ///
4184    /// Maps to OKX bar query parameter:
4185    /// - `Second` → `{n}s`
4186    /// - `Minute` → `{n}m`
4187    /// - `Hour` → `{n}H`
4188    /// - `Day` → `{n}D`
4189    /// - `Week` → `{n}W`
4190    /// - `Month` → `{n}M`
4191    ///
4192    /// # Pagination
4193    ///
4194    /// - Range requests use exclusive `after` and `before` cursors, setting `before` one bar before
4195    ///   the floored start (two for months) so the first candle that closes at or after the start
4196    ///   is included
4197    /// - Pages backwards from end time (or now) to start time
4198    /// - Stops when: limit reached, time window covered, or API returns empty
4199    /// - Rate limit safety: ≥ 50ms between requests
4200    ///
4201    /// # References
4202    ///
4203    /// - <https://tr.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks>
4204    /// - <https://tr.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks-history>
4205    pub async fn request_bars(
4206        &self,
4207        bar_type: BarType,
4208        start: Option<Timestamp>,
4209        end: Option<Timestamp>,
4210        limit: Option<u32>,
4211    ) -> anyhow::Result<Vec<Bar>> {
4212        self.request_bars_with_coverage(bar_type, start, end, limit)
4213            .await
4214            .map(|(bars, _)| bars)
4215    }
4216
4217    /// Requests bars like [`Self::request_bars`] and reports whether the pagination
4218    /// covered the window down to `start`: the oldest bar returned closes in the first
4219    /// bar slot at or after `start`. A window is never reported as covered when a limit ended
4220    /// the request, when it holds a candle OKX has not confirmed, or for months, since month
4221    /// lengths vary.
4222    ///
4223    /// # Errors
4224    ///
4225    /// Returns an error if the request fails.
4226    pub async fn request_bars_with_coverage(
4227        &self,
4228        bar_type: BarType,
4229        start: Option<Timestamp>,
4230        end: Option<Timestamp>,
4231        limit: Option<u32>,
4232    ) -> anyhow::Result<(Vec<Bar>, OKXHistoryCoverage)> {
4233        const MAX_PAGES_SOFT: usize = 500;
4234
4235        self.request_bars_paged(bar_type, start, end, limit, MAX_PAGES_SOFT)
4236            .await
4237    }
4238
4239    async fn request_bars_paged(
4240        &self,
4241        bar_type: BarType,
4242        start: Option<Timestamp>,
4243        mut end: Option<Timestamp>,
4244        limit: Option<u32>,
4245        max_pages: usize,
4246    ) -> anyhow::Result<(Vec<Bar>, OKXHistoryCoverage)> {
4247        const HISTORY_SPLIT_DAYS: i64 = 100;
4248
4249        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
4250        enum Mode {
4251            Latest,
4252            Backward,
4253            Range,
4254        }
4255
4256        let limit = if limit == Some(0) { None } else { limit };
4257
4258        anyhow::ensure!(
4259            bar_type.aggregation_source() == AggregationSource::External,
4260            "Only EXTERNAL aggregation is supported"
4261        );
4262
4263        if let (Some(s), Some(e)) = (start, end) {
4264            anyhow::ensure!(s < e, "Invalid time range: start={s:?} end={e:?}");
4265        }
4266
4267        let now = self.inner.clock.get_time_ns().to_datetime_utc();
4268
4269        if let Some(s) = start
4270            && s > now
4271        {
4272            return Ok((Vec::new(), OKXHistoryCoverage::Unverified));
4273        }
4274
4275        if let Some(e) = end
4276            && e > now
4277        {
4278            end = Some(now);
4279        }
4280
4281        let spec = bar_type.spec();
4282        let step = spec.step.get();
4283        let bar_param = match spec.aggregation {
4284            BarAggregation::Second => format!("{step}s"),
4285            BarAggregation::Minute => format!("{step}m"),
4286            BarAggregation::Hour => format!("{step}H"),
4287            BarAggregation::Day => format!("{step}D"),
4288            BarAggregation::Week => format!("{step}W"),
4289            BarAggregation::Month => format!("{step}M"),
4290            a => anyhow::bail!("OKX does not support {a:?} aggregation"),
4291        };
4292
4293        let slot_ms: i64 = match spec.aggregation {
4294            BarAggregation::Second => (step as i64) * 1_000,
4295            BarAggregation::Minute => (step as i64) * 60_000,
4296            BarAggregation::Hour => (step as i64) * 3_600_000,
4297            BarAggregation::Day => (step as i64) * 86_400_000,
4298            BarAggregation::Week => (step as i64) * 7 * 86_400_000,
4299            BarAggregation::Month => (step as i64) * 30 * 86_400_000,
4300            _ => unreachable!("Unsupported aggregation should have been caught above"),
4301        };
4302        let slot_ns: i64 = slot_ms * 1_000_000;
4303
4304        let mode = match (start, end) {
4305            (None, None) => Mode::Latest,
4306            (Some(_), None) => Mode::Backward, // Changed: when only start is provided, work backward from now
4307            (None, Some(_)) => Mode::Backward,
4308            (Some(_), Some(_)) => Mode::Range,
4309        };
4310
4311        let start_ns = start.and_then(|s| i64::try_from(s.as_nanosecond()).ok());
4312        let end_ns = end.and_then(|e| i64::try_from(e.as_nanosecond()).ok());
4313
4314        // Floor start to bar boundaries for cleaner API requests, then step back one bar: OKX
4315        // filters candles by open time, while the window is defined on the close (`ts_init`),
4316        // so the bar that closes at or just after the start opens before it. The month slot is
4317        // an approximate 30 days, so months step back two slots to cover 31-day months
4318        let is_month = spec.aggregation == BarAggregation::Month;
4319        let lookback_ms = if is_month { 2 * slot_ms } else { slot_ms };
4320        // The shortest bar length: the earliest bar in the window closes within it of the start
4321        let min_slot_ns = if is_month {
4322            (step as i64) * 28 * 86_400_000 * 1_000_000
4323        } else {
4324            slot_ns
4325        };
4326        let start_ms = start.map(|s| {
4327            let ms = s.as_millisecond();
4328
4329            if slot_ms > 0 {
4330                ((ms / slot_ms) * slot_ms)
4331                    .saturating_sub(lookback_ms)
4332                    .max(0)
4333            } else {
4334                ms
4335            }
4336        });
4337
4338        let end_ms = end.map(Timestamp::as_millisecond);
4339        let now_ms = now.as_millisecond();
4340
4341        let instrument_id = bar_type.instrument_id();
4342        let symbol = instrument_id.symbol;
4343        let inst = self.instrument_from_cache_by_id(instrument_id)?;
4344
4345        let mut out: Vec<Bar> = Vec::new();
4346        let mut pages = 0usize;
4347
4348        // IMPORTANT: OKX API has COUNTER-INTUITIVE semantics (same for bars and trades):
4349        // - after=X returns records with timestamp < X (upper bound, despite the name!)
4350        // - before=X returns records with timestamp > X (lower bound, despite the name!)
4351        // For Range [start, end], use: before=start (lower bound), after=end (upper bound)
4352        let mut after_ms: Option<i64> = match mode {
4353            Mode::Range => end_ms.or(Some(now_ms)), // Upper bound: bars < end
4354            _ => None,
4355        };
4356        let mut before_ms: Option<i64> = match mode {
4357            Mode::Backward => end_ms.map(|v| v.saturating_sub(1)),
4358            Mode::Range => start_ms.map(|v| v.saturating_sub(1)),
4359            Mode::Latest => None,
4360        };
4361
4362        // For Range mode, we'll paginate backwards like Backward mode
4363        let forward_prepend_mode = matches!(mode, Mode::Range);
4364
4365        // Adjust before_ms to ensure we get data from the API
4366        // OKX API might not have bars for the very recent past
4367        // This handles both explicit end=now and the actor layer setting end=now when it's None
4368        if matches!(mode, Mode::Backward | Mode::Range)
4369            && let Some(b) = before_ms
4370        {
4371            // OKX endpoints have different data availability windows:
4372            // - Regular endpoint: has most recent data but limited depth
4373            // - History endpoint: has deep history but lags behind current time
4374            // Use a small buffer to avoid the "dead zone"
4375            let buffer_ms = slot_ms.max(60_000); // At least 1 minute or 1 bar
4376            if b >= now_ms.saturating_sub(buffer_ms) {
4377                before_ms = Some(now_ms.saturating_sub(buffer_ms));
4378            }
4379        }
4380
4381        let mut have_latest_first_page = false;
4382        let mut progressless_loops = 0u8;
4383        let mut truncated = false;
4384        // Open times of candles OKX has not confirmed yet; they rule out a covered window
4385        let mut unconfirmed: Vec<UnixNanos> = Vec::new();
4386
4387        loop {
4388            if let Some(lim) = limit
4389                && lim > 0
4390                && out.len() >= lim as usize
4391            {
4392                break;
4393            }
4394
4395            if pages >= max_pages {
4396                log::warn!("Hit page limit of {max_pages}");
4397                truncated = true;
4398                break;
4399            }
4400
4401            let pivot_ms = if let Some(a) = after_ms {
4402                a
4403            } else if let Some(b) = before_ms {
4404                b
4405            } else {
4406                now_ms
4407            };
4408            // Choose endpoint based on how old the data is:
4409            // - Use regular endpoint for recent data (< 1 hour old)
4410            // - Use history endpoint for older data (> 1 hour old)
4411            // This avoids the "gap" where history endpoint has no recent data
4412            // and regular endpoint has limited depth
4413            let age_ms = now_ms.saturating_sub(pivot_ms);
4414            let age_hours = age_ms / (60 * 60 * 1000);
4415            let using_history = age_hours > 1; // Use history if data is > 1 hour old
4416
4417            let page_ceiling = if using_history { 100 } else { 300 };
4418            let remaining = limit
4419                .filter(|&l| l > 0) // Treat limit=0 as no limit
4420                .map_or(page_ceiling, |l| (l as usize).saturating_sub(out.len()));
4421            let page_cap = remaining.min(page_ceiling);
4422
4423            let mut p = GetCandlesticksParamsBuilder::default();
4424            p.inst_id(symbol.as_str())
4425                .bar(&bar_param)
4426                .limit(page_cap as u32);
4427
4428            // Track whether this planned request uses BEFORE or AFTER.
4429            let mut req_used_before = false;
4430
4431            match mode {
4432                Mode::Latest => {
4433                    if have_latest_first_page && let Some(b) = before_ms {
4434                        p.before_ms(b);
4435                        req_used_before = true;
4436                    }
4437                }
4438                Mode::Backward => {
4439                    // Use 'after' to get older bars (OKX API: after=cursor means < cursor)
4440                    if let Some(b) = before_ms {
4441                        p.after_ms(b);
4442                    }
4443                }
4444                Mode::Range => {
4445                    // For Range mode, use both after and before to specify the full range
4446                    // This is much more efficient than pagination
4447                    if let Some(a) = after_ms {
4448                        p.after_ms(a);
4449                    }
4450
4451                    if let Some(b) = before_ms {
4452                        p.before_ms(b);
4453                        req_used_before = true;
4454                    }
4455                }
4456            }
4457
4458            let params = p.build().map_err(anyhow::Error::new)?;
4459
4460            let mut raw = if using_history {
4461                self.inner
4462                    .get_history_candles(params.clone())
4463                    .await
4464                    .map_err(anyhow::Error::new)?
4465            } else {
4466                self.inner
4467                    .get_candles(params.clone())
4468                    .await
4469                    .map_err(anyhow::Error::new)?
4470            };
4471
4472            // --- Fallbacks on empty page ---
4473            if raw.is_empty() {
4474                // LATEST: retry same cursor via history, then step back a page-interval before giving up
4475                if matches!(mode, Mode::Latest)
4476                    && have_latest_first_page
4477                    && !using_history
4478                    && let Some(b) = before_ms
4479                {
4480                    let mut p2 = GetCandlesticksParamsBuilder::default();
4481                    p2.inst_id(symbol.as_str())
4482                        .bar(&bar_param)
4483                        .limit(page_cap as u32);
4484                    p2.before_ms(b);
4485                    let params2 = p2.build().map_err(anyhow::Error::new)?;
4486                    let raw2 = self
4487                        .inner
4488                        .get_history_candles(params2)
4489                        .await
4490                        .map_err(anyhow::Error::new)?;
4491
4492                    if raw2.is_empty() {
4493                        // Step back one page interval and retry loop
4494                        let jump = (page_cap as i64).saturating_mul(slot_ms.max(1));
4495                        before_ms = Some(b.saturating_sub(jump));
4496                        progressless_loops = progressless_loops.saturating_add(1);
4497                        if progressless_loops >= 3 {
4498                            break;
4499                        }
4500                        continue;
4501                    } else {
4502                        raw = raw2;
4503                    }
4504                }
4505
4506                // First LATEST page empty: jump back >100d to force history, then continue loop
4507                if raw.is_empty()
4508                    && matches!(mode, Mode::Latest)
4509                    && !have_latest_first_page
4510                    && !using_history
4511                {
4512                    let jump_days_ms = (HISTORY_SPLIT_DAYS + 1) * 86_400_000;
4513                    before_ms = Some(now_ms.saturating_sub(jump_days_ms));
4514                    have_latest_first_page = true;
4515                    continue;
4516                }
4517
4518                // Still empty for any other case? Just break.
4519                if raw.is_empty() {
4520                    break;
4521                }
4522            }
4523            // --- end fallbacks ---
4524
4525            pages += 1;
4526
4527            // Parse, oldest → newest
4528            let mut page: Vec<Bar> = Vec::with_capacity(raw.len());
4529            for r in &raw {
4530                let bar = parse_historical_candlestick(
4531                    r,
4532                    bar_type,
4533                    inst.price_precision(),
4534                    inst.size_precision(),
4535                )?;
4536
4537                if r.8 != "1" {
4538                    unconfirmed.push(bar.ts_event);
4539                }
4540                page.push(bar);
4541            }
4542            page.reverse();
4543
4544            let page_oldest_ms = page.first().map(|b| b.ts_event.as_i64() / 1_000_000);
4545            let page_newest_ms = page.last().map(|b| b.ts_event.as_i64() / 1_000_000);
4546
4547            let mut filtered: Vec<Bar> = page
4548                .clone()
4549                .into_iter()
4550                .filter(|b| {
4551                    let ts = b.ts_init.as_i64();
4552                    let ok_after = start_ns.is_none_or(|sns| ts >= sns);
4553                    let ok_before = end_ns.is_none_or(|ens| ts <= ens);
4554                    ok_after && ok_before
4555                })
4556                .collect();
4557
4558            if !page.is_empty() && filtered.is_empty() {
4559                // For Range mode, if all bars are before our start time, there's no point continuing
4560                if matches!(mode, Mode::Range)
4561                    && !forward_prepend_mode
4562                    && let (Some(newest_ms), Some(start_ms)) = (page_newest_ms, start_ms)
4563                    && newest_ms < start_ms.saturating_sub(slot_ms * 2)
4564                {
4565                    // Bars are too old (more than 2 bar periods before start), stop
4566                    break;
4567                }
4568            }
4569
4570            // Track contribution for progress guard
4571            let contribution;
4572
4573            if out.is_empty() {
4574                contribution = filtered.len();
4575                out = filtered;
4576            } else {
4577                match mode {
4578                    Mode::Backward | Mode::Latest => {
4579                        if let Some(first) = out.first() {
4580                            filtered.retain(|b| b.ts_event < first.ts_event);
4581                        }
4582                        contribution = filtered.len();
4583                        if contribution != 0 {
4584                            let mut new_out = Vec::with_capacity(out.len() + filtered.len());
4585                            new_out.extend_from_slice(&filtered);
4586                            new_out.extend_from_slice(&out);
4587                            out = new_out;
4588                        }
4589                    }
4590                    Mode::Range => {
4591                        if forward_prepend_mode || req_used_before {
4592                            // We are backfilling older pages: prepend them.
4593                            if let Some(first) = out.first() {
4594                                filtered.retain(|b| b.ts_event < first.ts_event);
4595                            }
4596                            contribution = filtered.len();
4597                            if contribution != 0 {
4598                                let mut new_out = Vec::with_capacity(out.len() + filtered.len());
4599                                new_out.extend_from_slice(&filtered);
4600                                new_out.extend_from_slice(&out);
4601                                out = new_out;
4602                            }
4603                        } else {
4604                            // Normal forward: append newer pages.
4605                            if let Some(last) = out.last() {
4606                                filtered.retain(|b| b.ts_event > last.ts_event);
4607                            }
4608                            contribution = filtered.len();
4609                            out.extend(filtered);
4610                        }
4611                    }
4612                }
4613            }
4614
4615            if contribution == 0 {
4616                // An unaligned end can exclude the newest candle by its close time
4617                match mode {
4618                    Mode::Range => after_ms = page_oldest_ms,
4619                    Mode::Backward => before_ms = page_oldest_ms,
4620                    Mode::Latest => {
4621                        if let Some(b) = before_ms {
4622                            let jump = (page_cap as i64).saturating_mul(slot_ms.max(1));
4623                            before_ms = Some(b.saturating_sub(jump));
4624                        }
4625                    }
4626                }
4627
4628                progressless_loops = progressless_loops.saturating_add(1);
4629                if progressless_loops >= 3 {
4630                    break;
4631                }
4632            } else {
4633                progressless_loops = 0;
4634
4635                // Advance cursors only when we made progress
4636                match mode {
4637                    Mode::Latest | Mode::Backward => {
4638                        if let Some(oldest) = page_oldest_ms {
4639                            before_ms = Some(oldest.saturating_sub(1));
4640                            have_latest_first_page = true;
4641                        } else {
4642                            break;
4643                        }
4644                    }
4645                    Mode::Range => {
4646                        if forward_prepend_mode || req_used_before {
4647                            if let Some(oldest) = page_oldest_ms {
4648                                after_ms = Some(oldest);
4649                            } else {
4650                                break;
4651                            }
4652                        } else if let Some(newest) = page_newest_ms {
4653                            after_ms = Some(newest.saturating_add(1));
4654                            before_ms = None;
4655                        } else {
4656                            break;
4657                        }
4658                    }
4659                }
4660            }
4661
4662            // Stop conditions
4663            if let Some(lim) = limit
4664                && lim > 0
4665                && out.len() >= lim as usize
4666            {
4667                break;
4668            }
4669
4670            if let Some(ens) = end_ns
4671                && let Some(last) = out.last()
4672                && last.ts_event.as_i64() >= ens
4673            {
4674                break;
4675            }
4676
4677            // The earliest bar in the window closes within one bar of the start
4678            if let Some(sns) = start_ns
4679                && let Some(first) = out.first()
4680                && (matches!(mode, Mode::Backward) || forward_prepend_mode)
4681                && first.ts_init.as_i64() < sns.saturating_add(min_slot_ns)
4682            {
4683                break;
4684            }
4685
4686            time::sleep(time::Duration::from_millis(50)).await;
4687        }
4688
4689        // Final rescue for FORWARD/RANGE when nothing gathered
4690        if out.is_empty() && matches!(mode, Mode::Range) {
4691            let pivot = end_ms.unwrap_or(now_ms.saturating_sub(1));
4692            let hist = (now_ms.saturating_sub(pivot)) / (24 * 60 * 60 * 1000) > HISTORY_SPLIT_DAYS;
4693            let mut p = GetCandlesticksParamsBuilder::default();
4694            p.inst_id(symbol.as_str())
4695                .bar(&bar_param)
4696                .limit(300)
4697                .before_ms(pivot);
4698            let params = p.build().map_err(anyhow::Error::new)?;
4699            let raw = if hist {
4700                self.inner.get_history_candles(params).await
4701            } else {
4702                self.inner.get_candles(params).await
4703            }
4704            .map_err(anyhow::Error::new)?;
4705
4706            if !raw.is_empty() {
4707                let mut page: Vec<Bar> = Vec::with_capacity(raw.len());
4708                for r in &raw {
4709                    let bar = parse_historical_candlestick(
4710                        r,
4711                        bar_type,
4712                        inst.price_precision(),
4713                        inst.size_precision(),
4714                    )?;
4715
4716                    if r.8 != "1" {
4717                        unconfirmed.push(bar.ts_event);
4718                    }
4719                    page.push(bar);
4720                }
4721                page.reverse();
4722                out = page
4723                    .into_iter()
4724                    .filter(|b| {
4725                        let ts = b.ts_init.as_i64();
4726                        let ok_after = start_ns.is_none_or(|sns| ts >= sns);
4727                        let ok_before = end_ns.is_none_or(|ens| ts <= ens);
4728                        ok_after && ok_before
4729                    })
4730                    .collect();
4731            }
4732        }
4733
4734        // Trim against end bound if needed (keep ≤ end)
4735        if let Some(ens) = end_ns {
4736            while out.last().is_some_and(|b| b.ts_event.as_i64() > ens) {
4737                out.pop();
4738            }
4739        }
4740
4741        // Clamp first bar for Range when using forward pagination
4742        if matches!(mode, Mode::Range)
4743            && !forward_prepend_mode
4744            && let Some(sns) = start_ns
4745        {
4746            let lower = sns.saturating_sub(slot_ns);
4747            while out.first().is_some_and(|b| b.ts_event.as_i64() < lower) {
4748                out.remove(0);
4749            }
4750        }
4751
4752        // Keep the most recent N bars when limit is specified
4753        if let Some(lim) = limit
4754            && lim > 0
4755            && out.len() > lim as usize
4756        {
4757            let start = out.len() - lim as usize;
4758            out.drain(..start);
4759        }
4760
4761        let limited = limit.is_some_and(|lim| lim > 0 && out.len() >= lim as usize);
4762        let coverage = if truncated {
4763            OKXHistoryCoverage::Truncated
4764        } else if !limited
4765            && !is_month
4766            && !out.iter().any(|bar| unconfirmed.contains(&bar.ts_event))
4767            && let (Some(sns), Some(first)) = (start_ns, out.first())
4768            && first.ts_init.as_i64() < sns.saturating_add(slot_ns)
4769        {
4770            OKXHistoryCoverage::Complete
4771        } else {
4772            OKXHistoryCoverage::Unverified
4773        };
4774
4775        Ok((out, coverage))
4776    }
4777
4778    /// Requests historical order status reports for the given parameters.
4779    ///
4780    /// # Errors
4781    ///
4782    /// Returns an error if the request fails.
4783    ///
4784    /// # References
4785    ///
4786    /// - <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-7-days>.
4787    /// - <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-3-months>.
4788    #[expect(clippy::too_many_arguments)]
4789    pub async fn request_order_status_reports(
4790        &self,
4791        account_id: AccountId,
4792        instrument_type: Option<OKXInstrumentType>,
4793        instrument_id: Option<InstrumentId>,
4794        start: Option<Timestamp>,
4795        end: Option<Timestamp>,
4796        open_only: bool,
4797        limit: Option<u32>,
4798    ) -> anyhow::Result<Vec<OrderStatusReport>> {
4799        Ok(self
4800            .request_order_status_reports_scoped(
4801                account_id,
4802                instrument_type,
4803                instrument_id,
4804                start,
4805                end,
4806                open_only,
4807                limit,
4808                false,
4809                None,
4810                None,
4811            )
4812            .await?
4813            .reports)
4814    }
4815
4816    #[expect(clippy::too_many_arguments)]
4817    pub(crate) async fn request_order_status_reports_scoped(
4818        &self,
4819        account_id: AccountId,
4820        instrument_type: Option<OKXInstrumentType>,
4821        instrument_id: Option<InstrumentId>,
4822        start: Option<Timestamp>,
4823        end: Option<Timestamp>,
4824        open_only: bool,
4825        limit: Option<u32>,
4826        allow_history_failure: bool,
4827        scope: Option<ReportInstrumentScope<'_>>,
4828        max_history_pages: Option<u32>,
4829    ) -> anyhow::Result<ReportSweep<OrderStatusReport>> {
4830        if instrument_id.as_ref().is_some_and(|id| self.is_spread(*id))
4831            || (instrument_id.is_none() && instrument_type.is_none())
4832        {
4833            return self
4834                .request_spread_order_status_reports_scoped(
4835                    account_id,
4836                    instrument_id,
4837                    start,
4838                    end,
4839                    open_only,
4840                    limit,
4841                    allow_history_failure,
4842                    scope,
4843                    max_history_pages,
4844                )
4845                .await;
4846        }
4847
4848        let instrument_type = if let Some(instrument_type) = instrument_type {
4849            instrument_type
4850        } else {
4851            let instrument_id = instrument_id.ok_or_else(|| {
4852                anyhow::anyhow!("Instrument ID required if `instrument_type` not provided")
4853            })?;
4854
4855            let instrument = self.resolve_instrument(instrument_id).await?;
4856
4857            okx_instrument_type(&instrument)?
4858        };
4859
4860        let mut history_base = GetOrderHistoryParamsBuilder::default();
4861        history_base.inst_type(instrument_type);
4862
4863        if let Some(instrument_id) = instrument_id.as_ref() {
4864            history_base.inst_id(instrument_id.symbol.inner().to_string());
4865        }
4866        let history_base = history_base.build().map_err(|e| anyhow::anyhow!(e))?;
4867
4868        let mut pending_base = GetOrderListParamsBuilder::default();
4869        pending_base.inst_type(instrument_type);
4870
4871        if let Some(instrument_id) = instrument_id.as_ref() {
4872            pending_base.inst_id(instrument_id.symbol.inner().to_string());
4873        }
4874        let pending_base = pending_base.build().map_err(|e| anyhow::anyhow!(e))?;
4875
4876        let (pending, history) = if open_only {
4877            (
4878                self.paginate_orders_pending(&pending_base, limit).await?,
4879                None,
4880            )
4881        } else {
4882            let (history, pending) = Box::pin(async {
4883                tokio::join!(
4884                    self.paginate_orders_history(
4885                        &history_base,
4886                        limit,
4887                        reconciliation_history_page_limit(max_history_pages),
4888                    ),
4889                    self.paginate_orders_pending(&pending_base, limit),
4890                )
4891            })
4892            .await;
4893
4894            (pending?, Some(history))
4895        };
4896
4897        anyhow::ensure!(
4898            pending.complete,
4899            "Pending orders did not establish complete coverage"
4900        );
4901
4902        let (history, mut complete) = match history {
4903            Some(Ok(history)) => (history.items, history.complete),
4904            Some(Err(e)) if !allow_history_failure => return Err(e),
4905            Some(Err(e)) => {
4906                log::warn!("Failed to fetch order history: {e}");
4907                (Vec::new(), false)
4908            }
4909            None => (Vec::new(), true),
4910        };
4911
4912        let capacity = pending.items.len() + history.len();
4913        let orders = pending
4914            .items
4915            .into_iter()
4916            .map(|order| (order, true))
4917            .chain(history.into_iter().map(|order| (order, false)));
4918
4919        // Prepare time range filter
4920        let start_ns = start.map(UnixNanos::from);
4921        let end_ns = end.map(UnixNanos::from);
4922
4923        let ts_init = self.generate_ts_init();
4924        let mut reports = Vec::with_capacity(capacity);
4925
4926        // Use a seen filter in case pending orders are within the histories "2hr reserve window"
4927        let mut seen: AHashSet<String> = AHashSet::new();
4928
4929        for (order, from_pending_source) in orders {
4930            let active = is_open_okx_order(order.state, from_pending_source);
4931            let seen_key = [
4932                Some(order.cl_ord_id.as_str()),
4933                order.algo_cl_ord_id.as_ref().map(Ustr::as_str),
4934                order.algo_id.as_ref().map(Ustr::as_str),
4935                Some(order.ord_id.as_str()),
4936            ]
4937            .into_iter()
4938            .flatten()
4939            .find(|value| !value.is_empty())
4940            .unwrap_or_default()
4941            .to_string();
4942
4943            if !seen.insert(seen_key) {
4944                continue; // Reserved pending already reported
4945            }
4946
4947            // Open orders are authoritative regardless of age; only closed
4948            // history respects the report window.
4949            if report_ts_outside_window(order.u_time, start_ns, end_ns) && !active {
4950                continue;
4951            }
4952
4953            let inst = match self
4954                .resolve_report_instrument(order.inst_id, order.inst_type, false, active, scope)
4955                .await?
4956            {
4957                InstrumentResolution::Found(inst) => inst,
4958                InstrumentResolution::Skip => continue,
4959                InstrumentResolution::Incomplete => {
4960                    complete = false;
4961                    continue;
4962                }
4963            };
4964
4965            let mut report = match parse_order_status_report(
4966                &order,
4967                account_id,
4968                inst.id(),
4969                inst.price_precision(),
4970                inst.size_precision(),
4971                ts_init,
4972            ) {
4973                Ok(report) => report,
4974                Err(e) if active => return Err(e),
4975                Err(e) => {
4976                    log::warn!("Failed to parse order status report: {e}");
4977                    complete = false;
4978                    continue;
4979                }
4980            };
4981
4982            apply_post_only_rejection(&order, &mut report);
4983            reports.push(report);
4984        }
4985
4986        Ok(ReportSweep { reports, complete })
4987    }
4988
4989    /// Requests a regular order status report by client order identifier.
4990    ///
4991    /// # Errors
4992    ///
4993    /// Returns an error if the request fails or the report cannot be parsed.
4994    pub async fn request_order_status_report(
4995        &self,
4996        account_id: AccountId,
4997        instrument_id: InstrumentId,
4998        client_order_id: ClientOrderId,
4999    ) -> anyhow::Result<Option<OrderStatusReport>> {
5000        self.request_order_status_report_by_identifier(
5001            account_id,
5002            instrument_id,
5003            Some(client_order_id),
5004            None,
5005        )
5006        .await
5007    }
5008
5009    pub(crate) async fn request_order_status_report_by_venue_order_id(
5010        &self,
5011        account_id: AccountId,
5012        instrument_id: InstrumentId,
5013        venue_order_id: VenueOrderId,
5014    ) -> anyhow::Result<Option<OrderStatusReport>> {
5015        self.request_order_status_report_by_identifier(
5016            account_id,
5017            instrument_id,
5018            None,
5019            Some(venue_order_id),
5020        )
5021        .await
5022    }
5023
5024    async fn request_order_status_report_by_identifier(
5025        &self,
5026        account_id: AccountId,
5027        instrument_id: InstrumentId,
5028        client_order_id: Option<ClientOrderId>,
5029        venue_order_id: Option<VenueOrderId>,
5030    ) -> anyhow::Result<Option<OrderStatusReport>> {
5031        let instrument = self.instrument_from_cache(instrument_id.symbol.inner())?;
5032        let mut params_builder = GetOrderParamsBuilder::default();
5033        params_builder.inst_id(instrument_id.symbol.inner().to_string());
5034
5035        match (client_order_id, venue_order_id) {
5036            (Some(client_order_id), None) => {
5037                params_builder.cl_ord_id(client_order_id.as_str().to_string());
5038            }
5039            (None, Some(venue_order_id)) => {
5040                params_builder.ord_id(venue_order_id.as_str().to_string());
5041            }
5042            _ => anyhow::bail!(
5043                "Exactly one of client_order_id or venue_order_id is required for an order detail request"
5044            ),
5045        }
5046
5047        let params = params_builder
5048            .build()
5049            .map_err(|e| anyhow::anyhow!("Failed to build order detail params: {e}"))?;
5050        let orders = match self.inner.get_order(params).await {
5051            Ok(orders) => orders,
5052            Err(e) if e.is_order_not_found() => return Ok(None),
5053            Err(e) => return Err(e.into()),
5054        };
5055        let order = match orders.as_slice() {
5056            [] => return Ok(None),
5057            [order] => order,
5058            _ => anyhow::bail!(
5059                "Order detail returned {} records for one identifier",
5060                orders.len(),
5061            ),
5062        };
5063
5064        if order.inst_id.as_str() != instrument_id.symbol.inner() {
5065            anyhow::bail!(
5066                "Order detail instrument mismatch for {instrument_id}: returned {}",
5067                order.inst_id,
5068            );
5069        }
5070
5071        if let Some(venue_order_id) = venue_order_id
5072            && order.ord_id.as_str() != venue_order_id.as_str()
5073        {
5074            anyhow::bail!(
5075                "Order detail venue order ID mismatch for {venue_order_id}: returned {}",
5076                order.ord_id,
5077            );
5078        }
5079
5080        let ts_init = self.generate_ts_init();
5081
5082        let mut report = parse_order_status_report(
5083            order,
5084            account_id,
5085            instrument.id(),
5086            instrument.price_precision(),
5087            instrument.size_precision(),
5088            ts_init,
5089        )
5090        .map_err(|e| {
5091            if is_open_okx_order(order.state, false) {
5092                OKXActiveOrderReportError(e).into()
5093            } else {
5094                e
5095            }
5096        })?;
5097
5098        apply_post_only_rejection(order, &mut report);
5099
5100        Ok(Some(report))
5101    }
5102
5103    /// Requests spread order status reports for the given parameters.
5104    ///
5105    /// # Errors
5106    ///
5107    /// Returns an error if the request fails.
5108    pub async fn request_spread_order_status_reports(
5109        &self,
5110        account_id: AccountId,
5111        instrument_id: Option<InstrumentId>,
5112        start: Option<Timestamp>,
5113        end: Option<Timestamp>,
5114        open_only: bool,
5115        limit: Option<u32>,
5116    ) -> anyhow::Result<Vec<OrderStatusReport>> {
5117        Ok(self
5118            .request_spread_order_status_reports_scoped(
5119                account_id,
5120                instrument_id,
5121                start,
5122                end,
5123                open_only,
5124                limit,
5125                false,
5126                None,
5127                None,
5128            )
5129            .await?
5130            .reports)
5131    }
5132
5133    #[expect(clippy::too_many_arguments)]
5134    pub(crate) async fn request_spread_order_status_reports_scoped(
5135        &self,
5136        account_id: AccountId,
5137        instrument_id: Option<InstrumentId>,
5138        start: Option<Timestamp>,
5139        end: Option<Timestamp>,
5140        open_only: bool,
5141        limit: Option<u32>,
5142        allow_history_failure: bool,
5143        scope: Option<ReportInstrumentScope<'_>>,
5144        max_history_pages: Option<u32>,
5145    ) -> anyhow::Result<ReportSweep<OrderStatusReport>> {
5146        let mut pending_builder = GetSpreadOrdersParamsBuilder::default();
5147        let mut history_builder = GetSpreadOrdersParamsBuilder::default();
5148
5149        if let Some(instrument_id) = instrument_id.as_ref() {
5150            let sprd_id = instrument_id.symbol.inner().to_string();
5151            pending_builder.sprd_id(sprd_id.clone());
5152            history_builder.sprd_id(sprd_id);
5153        }
5154
5155        if let Some(start) = start {
5156            history_builder.begin(start.as_millisecond().to_string());
5157        }
5158
5159        if let Some(end) = end {
5160            history_builder.end(end.as_millisecond().to_string());
5161        }
5162
5163        if let Some(limit) = spread_page_limit(limit) {
5164            pending_builder.limit(limit);
5165            history_builder.limit(limit);
5166        }
5167
5168        let pending_base = pending_builder.build().map_err(|e| anyhow::anyhow!(e))?;
5169        let history_base = history_builder.build().map_err(|e| anyhow::anyhow!(e))?;
5170
5171        let (pending, history) = if open_only {
5172            (
5173                self.paginate_spread_orders_pending(&pending_base, limit)
5174                    .await?,
5175                None,
5176            )
5177        } else {
5178            let (history, pending) = Box::pin(async {
5179                tokio::join!(
5180                    self.paginate_spread_orders_history(
5181                        &history_base,
5182                        limit,
5183                        reconciliation_history_page_limit(max_history_pages),
5184                    ),
5185                    self.paginate_spread_orders_pending(&pending_base, limit),
5186                )
5187            })
5188            .await;
5189
5190            (pending?, Some(history))
5191        };
5192
5193        anyhow::ensure!(
5194            pending.complete,
5195            "Pending spread orders did not establish complete coverage"
5196        );
5197
5198        let (history, mut complete) = match history {
5199            Some(Ok(history)) => (history.items, history.complete),
5200            Some(Err(e)) if !allow_history_failure => return Err(e),
5201            Some(Err(e)) => {
5202                log::warn!("Failed to fetch spread order history: {e}");
5203                (Vec::new(), false)
5204            }
5205            None => (Vec::new(), true),
5206        };
5207
5208        let capacity = pending.items.len() + history.len();
5209        let orders = pending
5210            .items
5211            .into_iter()
5212            .map(|order| (order, true))
5213            .chain(history.into_iter().map(|order| (order, false)));
5214
5215        let start_ns = start.map(UnixNanos::from);
5216        let end_ns = end.map(UnixNanos::from);
5217        let ts_init = self.generate_ts_init();
5218        let mut reports = Vec::with_capacity(capacity);
5219        let mut seen: AHashSet<String> = AHashSet::new();
5220
5221        for (order, from_pending_source) in orders {
5222            let active = is_open_okx_order(order.state, from_pending_source);
5223            let seen_key = if order.cl_ord_id.is_empty() {
5224                order.ord_id.as_str().to_string()
5225            } else {
5226                order.cl_ord_id.as_str().to_string()
5227            };
5228
5229            if !seen.insert(seen_key) {
5230                continue;
5231            }
5232
5233            // Open spread orders are authoritative regardless of age; only
5234            // closed history respects the report window.
5235            let ts_last = order
5236                .u_time
5237                .or(order.c_time)
5238                .map_or(ts_init, parse_millisecond_timestamp);
5239
5240            if !active
5241                && (start_ns.is_some_and(|start| ts_last < start)
5242                    || end_ns.is_some_and(|end| ts_last > end))
5243            {
5244                continue;
5245            }
5246
5247            let inst = match self
5248                .resolve_report_instrument(
5249                    order.sprd_id,
5250                    OKXInstrumentType::Any,
5251                    true,
5252                    active,
5253                    scope,
5254                )
5255                .await?
5256            {
5257                InstrumentResolution::Found(inst) => inst,
5258                InstrumentResolution::Skip => continue,
5259                InstrumentResolution::Incomplete => {
5260                    complete = false;
5261                    continue;
5262                }
5263            };
5264
5265            let report = match parse_spread_order_status_report(
5266                &order,
5267                account_id,
5268                inst.id(),
5269                inst.price_precision(),
5270                inst.size_precision(),
5271                ts_init,
5272            ) {
5273                Ok(report) => report,
5274                Err(e) if active => return Err(e),
5275                Err(e) => {
5276                    log::warn!("Failed to parse spread order status report: {e}");
5277                    complete = false;
5278                    continue;
5279                }
5280            };
5281
5282            reports.push(report);
5283        }
5284
5285        Ok(ReportSweep { reports, complete })
5286    }
5287
5288    async fn paginate_spread_orders_history(
5289        &self,
5290        base: &GetSpreadOrdersParams,
5291        limit: Option<u32>,
5292        max_pages: usize,
5293    ) -> anyhow::Result<PageSweep<OKXSpreadOrder>> {
5294        let mut all = Vec::new();
5295        let mut cursor: Option<String> = None;
5296        let mut exhausted = true;
5297
5298        for _ in 0..max_pages {
5299            let mut params = base.clone();
5300            params.end_id = cursor.take();
5301
5302            let page = self
5303                .inner
5304                .get_spread_orders_history(params)
5305                .await
5306                .map_err(|e| anyhow::anyhow!(e))?;
5307
5308            let page_len = page.len();
5309            cursor = page.last().map(|o| o.ord_id.to_string());
5310            all.extend(page);
5311
5312            if page_len < OKX_PAGE_SIZE {
5313                exhausted = false;
5314                break;
5315            }
5316
5317            if let Some(lim) = limit
5318                && all.len() >= lim as usize
5319            {
5320                exhausted = false;
5321                break;
5322            }
5323        }
5324
5325        if exhausted && !all.is_empty() {
5326            log::warn!(
5327                "Spread order history pagination hit {max_pages} page cap, \
5328                 results may be truncated ({} records)",
5329                all.len()
5330            );
5331        }
5332
5333        if let Some(lim) = limit {
5334            all.truncate(lim as usize);
5335        }
5336
5337        Ok(PageSweep::from_pages(all, exhausted))
5338    }
5339
5340    async fn paginate_spread_orders_pending(
5341        &self,
5342        base: &GetSpreadOrdersParams,
5343        limit: Option<u32>,
5344    ) -> anyhow::Result<PageSweep<OKXSpreadOrder>> {
5345        let mut all = Vec::new();
5346        let mut cursor: Option<String> = None;
5347        let mut exhausted = true;
5348
5349        for _ in 0..MAX_RECONCILIATION_PAGES {
5350            let mut params = base.clone();
5351            params.end_id = cursor.take();
5352
5353            let page = self
5354                .inner
5355                .get_spread_orders_pending(params)
5356                .await
5357                .map_err(|e| anyhow::anyhow!(e))?;
5358
5359            let page_len = page.len();
5360            cursor = page.last().map(|o| o.ord_id.to_string());
5361            all.extend(page);
5362
5363            if page_len < OKX_PAGE_SIZE {
5364                exhausted = false;
5365                break;
5366            }
5367
5368            if let Some(lim) = limit
5369                && all.len() >= lim as usize
5370            {
5371                exhausted = false;
5372                break;
5373            }
5374        }
5375
5376        if exhausted && !all.is_empty() {
5377            log::warn!(
5378                "Pending spread orders pagination hit {MAX_RECONCILIATION_PAGES} page cap, \
5379                 results may be truncated ({} records)",
5380                all.len()
5381            );
5382        }
5383
5384        if let Some(lim) = limit {
5385            all.truncate(lim as usize);
5386        }
5387
5388        Ok(PageSweep::from_pages(all, exhausted))
5389    }
5390
5391    // Paginates through order history using `ord_id` as the cursor
5392    async fn paginate_orders_history(
5393        &self,
5394        base: &GetOrderHistoryParams,
5395        limit: Option<u32>,
5396        max_pages: usize,
5397    ) -> anyhow::Result<PageSweep<OKXOrderHistory>> {
5398        let mut all = Vec::new();
5399        let mut cursor: Option<String> = None;
5400        let mut exhausted = true;
5401
5402        for _ in 0..max_pages {
5403            let mut params = base.clone();
5404            params.after = cursor.take();
5405
5406            let page = self
5407                .inner
5408                .get_orders_history(params)
5409                .await
5410                .map_err(|e| anyhow::anyhow!(e))?;
5411
5412            let page_len = page.len();
5413            cursor = page.last().map(|o| o.ord_id.to_string());
5414            all.extend(page);
5415
5416            if page_len < OKX_PAGE_SIZE {
5417                exhausted = false;
5418                break;
5419            }
5420
5421            if let Some(lim) = limit
5422                && all.len() >= lim as usize
5423            {
5424                exhausted = false;
5425                break;
5426            }
5427        }
5428
5429        if exhausted && !all.is_empty() {
5430            log::warn!(
5431                "Order history pagination hit {max_pages} page cap, \
5432                 results may be truncated ({} records)",
5433                all.len()
5434            );
5435        }
5436
5437        if let Some(lim) = limit {
5438            all.truncate(lim as usize);
5439        }
5440
5441        Ok(PageSweep::from_pages(all, exhausted))
5442    }
5443
5444    // Paginates through pending orders using `ord_id` as the cursor
5445    async fn paginate_orders_pending(
5446        &self,
5447        base: &GetOrderListParams,
5448        limit: Option<u32>,
5449    ) -> anyhow::Result<PageSweep<OKXOrderHistory>> {
5450        let mut all = Vec::new();
5451        let mut cursor: Option<String> = None;
5452        let mut exhausted = true;
5453
5454        for _ in 0..MAX_RECONCILIATION_PAGES {
5455            let mut params = base.clone();
5456            params.after = cursor.take();
5457
5458            let page = self
5459                .inner
5460                .get_orders_pending(params)
5461                .await
5462                .map_err(|e| anyhow::anyhow!(e))?;
5463
5464            let page_len = page.len();
5465            cursor = page.last().map(|o| o.ord_id.to_string());
5466            all.extend(page);
5467
5468            if page_len < OKX_PAGE_SIZE {
5469                exhausted = false;
5470                break;
5471            }
5472
5473            if let Some(lim) = limit
5474                && all.len() >= lim as usize
5475            {
5476                exhausted = false;
5477                break;
5478            }
5479        }
5480
5481        if exhausted && !all.is_empty() {
5482            log::warn!(
5483                "Pending orders pagination hit {MAX_RECONCILIATION_PAGES} page cap, \
5484                 results may be truncated ({} records)",
5485                all.len()
5486            );
5487        }
5488
5489        if let Some(lim) = limit {
5490            all.truncate(lim as usize);
5491        }
5492
5493        Ok(PageSweep::from_pages(all, exhausted))
5494    }
5495
5496    // Paginates through transaction details (fills) using `bill_id` as the cursor
5497    async fn paginate_fills(
5498        &self,
5499        base: &GetTransactionDetailsParams,
5500        limit: Option<u32>,
5501        history: FillHistory,
5502        max_pages: usize,
5503    ) -> anyhow::Result<PageSweep<OKXTransactionDetail>> {
5504        let mut all = Vec::new();
5505        let mut cursor: Option<String> = None;
5506        let mut exhausted = true;
5507
5508        for _ in 0..max_pages {
5509            let mut params = base.clone();
5510            params.after = cursor.take();
5511
5512            let page = match history {
5513                FillHistory::Recent => self.inner.get_fills(params).await,
5514                FillHistory::Extended => self.inner.get_fills_history(params).await,
5515            }
5516            .map_err(|e| anyhow::anyhow!(e))?;
5517
5518            let page_len = page.len();
5519            cursor = page.last().map(|o| o.bill_id.to_string());
5520            all.extend(page);
5521
5522            if page_len < OKX_PAGE_SIZE {
5523                exhausted = false;
5524                break;
5525            }
5526
5527            if let Some(lim) = limit
5528                && all.len() >= lim as usize
5529            {
5530                exhausted = false;
5531                break;
5532            }
5533        }
5534
5535        if exhausted && !all.is_empty() {
5536            log::warn!(
5537                "Fill pagination hit {max_pages} page cap, \
5538                 results may be truncated ({} records)",
5539                all.len()
5540            );
5541        }
5542
5543        if let Some(lim) = limit {
5544            all.truncate(lim as usize);
5545        }
5546
5547        Ok(PageSweep::from_pages(all, exhausted))
5548    }
5549
5550    // Paginates through pending algo orders using `algo_id` as the cursor
5551    async fn paginate_algo_pending(
5552        &self,
5553        base: &GetAlgoOrdersParams,
5554        limit: Option<usize>,
5555        require_complete_active_coverage: bool,
5556    ) -> anyhow::Result<PageSweep<OKXOrderAlgo>> {
5557        let mut all = Vec::new();
5558        let mut cursor: Option<String> = None;
5559        let mut exhausted = true;
5560
5561        for _ in 0..MAX_RECONCILIATION_PAGES {
5562            let mut params = base.clone();
5563            params.after = cursor.take();
5564
5565            let page = match self.inner.get_order_algo_pending(params).await {
5566                Ok(result) => result,
5567                Err(OKXHttpError::UnexpectedStatus { status, .. })
5568                    if status == StatusCode::NOT_FOUND && !require_complete_active_coverage =>
5569                {
5570                    exhausted = false;
5571                    break;
5572                }
5573                Err(e) => return Err(e.into()),
5574            };
5575
5576            let page_len = page.len();
5577            cursor = page.last().map(|o| o.algo_id.clone());
5578            all.extend(page);
5579
5580            if page_len < OKX_PAGE_SIZE {
5581                exhausted = false;
5582                break;
5583            }
5584
5585            if let Some(lim) = limit
5586                && all.len() >= lim
5587            {
5588                exhausted = false;
5589                break;
5590            }
5591        }
5592
5593        if exhausted && !all.is_empty() {
5594            log::warn!(
5595                "Algo pending pagination hit {MAX_RECONCILIATION_PAGES} page cap, \
5596                 results may be truncated ({} records)",
5597                all.len()
5598            );
5599        }
5600
5601        Ok(PageSweep::from_pages(all, exhausted))
5602    }
5603
5604    // Paginates through historical algo orders using `algo_id` as the cursor
5605    async fn paginate_algo_history(
5606        &self,
5607        base: &GetAlgoOrdersParams,
5608        limit: Option<usize>,
5609        require_complete_active_coverage: bool,
5610        max_pages: usize,
5611    ) -> anyhow::Result<PageSweep<OKXOrderAlgo>> {
5612        let mut all = Vec::new();
5613        let mut cursor: Option<String> = None;
5614        let mut exhausted = true;
5615
5616        for _ in 0..max_pages {
5617            let mut params = base.clone();
5618            params.after = cursor.take();
5619
5620            let page = match self.inner.get_order_algo_history(params).await {
5621                Ok(result) => result,
5622                Err(OKXHttpError::UnexpectedStatus { status, .. })
5623                    if status == StatusCode::NOT_FOUND && !require_complete_active_coverage =>
5624                {
5625                    exhausted = false;
5626                    break;
5627                }
5628                Err(e) => return Err(e.into()),
5629            };
5630
5631            let page_len = page.len();
5632            cursor = page.last().map(|o| o.algo_id.clone());
5633            all.extend(page);
5634
5635            if page_len < OKX_PAGE_SIZE {
5636                exhausted = false;
5637                break;
5638            }
5639
5640            if let Some(lim) = limit
5641                && all.len() >= lim
5642            {
5643                exhausted = false;
5644                break;
5645            }
5646        }
5647
5648        if exhausted && !all.is_empty() {
5649            log::warn!(
5650                "Algo history pagination hit {max_pages} page cap, \
5651                 results may be truncated ({} records)",
5652                all.len()
5653            );
5654        }
5655
5656        Ok(PageSweep::from_pages(all, exhausted))
5657    }
5658
5659    /// Requests fill reports (transaction details) for the given parameters.
5660    ///
5661    /// # Errors
5662    ///
5663    /// Returns an error if the request fails.
5664    ///
5665    /// # References
5666    ///
5667    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-days>.
5668    pub async fn request_fill_reports(
5669        &self,
5670        account_id: AccountId,
5671        instrument_type: Option<OKXInstrumentType>,
5672        instrument_id: Option<InstrumentId>,
5673        start: Option<Timestamp>,
5674        end: Option<Timestamp>,
5675        limit: Option<u32>,
5676    ) -> anyhow::Result<Vec<FillReport>> {
5677        Ok(self
5678            .request_fill_reports_scoped(
5679                account_id,
5680                instrument_type,
5681                instrument_id,
5682                start,
5683                end,
5684                limit,
5685                FillHistory::Recent,
5686                None,
5687                None,
5688            )
5689            .await?
5690            .reports)
5691    }
5692
5693    #[expect(clippy::too_many_arguments)]
5694    pub(crate) async fn request_fill_reports_scoped(
5695        &self,
5696        account_id: AccountId,
5697        instrument_type: Option<OKXInstrumentType>,
5698        instrument_id: Option<InstrumentId>,
5699        start: Option<Timestamp>,
5700        end: Option<Timestamp>,
5701        limit: Option<u32>,
5702        history: FillHistory,
5703        scope: Option<ReportInstrumentScope<'_>>,
5704        max_history_pages: Option<u32>,
5705    ) -> anyhow::Result<ReportSweep<FillReport>> {
5706        if instrument_id.as_ref().is_some_and(|id| self.is_spread(*id))
5707            || (instrument_id.is_none() && instrument_type.is_none())
5708        {
5709            return self
5710                .request_spread_fill_reports_scoped(
5711                    account_id,
5712                    instrument_id,
5713                    start,
5714                    end,
5715                    limit,
5716                    scope,
5717                    max_history_pages,
5718                )
5719                .await;
5720        }
5721
5722        let mut params = GetTransactionDetailsParamsBuilder::default();
5723
5724        let instrument_type = if let Some(instrument_type) = instrument_type {
5725            instrument_type
5726        } else {
5727            let instrument_id = instrument_id.ok_or_else(|| {
5728                anyhow::anyhow!("Instrument ID required if `instrument_type` not provided")
5729            })?;
5730
5731            let instrument = self.resolve_instrument(instrument_id).await?;
5732            okx_instrument_type(&instrument)?
5733        };
5734
5735        params.inst_type(instrument_type);
5736
5737        if let Some(instrument_id) = instrument_id {
5738            let instrument = self.resolve_instrument(instrument_id).await?;
5739            let instrument_type = okx_instrument_type(&instrument)?;
5740            params.inst_type(instrument_type);
5741            params.inst_id(instrument_id.symbol.inner().to_string());
5742        }
5743
5744        if let Some(start) = start {
5745            params.begin(start.as_millisecond().to_string());
5746        }
5747
5748        if let Some(end) = end {
5749            params.end(end.as_millisecond().to_string());
5750        }
5751
5752        let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
5753
5754        let sweep = self
5755            .paginate_fills(
5756                &params,
5757                limit,
5758                history,
5759                reconciliation_history_page_limit(max_history_pages),
5760            )
5761            .await?;
5762        let mut complete = sweep.complete;
5763
5764        // Prepare time range filter
5765        let start_ns = start.map(UnixNanos::from);
5766        let end_ns = end.map(UnixNanos::from);
5767
5768        let ts_init = self.generate_ts_init();
5769        let mut reports = Vec::with_capacity(sweep.items.len());
5770
5771        for detail in sweep.items {
5772            // Skip fills with zero or negative quantity (cancelled orders, etc)
5773            if detail.fill_sz.is_empty() {
5774                continue;
5775            }
5776
5777            if !fill_quantity_is_positive(&detail.fill_sz).with_context(|| {
5778                format!(
5779                    "failed to parse fill quantity for instrument {}",
5780                    detail.inst_id
5781                )
5782            })? {
5783                continue;
5784            }
5785
5786            if report_ts_outside_window(detail.ts, start_ns, end_ns) {
5787                continue;
5788            }
5789
5790            let inst = match self
5791                .resolve_report_instrument(detail.inst_id, detail.inst_type, false, false, scope)
5792                .await?
5793            {
5794                InstrumentResolution::Found(inst) => inst,
5795                InstrumentResolution::Skip => continue,
5796                InstrumentResolution::Incomplete => {
5797                    complete = false;
5798                    continue;
5799                }
5800            };
5801
5802            let report = parse_fill_report(
5803                &detail,
5804                account_id,
5805                inst.id(),
5806                inst.price_precision(),
5807                inst.size_precision(),
5808                ts_init,
5809            )
5810            .with_context(|| {
5811                format!(
5812                    "failed to parse fill report for instrument {}",
5813                    detail.inst_id
5814                )
5815            })?;
5816
5817            if let Some(start_ns) = start_ns
5818                && report.ts_event < start_ns
5819            {
5820                continue;
5821            }
5822
5823            if let Some(end_ns) = end_ns
5824                && report.ts_event > end_ns
5825            {
5826                continue;
5827            }
5828
5829            reports.push(report);
5830        }
5831
5832        Ok(ReportSweep { reports, complete })
5833    }
5834
5835    /// Requests spread fill reports for the given parameters.
5836    ///
5837    /// # Errors
5838    ///
5839    /// Returns an error if the request fails.
5840    pub async fn request_spread_fill_reports(
5841        &self,
5842        account_id: AccountId,
5843        instrument_id: Option<InstrumentId>,
5844        start: Option<Timestamp>,
5845        end: Option<Timestamp>,
5846        limit: Option<u32>,
5847    ) -> anyhow::Result<Vec<FillReport>> {
5848        Ok(self
5849            .request_spread_fill_reports_scoped(
5850                account_id,
5851                instrument_id,
5852                start,
5853                end,
5854                limit,
5855                None,
5856                None,
5857            )
5858            .await?
5859            .reports)
5860    }
5861
5862    #[expect(clippy::too_many_arguments)]
5863    pub(crate) async fn request_spread_fill_reports_scoped(
5864        &self,
5865        account_id: AccountId,
5866        instrument_id: Option<InstrumentId>,
5867        start: Option<Timestamp>,
5868        end: Option<Timestamp>,
5869        limit: Option<u32>,
5870        scope: Option<ReportInstrumentScope<'_>>,
5871        max_history_pages: Option<u32>,
5872    ) -> anyhow::Result<ReportSweep<FillReport>> {
5873        let mut builder = GetSpreadTradesParamsBuilder::default();
5874
5875        if let Some(instrument_id) = instrument_id {
5876            self.resolve_instrument(instrument_id).await?;
5877            builder.sprd_id(instrument_id.symbol.inner().to_string());
5878        }
5879
5880        if let Some(start) = start {
5881            builder.begin(start.as_millisecond().to_string());
5882        }
5883
5884        if let Some(end) = end {
5885            builder.end(end.as_millisecond().to_string());
5886        }
5887
5888        if let Some(limit) = spread_page_limit(limit) {
5889            builder.limit(limit);
5890        }
5891
5892        let params = builder.build().map_err(|e| anyhow::anyhow!(e))?;
5893        let sweep = self
5894            .paginate_spread_fills(
5895                &params,
5896                limit,
5897                reconciliation_history_page_limit(max_history_pages),
5898            )
5899            .await?;
5900        let mut complete = sweep.complete;
5901
5902        let start_ns = start.map(UnixNanos::from);
5903        let end_ns = end.map(UnixNanos::from);
5904        let ts_init = self.generate_ts_init();
5905        let mut reports = Vec::with_capacity(sweep.items.len());
5906
5907        for detail in sweep.items {
5908            if detail.fill_sz.is_empty() {
5909                continue;
5910            }
5911
5912            if !fill_quantity_is_positive(&detail.fill_sz).with_context(|| {
5913                format!(
5914                    "failed to parse spread fill quantity for instrument {}",
5915                    detail.sprd_id
5916                )
5917            })? {
5918                continue;
5919            }
5920
5921            if report_ts_outside_window(detail.ts, start_ns, end_ns) {
5922                continue;
5923            }
5924
5925            let inst = match self
5926                .resolve_report_instrument(
5927                    detail.sprd_id,
5928                    OKXInstrumentType::Any,
5929                    true,
5930                    false,
5931                    scope,
5932                )
5933                .await?
5934            {
5935                InstrumentResolution::Found(inst) => inst,
5936                InstrumentResolution::Skip => continue,
5937                InstrumentResolution::Incomplete => {
5938                    complete = false;
5939                    continue;
5940                }
5941            };
5942
5943            let report = parse_spread_fill_report(
5944                &detail,
5945                account_id,
5946                inst.id(),
5947                inst.price_precision(),
5948                inst.size_precision(),
5949                ts_init,
5950            )
5951            .with_context(|| {
5952                format!(
5953                    "failed to parse spread fill report for instrument {}",
5954                    detail.sprd_id
5955                )
5956            })?;
5957
5958            if let Some(start_ns) = start_ns
5959                && report.ts_event < start_ns
5960            {
5961                continue;
5962            }
5963
5964            if let Some(end_ns) = end_ns
5965                && report.ts_event > end_ns
5966            {
5967                continue;
5968            }
5969
5970            reports.push(report);
5971        }
5972
5973        Ok(ReportSweep { reports, complete })
5974    }
5975
5976    async fn paginate_spread_fills(
5977        &self,
5978        base: &GetSpreadTradesParams,
5979        limit: Option<u32>,
5980        max_pages: usize,
5981    ) -> anyhow::Result<PageSweep<OKXSpreadTrade>> {
5982        let mut all = Vec::new();
5983        let mut cursor: Option<String> = None;
5984        let mut exhausted = true;
5985
5986        for _ in 0..max_pages {
5987            let mut params = base.clone();
5988            params.end_id = cursor.take();
5989
5990            let page = self
5991                .inner
5992                .get_spread_trades(params)
5993                .await
5994                .map_err(|e| anyhow::anyhow!(e))?;
5995
5996            let page_len = page.len();
5997            cursor = page.last().map(|o| o.trade_id.to_string());
5998            all.extend(page);
5999
6000            if page_len < OKX_PAGE_SIZE {
6001                exhausted = false;
6002                break;
6003            }
6004
6005            if let Some(lim) = limit
6006                && all.len() >= lim as usize
6007            {
6008                exhausted = false;
6009                break;
6010            }
6011        }
6012
6013        if exhausted && !all.is_empty() {
6014            log::warn!(
6015                "Spread fill pagination hit {max_pages} page cap, \
6016                 results may be truncated ({} records)",
6017                all.len()
6018            );
6019        }
6020
6021        if let Some(lim) = limit {
6022            all.truncate(lim as usize);
6023        }
6024
6025        Ok(PageSweep::from_pages(all, exhausted))
6026    }
6027
6028    /// Requests current position status reports for the given parameters.
6029    ///
6030    /// # Position Modes
6031    ///
6032    /// OKX supports two position modes, which affects how position data is returned:
6033    ///
6034    /// ## Net Mode (One-way)
6035    /// - `posSide` field will be `"net"`
6036    /// - `pos` field uses **signed quantities**:
6037    ///   - Positive value = Long position
6038    ///   - Negative value = Short position
6039    ///   - Zero = Flat/no position
6040    ///
6041    /// ## Long/Short Mode (Hedge/Dual-side)
6042    /// - `posSide` field will be `"long"` or `"short"`
6043    /// - `pos` field is **always positive** (use `posSide` to determine actual side)
6044    /// - Allows holding simultaneous long and short positions on the same instrument
6045    /// - Position IDs are suffixed with `-LONG` or `-SHORT` for uniqueness
6046    ///
6047    /// # Errors
6048    ///
6049    /// Returns an error if the request fails, a position cannot be parsed, or multiple
6050    /// nonzero positions map to the same hedge leg.
6051    ///
6052    /// # References
6053    ///
6054    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions>
6055    pub async fn request_position_status_reports(
6056        &self,
6057        account_id: AccountId,
6058        instrument_type: Option<OKXInstrumentType>,
6059        instrument_id: Option<InstrumentId>,
6060    ) -> anyhow::Result<Vec<PositionStatusReport>> {
6061        Ok(self
6062            .request_position_status_reports_scoped(
6063                account_id,
6064                instrument_type,
6065                instrument_id,
6066                None,
6067            )
6068            .await?
6069            .reports)
6070    }
6071
6072    pub(crate) async fn request_position_status_reports_scoped(
6073        &self,
6074        account_id: AccountId,
6075        instrument_type: Option<OKXInstrumentType>,
6076        instrument_id: Option<InstrumentId>,
6077        scope: Option<ReportInstrumentScope<'_>>,
6078    ) -> anyhow::Result<ReportSweep<PositionStatusReport>> {
6079        let mut params = GetPositionsParamsBuilder::default();
6080
6081        let instrument_type = if let Some(instrument_type) = instrument_type {
6082            instrument_type
6083        } else {
6084            let instrument_id = instrument_id.ok_or_else(|| {
6085                anyhow::anyhow!("Instrument ID required if `instrument_type` not provided")
6086            })?;
6087
6088            let instrument = self.resolve_instrument(instrument_id).await?;
6089
6090            okx_instrument_type(&instrument)?
6091        };
6092
6093        params.inst_type(instrument_type);
6094
6095        instrument_id
6096            .as_ref()
6097            .map(|i| params.inst_id(i.symbol.inner()));
6098
6099        let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
6100
6101        let resp = self
6102            .inner
6103            .get_positions(params)
6104            .await
6105            .map_err(|e| anyhow::anyhow!(e))?;
6106
6107        let ts_init = self.generate_ts_init();
6108        let mut reports: Vec<PositionStatusReport> = Vec::with_capacity(resp.len());
6109        let mut position_ids = AHashMap::new();
6110
6111        for position in resp {
6112            let inst = match self
6113                .resolve_report_instrument(position.inst_id, position.inst_type, false, true, scope)
6114                .await?
6115            {
6116                InstrumentResolution::Found(inst) => inst,
6117                InstrumentResolution::Skip => continue,
6118                InstrumentResolution::Incomplete => {
6119                    anyhow::bail!(
6120                        "Instrument {} missing from cache for position report",
6121                        position.inst_id
6122                    );
6123                }
6124            };
6125
6126            if let Some(scope) = scope {
6127                scope.validate_position_margin(&position)?;
6128            }
6129
6130            let report = parse_position_status_report(
6131                &position,
6132                account_id,
6133                inst.id(),
6134                inst.size_precision(),
6135                ts_init,
6136            )
6137            .with_context(|| {
6138                format!(
6139                    "failed to parse position status report for instrument {}",
6140                    position.inst_id
6141                )
6142            })?;
6143
6144            if let Some(position_id) = report.venue_position_id {
6145                if let Some(index) = position_ids.get(&position_id).copied() {
6146                    if report.quantity.is_zero() {
6147                        continue;
6148                    }
6149
6150                    let existing: &mut PositionStatusReport = &mut reports[index];
6151                    if existing.quantity.is_zero() {
6152                        *existing = report;
6153                        continue;
6154                    }
6155
6156                    anyhow::bail!(
6157                        "Multiple OKX positions map to {position_id}; mixed margin modes are not supported"
6158                    );
6159                }
6160
6161                position_ids.insert(position_id, reports.len());
6162            }
6163
6164            reports.push(report);
6165        }
6166
6167        Ok(ReportSweep {
6168            reports,
6169            complete: true,
6170        })
6171    }
6172
6173    /// Requests spot position status reports derived from net wallet balances.
6174    ///
6175    /// Reports the signed base currency `cashBal` of each cached spot pair quoted in
6176    /// `quote_currency`, as `LONG` or `SHORT` according to its sign. A balance that rounds to
6177    /// zero is omitted from bulk requests and reported `FLAT` for a targeted request. A pair
6178    /// quoted in another currency gets no report.
6179    ///
6180    /// # Errors
6181    ///
6182    /// Returns an error if the request fails, the response contains no account, `cashBal` or `liab`
6183    /// cannot be parsed exactly, the balance sum overflows or loses precision, or the quantity
6184    /// cannot be represented.
6185    ///
6186    /// # References
6187    ///
6188    /// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-balance>
6189    pub async fn request_spot_position_reports(
6190        &self,
6191        account_id: AccountId,
6192        instrument_id: Option<InstrumentId>,
6193        quote_currency: Ustr,
6194    ) -> anyhow::Result<Vec<PositionStatusReport>> {
6195        let covered: Vec<(InstrumentId, Ustr, u8)> = {
6196            let cache = self.instruments_cache.load();
6197            let instruments: Vec<&InstrumentAny> = match instrument_id {
6198                Some(instrument_id) => cache
6199                    .get(&instrument_id.symbol.inner())
6200                    .into_iter()
6201                    .collect(),
6202                None => cache.values().collect(),
6203            };
6204
6205            instruments
6206                .into_iter()
6207                .filter_map(|instrument| {
6208                    let base_currency = spot_position_base_currency(instrument, quote_currency)?;
6209                    Some((
6210                        instrument.id(),
6211                        base_currency.code,
6212                        instrument.size_precision(),
6213                    ))
6214                })
6215                .collect()
6216        };
6217
6218        if covered.is_empty() {
6219            return Ok(Vec::new());
6220        }
6221
6222        let accounts = self
6223            .inner
6224            .get_balance()
6225            .await
6226            .map_err(|e| anyhow::anyhow!(e))?;
6227        anyhow::ensure!(
6228            !accounts.is_empty(),
6229            "OKX balance response contained no account"
6230        );
6231
6232        let ts_init = self.generate_ts_init();
6233        let mut reports = Vec::new();
6234
6235        for (covered_id, base_code, size_precision) in covered {
6236            let (position_side, quantity) =
6237                parse_spot_position_quantity(&accounts, base_code, size_precision)?;
6238
6239            if quantity.is_zero() && instrument_id.is_none() {
6240                continue;
6241            }
6242
6243            reports.push(PositionStatusReport::new(
6244                account_id,
6245                covered_id,
6246                position_side,
6247                quantity,
6248                ts_init,
6249                ts_init,
6250                None,
6251                None,
6252                None,
6253            ));
6254        }
6255
6256        Ok(reports)
6257    }
6258
6259    /// Places a regular order via HTTP.
6260    ///
6261    /// # Errors
6262    ///
6263    /// Returns an error if the request fails.
6264    ///
6265    /// # References
6266    ///
6267    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order>
6268    pub async fn place_order(
6269        &self,
6270        request: OKXPlaceOrderRequest,
6271    ) -> Result<OKXPlaceOrderResponse, OKXHttpError> {
6272        let request = OKXPlaceOrderRequest {
6273            tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
6274            ..request
6275        };
6276
6277        let body = serde_json::to_vec(&request)?;
6278
6279        let resp: Vec<OKXPlaceOrderResponse> = self
6280            .inner
6281            .send_request::<_, ()>(Method::POST, "/api/v5/trade/order", None, Some(body), true)
6282            .await?;
6283
6284        resp.into_iter().next().ok_or(OKXHttpError::EmptyResponse)
6285    }
6286
6287    /// Places multiple regular orders via HTTP.
6288    ///
6289    /// # Errors
6290    ///
6291    /// Returns an error if the request fails.
6292    pub async fn place_orders(
6293        &self,
6294        requests: Vec<OKXPlaceOrderRequest>,
6295    ) -> Result<Vec<OKXPlaceOrderResponse>, OKXHttpError> {
6296        if requests.is_empty() {
6297            return Ok(Vec::new());
6298        }
6299
6300        let requests: Vec<_> = requests
6301            .into_iter()
6302            .map(|request| OKXPlaceOrderRequest {
6303                tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
6304                ..request
6305            })
6306            .collect();
6307
6308        let body = serde_json::to_vec(&requests)?;
6309        self.inner
6310            .send_request::<_, ()>(
6311                Method::POST,
6312                "/api/v5/trade/batch-orders",
6313                None,
6314                Some(body),
6315                true,
6316            )
6317            .await
6318    }
6319
6320    /// Amends a regular order via HTTP.
6321    ///
6322    /// # Errors
6323    ///
6324    /// Returns an error if the request fails.
6325    pub async fn amend_order(
6326        &self,
6327        request: OKXAmendOrderRequest,
6328    ) -> Result<OKXPlaceOrderResponse, OKXHttpError> {
6329        let body = serde_json::to_vec(&request)?;
6330        let resp: Vec<OKXPlaceOrderResponse> = self
6331            .inner
6332            .send_request::<_, ()>(
6333                Method::POST,
6334                "/api/v5/trade/amend-order",
6335                None,
6336                Some(body),
6337                true,
6338            )
6339            .await?;
6340
6341        resp.into_iter().next().ok_or(OKXHttpError::EmptyResponse)
6342    }
6343
6344    /// Amends multiple regular orders via HTTP.
6345    ///
6346    /// # Errors
6347    ///
6348    /// Returns an error if the request fails.
6349    pub async fn amend_orders(
6350        &self,
6351        requests: Vec<OKXAmendOrderRequest>,
6352    ) -> Result<Vec<OKXPlaceOrderResponse>, OKXHttpError> {
6353        if requests.is_empty() {
6354            return Ok(Vec::new());
6355        }
6356
6357        let body = serde_json::to_vec(&requests)?;
6358        self.inner
6359            .send_request::<_, ()>(
6360                Method::POST,
6361                "/api/v5/trade/amend-batch-orders",
6362                None,
6363                Some(body),
6364                true,
6365            )
6366            .await
6367    }
6368
6369    /// Places a spread order via HTTP.
6370    ///
6371    /// # Errors
6372    ///
6373    /// Returns an error if the request fails.
6374    pub async fn place_spread_order(
6375        &self,
6376        request: OKXPlaceSpreadOrderRequest,
6377    ) -> Result<OKXPlaceOrderResponse, OKXHttpError> {
6378        let resp = self.inner.place_spread_order(request).await?;
6379        let item = resp.into_iter().next().ok_or(OKXHttpError::EmptyResponse)?;
6380
6381        if let Some(ref code) = item.s_code
6382            && code != OKX_SUCCESS_CODE
6383        {
6384            let msg = item.s_msg.clone().unwrap_or_default();
6385            return Err(OKXHttpError::from_venue_response(code.clone(), msg, None));
6386        }
6387
6388        Ok(item)
6389    }
6390
6391    /// Cancels a spread order via HTTP.
6392    ///
6393    /// # Errors
6394    ///
6395    /// Returns an error if the request fails.
6396    pub async fn cancel_spread_order(
6397        &self,
6398        request: OKXCancelSpreadOrderRequest,
6399    ) -> Result<OKXCancelOrderResponse, OKXHttpError> {
6400        let resp = self.inner.cancel_spread_order(request).await?;
6401        let item = resp.into_iter().next().ok_or(OKXHttpError::EmptyResponse)?;
6402
6403        if let Some(ref code) = item.s_code
6404            && code != OKX_SUCCESS_CODE
6405        {
6406            let msg = item.s_msg.clone().unwrap_or_default();
6407            return Err(OKXHttpError::from_venue_response(code.clone(), msg, None));
6408        }
6409
6410        Ok(item)
6411    }
6412
6413    /// Cancels all orders for a spread via HTTP.
6414    ///
6415    /// # Errors
6416    ///
6417    /// Returns an error if the request fails.
6418    pub async fn cancel_all_spread_orders(
6419        &self,
6420        spread_id: InstrumentId,
6421    ) -> Result<Vec<OKXCancelOrderResponse>, OKXHttpError> {
6422        let request = OKXCancelAllSpreadOrdersRequest {
6423            sprd_id: spread_id.symbol.as_str().to_string(),
6424        };
6425
6426        self.inner.cancel_all_spread_orders(request).await
6427    }
6428
6429    /// Cancels an order via HTTP, routing spread instruments to the spread endpoint.
6430    ///
6431    /// # Errors
6432    ///
6433    /// Returns an error if the request fails or if no order identifier is supplied.
6434    pub async fn cancel_order(
6435        &self,
6436        instrument_id: InstrumentId,
6437        client_order_id: Option<ClientOrderId>,
6438        venue_order_id: Option<VenueOrderId>,
6439    ) -> Result<OKXCancelOrderResponse, OKXHttpError> {
6440        if client_order_id.is_none() && venue_order_id.is_none() {
6441            return Err(OKXHttpError::ValidationError(
6442                "Either `client_order_id` or `venue_order_id` is required".to_string(),
6443            ));
6444        }
6445
6446        let ord_id = venue_order_id.as_ref().map(ToString::to_string);
6447        let cl_ord_id = if venue_order_id.is_none() {
6448            client_order_id.as_ref().map(|id| id.as_str().to_string())
6449        } else {
6450            None
6451        };
6452
6453        if self.is_spread(instrument_id) {
6454            return self
6455                .cancel_spread_order(OKXCancelSpreadOrderRequest { ord_id, cl_ord_id })
6456                .await;
6457        }
6458
6459        let request = OKXCancelOrderRequest {
6460            inst_id: instrument_id.symbol.as_str().to_string(),
6461            inst_id_code: None,
6462            ord_id,
6463            cl_ord_id,
6464        };
6465        let mut resp = self.cancel_orders(vec![request]).await?;
6466        let item = resp.pop().ok_or(OKXHttpError::EmptyResponse)?;
6467
6468        if let Some(ref code) = item.s_code
6469            && code != OKX_SUCCESS_CODE
6470        {
6471            let msg = item.s_msg.clone().unwrap_or_default();
6472            return Err(OKXHttpError::from_venue_response(code.clone(), msg, None));
6473        }
6474
6475        Ok(item)
6476    }
6477
6478    /// Cancels all open orders for an instrument via HTTP.
6479    ///
6480    /// # Errors
6481    ///
6482    /// Returns an error if the request fails.
6483    pub async fn cancel_all_orders(
6484        &self,
6485        instrument_id: InstrumentId,
6486    ) -> Result<Vec<OKXCancelOrderResponse>, OKXHttpError> {
6487        if self.is_spread(instrument_id) {
6488            return self.cancel_all_spread_orders(instrument_id).await;
6489        }
6490
6491        let instrument = self
6492            .instrument_from_cache(instrument_id.symbol.inner())
6493            .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
6494        let instrument_type = okx_instrument_type(&instrument)
6495            .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
6496
6497        let mut pending_base = GetOrderListParamsBuilder::default();
6498        pending_base.inst_type(instrument_type);
6499        pending_base.inst_id(instrument_id.symbol.inner().to_string());
6500        let pending_base = pending_base
6501            .build()
6502            .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
6503
6504        let pending = self
6505            .paginate_orders_pending(&pending_base, None)
6506            .await
6507            .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
6508        let requests = pending
6509            .items
6510            .into_iter()
6511            .map(|order| OKXCancelOrderRequest {
6512                inst_id: order.inst_id.to_string(),
6513                inst_id_code: None,
6514                ord_id: if order.ord_id.is_empty() {
6515                    None
6516                } else {
6517                    Some(order.ord_id.to_string())
6518                },
6519                cl_ord_id: if order.ord_id.is_empty() && !order.cl_ord_id.is_empty() {
6520                    Some(order.cl_ord_id.to_string())
6521                } else {
6522                    None
6523                },
6524            })
6525            .collect();
6526
6527        self.cancel_orders(requests).await
6528    }
6529
6530    /// Cancels multiple regular orders via HTTP in a single request.
6531    ///
6532    /// Items with non-zero `sCode` are logged as warnings but do not
6533    /// fail the entire batch.
6534    ///
6535    /// # Errors
6536    ///
6537    /// Returns an error if the request fails.
6538    ///
6539    /// # References
6540    ///
6541    /// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-multiple-orders>
6542    pub async fn cancel_orders(
6543        &self,
6544        requests: Vec<OKXCancelOrderRequest>,
6545    ) -> Result<Vec<OKXCancelOrderResponse>, OKXHttpError> {
6546        if requests.is_empty() {
6547            return Ok(Vec::new());
6548        }
6549
6550        let body = serde_json::to_vec(&requests)?;
6551
6552        let resp: Vec<OKXCancelOrderResponse> = self
6553            .inner
6554            .send_request::<_, ()>(
6555                Method::POST,
6556                "/api/v5/trade/cancel-batch-orders",
6557                None,
6558                Some(body),
6559                true,
6560            )
6561            .await?;
6562
6563        for item in &resp {
6564            if let Some(ref code) = item.s_code
6565                && code != OKX_SUCCESS_CODE
6566            {
6567                let msg = item.s_msg.as_deref().unwrap_or("");
6568                log::warn!(
6569                    "Order cancel rejected: ord_id={} sCode={code} sMsg={msg}",
6570                    item.ord_id
6571                );
6572            }
6573        }
6574
6575        Ok(resp)
6576    }
6577
6578    /// Places an algo order via HTTP.
6579    ///
6580    /// # Errors
6581    ///
6582    /// Returns an error if the request fails.
6583    ///
6584    /// # References
6585    ///
6586    /// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order>
6587    pub async fn place_algo_order(
6588        &self,
6589        request: OKXPlaceAlgoOrderRequest,
6590    ) -> Result<OKXPlaceAlgoOrderResponse, OKXHttpError> {
6591        let request = OKXPlaceAlgoOrderRequest {
6592            tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
6593            ..request
6594        };
6595
6596        let body = serde_json::to_vec(&request)?;
6597
6598        let resp: Vec<OKXPlaceAlgoOrderResponse> = self
6599            .inner
6600            .send_request::<_, ()>(
6601                Method::POST,
6602                "/api/v5/trade/order-algo",
6603                None,
6604                Some(body),
6605                true,
6606            )
6607            .await?;
6608
6609        let item = resp.into_iter().next().ok_or(OKXHttpError::EmptyResponse)?;
6610
6611        if let Some(ref code) = item.s_code
6612            && code != "0"
6613        {
6614            let msg = item.s_msg.clone().unwrap_or_default();
6615            return Err(OKXHttpError::from_venue_response(code.clone(), msg, None));
6616        }
6617
6618        Ok(item)
6619    }
6620
6621    /// Cancels an algo order via HTTP.
6622    ///
6623    /// # Errors
6624    ///
6625    /// Returns an error if the request fails.
6626    ///
6627    /// # References
6628    ///
6629    /// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order>
6630    pub async fn cancel_algo_order(
6631        &self,
6632        request: OKXCancelAlgoOrderRequest,
6633    ) -> Result<OKXCancelAlgoOrderResponse, OKXHttpError> {
6634        // OKX expects an array for cancel-algos endpoint
6635        // Serialize once to bytes to keep signing and sending identical
6636        let body = serde_json::to_vec(&[request])?;
6637
6638        let resp: Vec<OKXCancelAlgoOrderResponse> = self
6639            .inner
6640            .send_request::<_, ()>(
6641                Method::POST,
6642                "/api/v5/trade/cancel-algos",
6643                None,
6644                Some(body),
6645                true,
6646            )
6647            .await?;
6648
6649        let item = resp.into_iter().next().ok_or(OKXHttpError::EmptyResponse)?;
6650
6651        if let Some(ref code) = item.s_code
6652            && code != "0"
6653        {
6654            let msg = item.s_msg.clone().unwrap_or_default();
6655            return Err(OKXHttpError::from_venue_response(code.clone(), msg, None));
6656        }
6657
6658        Ok(item)
6659    }
6660
6661    /// Cancels multiple algo orders via HTTP in a single request.
6662    ///
6663    /// Items with non-zero `sCode` are logged at debug level but do not
6664    /// fail the entire batch.
6665    ///
6666    /// # Errors
6667    ///
6668    /// Returns an error if the request fails.
6669    ///
6670    /// # References
6671    ///
6672    /// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order>
6673    pub async fn cancel_algo_orders(
6674        &self,
6675        requests: Vec<OKXCancelAlgoOrderRequest>,
6676    ) -> Result<Vec<OKXCancelAlgoOrderResponse>, OKXHttpError> {
6677        if requests.is_empty() {
6678            return Ok(Vec::new());
6679        }
6680
6681        let body = serde_json::to_vec(&requests)?;
6682
6683        let resp: Vec<OKXCancelAlgoOrderResponse> = self
6684            .inner
6685            .send_request::<_, ()>(
6686                Method::POST,
6687                "/api/v5/trade/cancel-algos",
6688                None,
6689                Some(body),
6690                true,
6691            )
6692            .await?;
6693
6694        for item in &resp {
6695            if let Some(ref code) = item.s_code
6696                && code != "0"
6697            {
6698                let msg = item.s_msg.as_deref().unwrap_or("");
6699                log::debug!(
6700                    "Algo cancel rejected: algo_id={} sCode={code} sMsg={msg}",
6701                    item.algo_id
6702                );
6703            }
6704        }
6705
6706        Ok(resp)
6707    }
6708
6709    /// Cancels advance algo orders (trailing stop, iceberg, TWAP) via HTTP.
6710    ///
6711    /// These order types cannot use the standard `cancel-algos` endpoint.
6712    /// Items with non-zero `sCode` are logged at debug level.
6713    ///
6714    /// # Errors
6715    ///
6716    /// Returns an error if the request fails.
6717    ///
6718    /// # References
6719    ///
6720    /// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-advance-algo-order>
6721    pub async fn cancel_advance_algo_orders(
6722        &self,
6723        requests: Vec<OKXCancelAlgoOrderRequest>,
6724    ) -> Result<Vec<OKXCancelAlgoOrderResponse>, OKXHttpError> {
6725        if requests.is_empty() {
6726            return Ok(Vec::new());
6727        }
6728
6729        let body = serde_json::to_vec(&requests)?;
6730
6731        let resp: Vec<OKXCancelAlgoOrderResponse> = self
6732            .inner
6733            .send_request::<_, ()>(
6734                Method::POST,
6735                "/api/v5/trade/cancel-advance-algos",
6736                None,
6737                Some(body),
6738                true,
6739            )
6740            .await?;
6741
6742        for item in &resp {
6743            if let Some(ref code) = item.s_code
6744                && code != "0"
6745            {
6746                let msg = item.s_msg.as_deref().unwrap_or("");
6747                log::debug!(
6748                    "Advance algo cancel rejected: algo_id={} sCode={code} sMsg={msg}",
6749                    item.algo_id
6750                );
6751            }
6752        }
6753
6754        Ok(resp)
6755    }
6756
6757    /// Amends an algo order via HTTP.
6758    ///
6759    /// # Errors
6760    ///
6761    /// Returns an error if the request fails.
6762    ///
6763    /// # References
6764    ///
6765    /// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-amend-algo-order>
6766    pub async fn amend_algo_order(
6767        &self,
6768        request: OKXAmendAlgoOrderRequest,
6769    ) -> Result<OKXAmendAlgoOrderResponse, OKXHttpError> {
6770        let body = serde_json::to_vec(&request)?;
6771
6772        let resp: Vec<OKXAmendAlgoOrderResponse> = self
6773            .inner
6774            .send_request::<_, ()>(
6775                Method::POST,
6776                "/api/v5/trade/amend-algos",
6777                None,
6778                Some(body),
6779                true,
6780            )
6781            .await?;
6782
6783        resp.into_iter().next().ok_or(OKXHttpError::EmptyResponse)
6784    }
6785
6786    /// Amends an algo order using domain types.
6787    ///
6788    /// This is a convenience method that accepts Nautilus domain types
6789    /// and builds the appropriate OKX request structure internally.
6790    ///
6791    /// # Errors
6792    ///
6793    /// Returns an error if the request fails.
6794    #[expect(clippy::too_many_arguments)]
6795    pub async fn amend_algo_order_with_domain_types(
6796        &self,
6797        instrument_id: InstrumentId,
6798        algo_id: String,
6799        new_trigger_price: Option<Price>,
6800        new_sl_trigger_price: Option<Price>,
6801        new_limit_price: Option<Price>,
6802        new_quantity: Option<Quantity>,
6803        new_callback_ratio: Option<String>,
6804        new_callback_spread: Option<String>,
6805        new_activation_price: Option<Price>,
6806        new_tp_trigger_price: Option<Price>,
6807        new_tp_order_price: Option<String>,
6808        new_tp_trigger_px_type: Option<String>,
6809        new_sl_order_price: Option<String>,
6810        new_sl_trigger_px_type: Option<String>,
6811    ) -> Result<OKXAmendAlgoOrderResponse, OKXHttpError> {
6812        let request = OKXAmendAlgoOrderRequest {
6813            inst_id: instrument_id.symbol.as_str().to_string(),
6814            algo_id,
6815            algo_cl_ord_id: None,
6816            new_sz: new_quantity.map(|q| q.to_string()),
6817            new_trigger_px: new_trigger_price.map(|p| p.to_string()),
6818            new_trigger_px_type: None,
6819            new_tp_trigger_px: new_tp_trigger_price.map(|p| p.to_string()),
6820            new_tp_ord_px: new_tp_order_price,
6821            new_tp_trigger_px_type,
6822            new_sl_trigger_px: new_sl_trigger_price.map(|p| p.to_string()),
6823            new_sl_ord_px: new_sl_order_price,
6824            new_sl_trigger_px_type,
6825            new_order_px: new_limit_price.map(|p| p.to_string()),
6826            new_callback_ratio,
6827            new_callback_spread,
6828            new_active_px: new_activation_price.map(|p| p.to_string()),
6829        };
6830
6831        self.amend_algo_order(request).await
6832    }
6833
6834    /// Places an algo order using domain types.
6835    ///
6836    /// This is a convenience method that accepts Nautilus domain types
6837    /// and builds the appropriate OKX request structure internally.
6838    ///
6839    /// # Errors
6840    ///
6841    /// Returns an error if the request fails.
6842    #[expect(clippy::too_many_arguments)]
6843    pub async fn place_order_with_domain_types(
6844        &self,
6845        instrument_id: InstrumentId,
6846        td_mode: OKXTradeMode,
6847        client_order_id: ClientOrderId,
6848        order_side: OrderSide,
6849        order_type: OrderType,
6850        quantity: Quantity,
6851        time_in_force: Option<TimeInForce>,
6852        price: Option<Price>,
6853        post_only: Option<bool>,
6854        reduce_only: Option<bool>,
6855        quote_quantity: Option<bool>,
6856        position_side: Option<PositionSide>,
6857        attach_algo_ords: Option<Vec<OKXAttachAlgoOrdRequest>>,
6858        px_usd: Option<String>,
6859        px_vol: Option<String>,
6860        outcome: Option<String>,
6861        slippage_pct: Option<String>,
6862        rpi: Option<bool>,
6863        rpi_taker_access: Option<bool>,
6864        rpi_px_round: Option<bool>,
6865    ) -> Result<OKXPlaceOrderResponse, OKXHttpError> {
6866        let rpi = rpi.unwrap_or(false);
6867
6868        if self.is_spread(instrument_id) {
6869            if reduce_only.unwrap_or(false)
6870                || quote_quantity.unwrap_or(false)
6871                || attach_algo_ords
6872                    .as_ref()
6873                    .is_some_and(|orders| !orders.is_empty())
6874                || px_usd.is_some()
6875                || px_vol.is_some()
6876                || outcome.is_some()
6877                || slippage_pct.is_some()
6878                || rpi
6879                || rpi_taker_access.is_some()
6880                || rpi_px_round.is_some()
6881            {
6882                return Err(OKXHttpError::ValidationError(
6883                    "OKX spread orders do not support regular order extensions".to_string(),
6884                ));
6885            }
6886
6887            return self
6888                .place_spread_order_with_domain_types(
6889                    instrument_id,
6890                    client_order_id,
6891                    order_side,
6892                    order_type,
6893                    quantity,
6894                    time_in_force,
6895                    price,
6896                    post_only,
6897                )
6898                .await;
6899        }
6900
6901        if !OKX_SUPPORTED_ORDER_TYPES.contains(&order_type) {
6902            return Err(OKXHttpError::ValidationError(format!(
6903                "Unsupported order type: {order_type:?}",
6904            )));
6905        }
6906
6907        if matches!(
6908            order_type,
6909            OrderType::StopMarket
6910                | OrderType::StopLimit
6911                | OrderType::MarketIfTouched
6912                | OrderType::LimitIfTouched
6913                | OrderType::TrailingStopMarket
6914        ) {
6915            return Err(OKXHttpError::ValidationError(
6916                "Conditional order types must use OKX algo order placement".to_string(),
6917            ));
6918        }
6919
6920        validate_order_time_in_force(time_in_force).map_err(OKXHttpError::ValidationError)?;
6921
6922        if !matches!(order_side, OrderSide::Buy | OrderSide::Sell) {
6923            return Err(OKXHttpError::ValidationError(
6924                "Invalid order side".to_string(),
6925            ));
6926        }
6927
6928        let instrument = self
6929            .instrument_from_cache(instrument_id.symbol.inner())
6930            .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
6931        let instrument_type = okx_instrument_type(&instrument)
6932            .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
6933
6934        // OKX options only support limit-style orders
6935        if instrument_type == OKXInstrumentType::Option
6936            && matches!(order_type, OrderType::Market | OrderType::MarketToLimit)
6937        {
6938            return Err(OKXHttpError::ValidationError(
6939                "Market orders are not supported for OKX options, use Limit orders instead"
6940                    .to_string(),
6941            ));
6942        }
6943
6944        let side = OKXSide::from(order_side);
6945        let pos_side = position_side.map(Into::into).or({
6946            if matches!(
6947                instrument_type,
6948                OKXInstrumentType::Swap | OKXInstrumentType::Futures | OKXInstrumentType::Option
6949            ) {
6950                Some(OKXPositionSide::Net)
6951            } else {
6952                None
6953            }
6954        });
6955
6956        let tgt_ccy =
6957            okx_market_target_currency(instrument_type, order_side, order_type, quote_quantity)
6958                .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
6959
6960        validate_regular_order_params(
6961            instrument_type,
6962            order_type,
6963            time_in_force,
6964            post_only.unwrap_or(false),
6965            rpi,
6966            outcome.as_deref(),
6967        )
6968        .map_err(OKXHttpError::ValidationError)?;
6969
6970        let (ord_type, px) = if rpi {
6971            (OKXOrderType::Rpi, price)
6972        } else if post_only.unwrap_or(false) {
6973            (OKXOrderType::PostOnly, price)
6974        } else if let Some(tif) = time_in_force {
6975            match (order_type, tif) {
6976                (OrderType::Market, TimeInForce::Ioc) => {
6977                    // optimal_limit_ioc only works for SWAP/FUTURES
6978                    if matches!(
6979                        instrument_type,
6980                        OKXInstrumentType::Spot | OKXInstrumentType::Option
6981                    ) {
6982                        (OKXOrderType::Market, price)
6983                    } else {
6984                        (OKXOrderType::OptimalLimitIoc, price)
6985                    }
6986                }
6987                (OrderType::Limit, TimeInForce::Fok) => (OKXOrderType::Fok, price),
6988                (OrderType::Limit, TimeInForce::Ioc) => (OKXOrderType::Ioc, price),
6989                _ => (OKXOrderType::from(order_type), price),
6990            }
6991        } else {
6992            (OKXOrderType::from(order_type), price)
6993        };
6994
6995        let reduce_only = if reduce_only == Some(true) || position_side.is_some() {
6996            okx_reduce_only_wire_value(
6997                instrument_type,
6998                td_mode,
6999                order_side,
7000                position_side,
7001                reduce_only,
7002            )
7003            .map_err(OKXHttpError::ValidationError)?
7004        } else {
7005            reduce_only
7006        };
7007
7008        // For options: pxUsd/pxVol are mutually exclusive with px
7009        let (px, px_usd, px_vol) = if px_usd.is_some() {
7010            (None, px_usd, None)
7011        } else if px_vol.is_some() {
7012            (None, None, px_vol)
7013        } else {
7014            (px.map(|p| p.to_string()), None, None)
7015        };
7016
7017        let trade_quote_ccy =
7018            self.resolve_spot_trade_quote_ccy(instrument_type, instrument_id.symbol.inner())?;
7019
7020        let request = OKXPlaceOrderRequest {
7021            inst_id: instrument_id.symbol.as_str().to_string(),
7022            td_mode,
7023            ccy: None,
7024            cl_ord_id: Some(client_order_id.as_str().to_string()),
7025            tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
7026            side,
7027            pos_side,
7028            ord_type,
7029            sz: quantity.to_string(),
7030            px,
7031            px_usd,
7032            px_vol,
7033            reduce_only,
7034            tgt_ccy,
7035            trade_quote_ccy,
7036            attach_algo_ords,
7037            outcome,
7038            slippage_pct,
7039            rpi_taker_access,
7040            rpi_px_round,
7041        };
7042
7043        self.place_order(request).await
7044    }
7045
7046    /// Places a spread order using domain types.
7047    ///
7048    /// # Errors
7049    ///
7050    /// Returns an error if the order cannot be represented by the OKX spread endpoint
7051    /// or if the request fails.
7052    #[expect(clippy::too_many_arguments)]
7053    pub async fn place_spread_order_with_domain_types(
7054        &self,
7055        instrument_id: InstrumentId,
7056        client_order_id: ClientOrderId,
7057        order_side: OrderSide,
7058        order_type: OrderType,
7059        quantity: Quantity,
7060        time_in_force: Option<TimeInForce>,
7061        price: Option<Price>,
7062        post_only: Option<bool>,
7063    ) -> Result<OKXPlaceOrderResponse, OKXHttpError> {
7064        if !self.is_spread(instrument_id) {
7065            return Err(OKXHttpError::ValidationError(format!(
7066                "Instrument is not an OKX spread: {instrument_id}",
7067            )));
7068        }
7069
7070        if !matches!(order_side, OrderSide::Buy | OrderSide::Sell) {
7071            return Err(OKXHttpError::ValidationError(
7072                "Invalid order side".to_string(),
7073            ));
7074        }
7075
7076        if !matches!(order_type, OrderType::Limit) {
7077            return Err(OKXHttpError::ValidationError(
7078                "OKX spread orders support Limit orders only".to_string(),
7079            ));
7080        }
7081
7082        let ord_type = if post_only.unwrap_or(false) {
7083            OKXOrderType::PostOnly
7084        } else if matches!(time_in_force, Some(TimeInForce::Ioc)) {
7085            OKXOrderType::Ioc
7086        } else if matches!(time_in_force, Some(TimeInForce::Fok)) {
7087            return Err(OKXHttpError::ValidationError(
7088                "OKX spread orders do not support FOK time-in-force".to_string(),
7089            ));
7090        } else {
7091            OKXOrderType::Limit
7092        };
7093
7094        let price = price.ok_or_else(|| {
7095            OKXHttpError::ValidationError("OKX spread orders require a limit price".to_string())
7096        })?;
7097
7098        let request = OKXPlaceSpreadOrderRequest {
7099            sprd_id: instrument_id.symbol.as_str().to_string(),
7100            cl_ord_id: Some(client_order_id.as_str().to_string()),
7101            tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
7102            side: OKXSide::from(order_side),
7103            ord_type,
7104            sz: quantity.to_string(),
7105            px: Some(price.to_string()),
7106        };
7107
7108        self.place_spread_order(request).await
7109    }
7110
7111    /// Places an algo order using domain types.
7112    ///
7113    /// Spot `StopMarket` and `MarketIfTouched` buys use `conditional` orders with explicit
7114    /// base (`quote_quantity=false`) or quote (`true`) sizing. Spot trailing buys require
7115    /// quote sizing. Other algo orders require base size or derivative contracts.
7116    /// Cash-spot triggers support last price only; cross/isolated feeds depend on the account mode
7117    /// and algo type.
7118    /// Trailing orders reject mark/index feeds.
7119    ///
7120    /// # Errors
7121    ///
7122    /// Returns an error if the quantity denomination or trigger feed is unsupported,
7123    /// required trigger terms are missing, or the request fails.
7124    #[expect(clippy::too_many_arguments)]
7125    pub async fn place_algo_order_with_domain_types(
7126        &self,
7127        instrument_id: InstrumentId,
7128        td_mode: OKXTradeMode,
7129        client_order_id: ClientOrderId,
7130        order_side: OrderSide,
7131        order_type: OrderType,
7132        quantity: Quantity,
7133        quote_quantity: bool,
7134        trigger_price: Option<Price>,
7135        trigger_type: Option<TriggerType>,
7136        limit_price: Option<Price>,
7137        reduce_only: Option<bool>,
7138        position_side: Option<PositionSide>,
7139        close_fraction: Option<String>,
7140        callback_ratio: Option<String>,
7141        callback_spread: Option<String>,
7142        activation_price: Option<Price>,
7143    ) -> Result<OKXPlaceAlgoOrderResponse, OKXHttpError> {
7144        if !matches!(order_side, OrderSide::Buy | OrderSide::Sell) {
7145            return Err(OKXHttpError::ValidationError(
7146                "Invalid order side".to_string(),
7147            ));
7148        }
7149
7150        let okx_side = OKXSide::from(order_side);
7151
7152        let instrument_type = okx_instrument_type_from_symbol(instrument_id.symbol.as_str());
7153
7154        let tgt_ccy = okx_algo_target_currency(
7155            instrument_type,
7156            td_mode,
7157            order_side,
7158            order_type,
7159            quote_quantity,
7160        )
7161        .map_err(OKXHttpError::from_order_denial)?;
7162
7163        validate_algo_trigger_type(instrument_type, td_mode, order_type, trigger_type)
7164            .map_err(OKXHttpError::ValidationError)?;
7165
7166        let ccy = if instrument_type == OKXInstrumentType::Spot && td_mode != OKXTradeMode::Cash {
7167            let (_, quote) = parse_base_quote_from_symbol(instrument_id.symbol.as_str())
7168                .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
7169            Some(quote.to_string())
7170        } else {
7171            None
7172        };
7173
7174        let trigger_px_type_enum = trigger_type.map_or(OKXTriggerType::Last, Into::into);
7175
7176        let uses_close_fraction = close_fraction.is_some();
7177
7178        let (
7179            algo_type,
7180            sz,
7181            trigger_px,
7182            order_px,
7183            trigger_px_type,
7184            sl_trigger_px,
7185            sl_ord_px,
7186            sl_trigger_px_type,
7187            tp_trigger_px,
7188            tp_ord_px,
7189            tp_trigger_px_type,
7190            pos_side,
7191            reduce_only,
7192        ) = if uses_close_fraction || tgt_ccy.is_some() {
7193            if order_type == OrderType::TrailingStopMarket {
7194                return Err(OKXHttpError::ValidationError(
7195                    "OKX close_fraction does not support TrailingStopMarket".to_string(),
7196                ));
7197            }
7198
7199            let trigger_px = trigger_price.map(|p| p.to_string()).ok_or_else(|| {
7200                OKXHttpError::ValidationError(
7201                    "OKX conditional orders require trigger_price".to_string(),
7202                )
7203            })?;
7204
7205            let close_order_px =
7206                if matches!(order_type, OrderType::StopLimit | OrderType::LimitIfTouched) {
7207                    limit_price.map(|p| p.to_string()).ok_or_else(|| {
7208                        OKXHttpError::ValidationError(format!(
7209                            "OKX {order_type:?} close_fraction orders require limit_price"
7210                        ))
7211                    })?
7212                } else {
7213                    "-1".to_string()
7214                };
7215
7216            let (
7217                sl_trigger_px,
7218                sl_ord_px,
7219                sl_trigger_px_type,
7220                tp_trigger_px,
7221                tp_ord_px,
7222                tp_trigger_px_type,
7223            ) = match order_type {
7224                OrderType::StopMarket | OrderType::StopLimit => (
7225                    Some(trigger_px),
7226                    Some(close_order_px),
7227                    Some(trigger_px_type_enum),
7228                    None,
7229                    None,
7230                    None,
7231                ),
7232                OrderType::MarketIfTouched | OrderType::LimitIfTouched => (
7233                    None,
7234                    None,
7235                    None,
7236                    Some(trigger_px),
7237                    Some(close_order_px),
7238                    Some(trigger_px_type_enum),
7239                ),
7240                _ => {
7241                    return Err(OKXHttpError::ValidationError(format!(
7242                        "OKX close_fraction is only supported for stop/touched conditional orders, received {order_type:?}"
7243                    )));
7244                }
7245            };
7246
7247            (
7248                OKXAlgoOrderType::Conditional,
7249                (!uses_close_fraction).then(|| quantity.to_string()),
7250                None,
7251                None,
7252                None,
7253                sl_trigger_px,
7254                sl_ord_px,
7255                sl_trigger_px_type,
7256                tp_trigger_px,
7257                tp_ord_px,
7258                tp_trigger_px_type,
7259                if uses_close_fraction {
7260                    Some(position_side.map_or(OKXPositionSide::Net, Into::into))
7261                } else {
7262                    position_side.map(Into::into)
7263                },
7264                if uses_close_fraction {
7265                    Some(true)
7266                } else {
7267                    reduce_only
7268                },
7269            )
7270        } else {
7271            let algo_type = conditional_order_to_algo_type(order_type)
7272                .map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
7273
7274            let order_px = if matches!(order_type, OrderType::StopLimit | OrderType::LimitIfTouched)
7275            {
7276                limit_price.map(|p| p.to_string())
7277            } else if order_type == OrderType::TrailingStopMarket {
7278                None
7279            } else {
7280                Some("-1".to_string())
7281            };
7282
7283            (
7284                algo_type,
7285                Some(quantity.to_string()),
7286                trigger_price.map(|p| p.to_string()),
7287                order_px,
7288                Some(trigger_px_type_enum),
7289                None,
7290                None,
7291                None,
7292                None,
7293                None,
7294                None,
7295                position_side.map(Into::into),
7296                reduce_only,
7297            )
7298        };
7299
7300        let reduce_only = if position_side.is_some() {
7301            okx_reduce_only_wire_value(
7302                instrument_type,
7303                td_mode,
7304                order_side,
7305                position_side,
7306                reduce_only,
7307            )
7308            .map_err(OKXHttpError::ValidationError)?
7309        } else {
7310            reduce_only
7311        };
7312
7313        let request = OKXPlaceAlgoOrderRequest {
7314            inst_id: instrument_id.symbol.as_str().to_string(),
7315            inst_id_code: None,
7316            td_mode,
7317            side: okx_side,
7318            ord_type: algo_type,
7319            sz,
7320            algo_cl_ord_id: Some(client_order_id.as_str().to_string()),
7321            trigger_px,
7322            order_px,
7323            trigger_px_type,
7324            sl_trigger_px,
7325            sl_ord_px,
7326            sl_trigger_px_type,
7327            tp_trigger_px,
7328            tp_ord_px,
7329            tp_trigger_px_type,
7330            tgt_ccy,
7331            pos_side,
7332            close_position: None,
7333            tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
7334            reduce_only,
7335            close_fraction,
7336            callback_ratio,
7337            callback_spread,
7338            active_px: activation_price.map(|p| p.to_string()),
7339            ccy,
7340        };
7341
7342        self.place_algo_order(request).await
7343    }
7344
7345    /// Cancels an algo order using domain types.
7346    ///
7347    /// This is a convenience method that accepts Nautilus domain types
7348    /// and builds the appropriate OKX request structure internally.
7349    ///
7350    /// # Errors
7351    ///
7352    /// Returns an error if the request fails.
7353    pub async fn cancel_algo_order_with_domain_types(
7354        &self,
7355        instrument_id: InstrumentId,
7356        algo_id: String,
7357    ) -> Result<OKXCancelAlgoOrderResponse, OKXHttpError> {
7358        let request = OKXCancelAlgoOrderRequest {
7359            inst_id: instrument_id.symbol.to_string(),
7360            inst_id_code: None,
7361            algo_id: Some(algo_id),
7362            algo_cl_ord_id: None,
7363        };
7364
7365        self.cancel_algo_order(request).await
7366    }
7367
7368    /// Requests algo order status reports.
7369    ///
7370    /// # Errors
7371    ///
7372    /// Returns an error if the request fails.
7373    #[expect(clippy::too_many_arguments)]
7374    pub async fn request_algo_order_status_reports(
7375        &self,
7376        account_id: AccountId,
7377        instrument_type: Option<OKXInstrumentType>,
7378        instrument_id: Option<InstrumentId>,
7379        algo_id: Option<String>,
7380        algo_client_order_id: Option<ClientOrderId>,
7381        state: Option<OKXAlgoOrderStatus>,
7382        limit: Option<u32>,
7383    ) -> anyhow::Result<Vec<OrderStatusReport>> {
7384        Ok(self
7385            .request_algo_order_status_reports_sweep(
7386                account_id,
7387                instrument_type,
7388                instrument_id,
7389                algo_id,
7390                algo_client_order_id,
7391                state,
7392                limit,
7393                None,
7394                None,
7395                false,
7396                None,
7397            )
7398            .await?
7399            .reports)
7400    }
7401
7402    #[expect(clippy::too_many_arguments)]
7403    pub(crate) async fn request_algo_order_status_reports_sweep(
7404        &self,
7405        account_id: AccountId,
7406        instrument_type: Option<OKXInstrumentType>,
7407        instrument_id: Option<InstrumentId>,
7408        algo_id: Option<String>,
7409        algo_client_order_id: Option<ClientOrderId>,
7410        state: Option<OKXAlgoOrderStatus>,
7411        limit: Option<u32>,
7412        start: Option<Timestamp>,
7413        end: Option<Timestamp>,
7414        require_complete_active_coverage: bool,
7415        max_history_pages: Option<u32>,
7416    ) -> anyhow::Result<AlgoOrderReportSweep> {
7417        let mut instruments_cache: AHashMap<Ustr, InstrumentAny> = AHashMap::new();
7418        let mut ambiguous_triggered_child_ids = AHashSet::new();
7419        let has_specific_lookup = algo_id.is_some() || algo_client_order_id.is_some();
7420        let start_ns = start.map(UnixNanos::from);
7421        let end_ns = end.map(UnixNanos::from);
7422        let mut complete = true;
7423
7424        let inst_type = if let Some(inst_type) = instrument_type {
7425            inst_type
7426        } else if let Some(inst_id) = instrument_id {
7427            let instrument = self.resolve_instrument(inst_id).await?;
7428
7429            let inst_type = okx_instrument_type(&instrument)?;
7430            instruments_cache.insert(inst_id.symbol.inner(), instrument);
7431            inst_type
7432        } else {
7433            anyhow::bail!("instrument_type or instrument_id required for algo order query")
7434        };
7435
7436        let ts_init = self.generate_ts_init();
7437        let mut reports = Vec::new();
7438        let mut seen: AHashMap<(String, String), usize> = AHashMap::new();
7439
7440        if has_specific_lookup {
7441            let mut params_builder = GetAlgoOrderParamsBuilder::default();
7442
7443            if let Some(algo_id) = algo_id {
7444                params_builder.algo_id(algo_id);
7445            }
7446
7447            if let Some(client_order_id) = algo_client_order_id {
7448                params_builder.algo_cl_ord_id(client_order_id.as_str().to_string());
7449            }
7450
7451            let params = params_builder
7452                .build()
7453                .map_err(|e| anyhow::anyhow!(format!("Failed to build algo order params: {e}")))?;
7454            let mut orders = match self.inner.get_algo_order(params).await {
7455                Ok(orders) => orders,
7456                Err(e) if e.is_order_not_found() => {
7457                    return Ok(AlgoOrderReportSweep {
7458                        reports,
7459                        complete,
7460                        ambiguous_triggered_child_ids,
7461                    });
7462                }
7463                Err(e) => return Err(e.into()),
7464            };
7465
7466            if let Some(state) = state {
7467                orders.retain(|order| order.state == state);
7468            }
7469
7470            self.resolve_close_fraction_sizes(&mut orders).await?;
7471
7472            complete &= self
7473                .collect_algo_reports(
7474                    account_id,
7475                    &orders,
7476                    false,
7477                    &mut instruments_cache,
7478                    ts_init,
7479                    start_ns,
7480                    end_ns,
7481                    &mut seen,
7482                    &mut reports,
7483                    &mut ambiguous_triggered_child_ids,
7484                )
7485                .await?;
7486
7487            if let Some(limit) = limit {
7488                reports.truncate(limit as usize);
7489            }
7490
7491            return Ok(AlgoOrderReportSweep {
7492                reports,
7493                complete,
7494                ambiguous_triggered_child_ids,
7495            });
7496        }
7497
7498        let query_pending = state.is_none()
7499            || matches!(
7500                state,
7501                Some(OKXAlgoOrderStatus::Live | OKXAlgoOrderStatus::Pause)
7502            );
7503        let history_states: &[OKXAlgoOrderStatus] = match state {
7504            None => &[
7505                OKXAlgoOrderStatus::Effective,
7506                OKXAlgoOrderStatus::Canceled,
7507                OKXAlgoOrderStatus::OrderFailed,
7508            ],
7509            // An unrecognized state cannot be queried by name and matches nothing
7510            Some(OKXAlgoOrderStatus::Unknown) => &[],
7511            Some(OKXAlgoOrderStatus::Live | OKXAlgoOrderStatus::Pause) => &[],
7512            Some(
7513                OKXAlgoOrderStatus::Effective
7514                | OKXAlgoOrderStatus::OrderPlaced
7515                | OKXAlgoOrderStatus::PartiallyEffective
7516                | OKXAlgoOrderStatus::Filled,
7517            ) => &[OKXAlgoOrderStatus::Effective],
7518            Some(OKXAlgoOrderStatus::Canceled) => &[OKXAlgoOrderStatus::Canceled],
7519            Some(OKXAlgoOrderStatus::OrderFailed | OKXAlgoOrderStatus::PartiallyFailed) => {
7520                &[OKXAlgoOrderStatus::OrderFailed]
7521            }
7522        };
7523
7524        for ord_type in [
7525            OKXAlgoOrderType::Oco,
7526            OKXAlgoOrderType::Conditional,
7527            OKXAlgoOrderType::Trigger,
7528            OKXAlgoOrderType::MoveOrderStop,
7529        ] {
7530            let mut params_builder = GetAlgoOrdersParamsBuilder::default();
7531            params_builder.inst_type(inst_type);
7532            params_builder.ord_type(ord_type);
7533
7534            if let Some(inst_id) = instrument_id {
7535                params_builder.inst_id(inst_id.symbol.inner().to_string());
7536            }
7537
7538            let mut params = params_builder
7539                .build()
7540                .map_err(|e| anyhow::anyhow!(format!("Failed to build algo order params: {e}")))?;
7541
7542            if query_pending {
7543                let remaining = limit.map(|l| (l as usize).saturating_sub(reports.len()));
7544                let pending_sweep = match self
7545                    .paginate_algo_pending(&params, remaining, require_complete_active_coverage)
7546                    .await
7547                {
7548                    Ok(sweep) => sweep,
7549                    Err(e) if require_complete_active_coverage => {
7550                        return Err(OKXPendingAlgoOrderReportsError::new(e).into());
7551                    }
7552                    Err(e) => return Err(e),
7553                };
7554
7555                if require_complete_active_coverage && !pending_sweep.complete {
7556                    return Err(OKXPendingAlgoOrderReportsError::new(anyhow::anyhow!(
7557                        "Pending {ord_type:?} algo order pagination for {inst_type:?} did not establish complete coverage"
7558                    ))
7559                    .into());
7560                }
7561                complete &= pending_sweep.complete;
7562                let mut pending = pending_sweep.items;
7563
7564                if let Some(state) = state {
7565                    pending.retain(|order| order.state == state);
7566                }
7567
7568                self.resolve_close_fraction_sizes(&mut pending)
7569                    .await
7570                    .map_err(OKXPendingAlgoOrderReportsError::new)?;
7571
7572                let pending_reports_complete = match self
7573                    .collect_algo_reports(
7574                        account_id,
7575                        &pending,
7576                        require_complete_active_coverage,
7577                        &mut instruments_cache,
7578                        ts_init,
7579                        start_ns,
7580                        end_ns,
7581                        &mut seen,
7582                        &mut reports,
7583                        &mut ambiguous_triggered_child_ids,
7584                    )
7585                    .await
7586                {
7587                    Ok(complete) => complete,
7588                    Err(e) if require_complete_active_coverage => {
7589                        return Err(OKXPendingAlgoOrderReportsError::new(e).into());
7590                    }
7591                    Err(e) => return Err(e),
7592                };
7593
7594                if require_complete_active_coverage && !pending_reports_complete {
7595                    return Err(OKXPendingAlgoOrderReportsError::new(anyhow::anyhow!(
7596                        "Pending {ord_type:?} algo order reports for {inst_type:?} could not be completely converted"
7597                    ))
7598                    .into());
7599                }
7600                complete &= pending_reports_complete;
7601
7602                if let Some(lim) = limit
7603                    && reports.len() >= lim as usize
7604                {
7605                    reports.truncate(lim as usize);
7606                    return Ok(AlgoOrderReportSweep {
7607                        reports,
7608                        complete,
7609                        ambiguous_triggered_child_ids,
7610                    });
7611                }
7612            }
7613
7614            for history_state in history_states {
7615                params.state = Some(*history_state);
7616                let remaining = limit.map(|l| (l as usize).saturating_sub(reports.len()));
7617
7618                let history_sweep = match self
7619                    .paginate_algo_history(
7620                        &params,
7621                        remaining,
7622                        require_complete_active_coverage,
7623                        reconciliation_history_page_limit(max_history_pages),
7624                    )
7625                    .await
7626                {
7627                    Ok(sweep) => sweep,
7628                    Err(e) if require_complete_active_coverage => {
7629                        log::warn!(
7630                            "Failed to fetch {history_state:?} {ord_type:?} algo order history for {inst_type:?}: {e}"
7631                        );
7632                        complete = false;
7633                        continue;
7634                    }
7635                    Err(e) => return Err(e),
7636                };
7637                complete &= history_sweep.complete;
7638                let mut history = history_sweep.items;
7639
7640                if let Some(state) = state {
7641                    history.retain(|order| order.state == state);
7642                }
7643
7644                complete &= self
7645                    .collect_algo_reports(
7646                        account_id,
7647                        &history,
7648                        false,
7649                        &mut instruments_cache,
7650                        ts_init,
7651                        start_ns,
7652                        end_ns,
7653                        &mut seen,
7654                        &mut reports,
7655                        &mut ambiguous_triggered_child_ids,
7656                    )
7657                    .await?;
7658
7659                if let Some(lim) = limit
7660                    && reports.len() >= lim as usize
7661                {
7662                    reports.truncate(lim as usize);
7663                    return Ok(AlgoOrderReportSweep {
7664                        reports,
7665                        complete,
7666                        ambiguous_triggered_child_ids,
7667                    });
7668                }
7669            }
7670        }
7671
7672        Ok(AlgoOrderReportSweep {
7673            reports,
7674            complete,
7675            ambiguous_triggered_child_ids,
7676        })
7677    }
7678
7679    /// Requests an algo order status report by client order identifier.
7680    ///
7681    /// # Errors
7682    ///
7683    /// Returns an error if the request fails.
7684    pub async fn request_algo_order_status_report(
7685        &self,
7686        account_id: AccountId,
7687        instrument_id: InstrumentId,
7688        algo_client_order_id: ClientOrderId,
7689    ) -> anyhow::Result<Option<OrderStatusReport>> {
7690        let reports = self
7691            .request_algo_order_status_reports(
7692                account_id,
7693                None,
7694                Some(instrument_id),
7695                None,
7696                Some(algo_client_order_id),
7697                None,
7698                Some(50_u32),
7699            )
7700            .await?;
7701
7702        Ok(reports.into_iter().next())
7703    }
7704
7705    /// Exposes raw HTTP client for testing purposes
7706    pub fn raw_client(&self) -> &Arc<OKXRawHttpClient> {
7707        &self.inner
7708    }
7709
7710    /// Sets `sz` on open `closeFraction` algo orders from the positions they close.
7711    ///
7712    /// OKX omits `sz` when an algo order closes the whole position, and links the order to that
7713    /// position through `closeOrderAlgo` instead. Reconciliation needs a positive quantity to
7714    /// materialize the order, so the linked position size stands in for it.
7715    async fn resolve_close_fraction_sizes(
7716        &self,
7717        orders: &mut [OKXOrderAlgo],
7718    ) -> anyhow::Result<()> {
7719        let needs_size = |order: &OKXOrderAlgo| {
7720            order.sz.is_empty() && !order.close_fraction.is_empty() && is_open_okx_algo(order.state)
7721        };
7722
7723        if !orders.iter().any(needs_size) {
7724            return Ok(());
7725        }
7726
7727        let positions = self
7728            .inner
7729            .get_positions(GetPositionsParams::default())
7730            .await
7731            .map_err(|e| anyhow::anyhow!(e))?;
7732
7733        for order in orders.iter_mut().filter(|order| needs_size(order)) {
7734            let position = positions.iter().find(|position| {
7735                position
7736                    .close_order_algo
7737                    .iter()
7738                    .any(|algo| algo.algo_id == order.algo_id)
7739            });
7740
7741            let Some(position) = position else {
7742                log::warn!(
7743                    "No position links close-fraction algo order {}, quantity remains zero",
7744                    order.algo_id,
7745                );
7746                continue;
7747            };
7748
7749            let size = Decimal::from_str(&position.pos).with_context(|| {
7750                format!("invalid position size for algo order {}", order.algo_id)
7751            })?;
7752
7753            order.sz = size.abs().to_string();
7754        }
7755
7756        Ok(())
7757    }
7758
7759    #[expect(clippy::too_many_arguments)]
7760    async fn collect_algo_reports(
7761        &self,
7762        account_id: AccountId,
7763        orders: &[OKXOrderAlgo],
7764        from_pending_source: bool,
7765        instruments_cache: &mut AHashMap<Ustr, InstrumentAny>,
7766        ts_init: UnixNanos,
7767        start_ns: Option<UnixNanos>,
7768        end_ns: Option<UnixNanos>,
7769        seen: &mut AHashMap<(String, String), usize>,
7770        reports: &mut Vec<OrderStatusReport>,
7771        ambiguous_triggered_child_ids: &mut AHashSet<VenueOrderId>,
7772    ) -> anyhow::Result<bool> {
7773        let mut complete = true;
7774
7775        for order in orders {
7776            let key = (order.algo_id.clone(), order.algo_cl_ord_id.clone());
7777
7778            let has_ambiguous_children = order.ord_id_list.len() > 1
7779                || !order.sub_algo_id_list.is_empty()
7780                || matches!(
7781                    order.ord_id_list.as_slice(),
7782                    [child_order_id]
7783                        if !order.ord_id.is_empty() && child_order_id != &order.ord_id
7784                );
7785
7786            // An unknown pending state cannot establish that the order is terminal
7787            if !(from_pending_source && order.state == OKXAlgoOrderStatus::Unknown)
7788                && report_ts_outside_window(order.u_time, start_ns, end_ns)
7789                && !is_open_okx_algo(order.state)
7790            {
7791                continue;
7792            }
7793
7794            let instrument = if let Some(instrument) = instruments_cache.get(&order.inst_id) {
7795                instrument.clone()
7796            } else {
7797                match self
7798                    .resolve_report_instrument(
7799                        order.inst_id,
7800                        order.inst_type,
7801                        false,
7802                        is_open_okx_algo(order.state),
7803                        None,
7804                    )
7805                    .await?
7806                {
7807                    InstrumentResolution::Found(instrument) => {
7808                        instruments_cache.insert(order.inst_id, (*instrument).clone());
7809                        *instrument
7810                    }
7811                    InstrumentResolution::Skip => continue,
7812                    InstrumentResolution::Incomplete => {
7813                        complete = false;
7814                        continue;
7815                    }
7816                }
7817            };
7818
7819            let report = match parse_http_algo_order(order, account_id, &instrument, ts_init) {
7820                Ok(report) => report,
7821                Err(e) if !from_pending_source && is_open_okx_algo(order.state) => return Err(e),
7822                Err(e) => {
7823                    log::warn!("Failed to parse algo order report: {e}");
7824                    complete = false;
7825                    continue;
7826                }
7827            };
7828
7829            if has_ambiguous_children && report.order_status == OrderStatus::Triggered {
7830                log::warn!(
7831                    "Algo order {} has ambiguous child order identifiers",
7832                    order.algo_id,
7833                );
7834                ambiguous_triggered_child_ids.insert(report.venue_order_id);
7835            }
7836
7837            match seen.get(&key).copied() {
7838                Some(index) if is_order_status_report_more_advanced(&report, &reports[index]) => {
7839                    reports[index] = report;
7840                }
7841                Some(_) => {}
7842                None => {
7843                    seen.insert(key, reports.len());
7844                    reports.push(report);
7845                }
7846            }
7847        }
7848
7849        Ok(complete)
7850    }
7851
7852    pub(crate) async fn resolve_instrument(
7853        &self,
7854        instrument_id: InstrumentId,
7855    ) -> anyhow::Result<InstrumentAny> {
7856        match self.instrument_from_cache(instrument_id.symbol.inner()) {
7857            Ok(instrument) => Ok(instrument),
7858            Err(_) => self.request_instrument(instrument_id).await,
7859        }
7860    }
7861
7862    async fn resolve_report_instrument(
7863        &self,
7864        symbol: Ustr,
7865        inst_type: OKXInstrumentType,
7866        is_spread: bool,
7867        is_open_or_position: bool,
7868        scope: Option<ReportInstrumentScope<'_>>,
7869    ) -> anyhow::Result<InstrumentResolution> {
7870        if let Ok(instrument) = self.instrument_from_cache(symbol) {
7871            return Ok(InstrumentResolution::Found(Box::new(instrument)));
7872        }
7873
7874        let in_scope = match scope {
7875            None => true,
7876            Some(scope) if is_spread => scope.load_spreads,
7877            Some(scope) => {
7878                scope.instrument_types.contains(&inst_type)
7879                    || scope.instrument_types.contains(&OKXInstrumentType::Any)
7880            }
7881        };
7882
7883        if !in_scope {
7884            log::debug!("Skipping report for out-of-scope instrument: symbol={symbol}");
7885            return Ok(InstrumentResolution::Skip);
7886        }
7887
7888        if !is_open_or_position {
7889            log::warn!("Instrument {symbol} missing from cache");
7890            return Ok(InstrumentResolution::Incomplete);
7891        }
7892
7893        let instrument_id = format!("{symbol}.OKX")
7894            .parse::<InstrumentId>()
7895            .context("invalid report instrument symbol")?;
7896
7897        let result = if is_spread {
7898            self.request_spread_instrument(symbol.as_str())
7899                .await
7900                .inspect(|instrument| {
7901                    self.cache_instrument(instrument.clone());
7902                })
7903        } else {
7904            self.request_instrument(instrument_id).await
7905        };
7906
7907        result
7908            .map(|instrument| InstrumentResolution::Found(Box::new(instrument)))
7909            .with_context(|| format!("Instrument {symbol} missing from cache and recovery failed"))
7910    }
7911
7912    pub(crate) async fn request_spread_order_status_report(
7913        &self,
7914        account_id: AccountId,
7915        instrument_id: InstrumentId,
7916        client_order_id: Option<ClientOrderId>,
7917        venue_order_id: Option<VenueOrderId>,
7918    ) -> anyhow::Result<Option<OrderStatusReport>> {
7919        let instrument = self.instrument_from_cache(instrument_id.symbol.inner())?;
7920        let mut params_builder = GetSpreadOrderParamsBuilder::default();
7921
7922        match (client_order_id, venue_order_id) {
7923            (Some(client_order_id), None) => {
7924                params_builder.cl_ord_id(client_order_id.as_str().to_string());
7925            }
7926            (None, Some(venue_order_id)) => {
7927                params_builder.ord_id(venue_order_id.as_str().to_string());
7928            }
7929            _ => anyhow::bail!(
7930                "Exactly one of client_order_id or venue_order_id is required for a spread order detail request"
7931            ),
7932        }
7933
7934        let params = params_builder
7935            .build()
7936            .map_err(|e| anyhow::anyhow!("Failed to build spread order detail params: {e}"))?;
7937        let orders = match self.inner.get_spread_order(params).await {
7938            Ok(orders) => orders,
7939            Err(e) if e.is_order_not_found() => return Ok(None),
7940            Err(e) => return Err(e.into()),
7941        };
7942        let Some(order) = orders.into_iter().next() else {
7943            return Ok(None);
7944        };
7945        let ts_init = self.generate_ts_init();
7946        let report = parse_spread_order_status_report(
7947            &order,
7948            account_id,
7949            instrument.id(),
7950            instrument.price_precision(),
7951            instrument.size_precision(),
7952            ts_init,
7953        )?;
7954
7955        Ok(Some(report))
7956    }
7957}
7958
7959fn parse_historical_candlestick(
7960    raw: &OKXCandlestick,
7961    bar_type: BarType,
7962    price_precision: u8,
7963    size_precision: u8,
7964) -> anyhow::Result<Bar> {
7965    let mut bar = parse_candlestick(
7966        raw,
7967        bar_type,
7968        price_precision,
7969        size_precision,
7970        UnixNanos::default(),
7971    )?;
7972
7973    bar.ts_init = if bar_type.spec().aggregation == BarAggregation::Month {
7974        let time_zone = jiff::tz::TimeZone::fixed(jiff::tz::offset(8));
7975        let (_, _, close) = get_time_bar_bounds(
7976            bar.ts_event.to_datetime_utc(),
7977            &bar_type,
7978            None,
7979            &time_zone,
7980            None,
7981        );
7982        UnixNanos::from(close)
7983    } else {
7984        bar.ts_event + get_bar_interval_ns(&bar_type)
7985    };
7986
7987    Ok(bar)
7988}
7989
7990fn apply_post_only_rejection(order: &OKXOrderHistory, report: &mut OrderStatusReport) {
7991    let post_only_rejected = order.state == OKXOrderStatus::Canceled
7992        && report.filled_qty.is_zero()
7993        && (order.cancel_source == OKX_POST_ONLY_CANCEL_SOURCE
7994            || order.cancel_source_reason.contains("POST_ONLY"));
7995
7996    if !post_only_rejected {
7997        return;
7998    }
7999
8000    report.order_status = OrderStatus::Rejected;
8001    report.post_only = true;
8002
8003    let reason = if order.cancel_source_reason.is_empty() {
8004        OKX_POST_ONLY_CANCEL_REASON.to_string()
8005    } else {
8006        order.cancel_source_reason.clone()
8007    };
8008
8009    report.cancel_reason = Some(reason);
8010}
8011
8012fn is_open_okx_order(state: OKXOrderStatus, from_pending_source: bool) -> bool {
8013    matches!(
8014        state,
8015        OKXOrderStatus::Live | OKXOrderStatus::PartiallyFilled
8016    ) || (from_pending_source && state == OKXOrderStatus::Unknown)
8017}
8018
8019fn fill_quantity_is_positive(value: &str) -> Result<bool, rust_decimal::Error> {
8020    Ok(Decimal::from_str(value)? > Decimal::ZERO)
8021}
8022
8023fn report_ts_outside_window(
8024    timestamp_ms: u64,
8025    start_ns: Option<UnixNanos>,
8026    end_ns: Option<UnixNanos>,
8027) -> bool {
8028    if start_ns.is_none() && end_ns.is_none() {
8029        return false;
8030    }
8031
8032    let ts = parse_millisecond_timestamp(timestamp_ms);
8033    start_ns.is_some_and(|start| ts < start) || end_ns.is_some_and(|end| ts > end)
8034}
8035
8036fn is_open_okx_algo(state: OKXAlgoOrderStatus) -> bool {
8037    matches!(
8038        state,
8039        OKXAlgoOrderStatus::Live
8040            | OKXAlgoOrderStatus::Pause
8041            | OKXAlgoOrderStatus::OrderPlaced
8042            | OKXAlgoOrderStatus::PartiallyEffective
8043    )
8044}
8045
8046fn spread_page_limit(limit: Option<u32>) -> Option<u32> {
8047    limit.map(|limit| limit.min(OKX_PAGE_SIZE as u32))
8048}
8049
8050fn parse_http_algo_order(
8051    order: &OKXOrderAlgo,
8052    account_id: AccountId,
8053    instrument: &InstrumentAny,
8054    ts_init: UnixNanos,
8055) -> anyhow::Result<OrderStatusReport> {
8056    let ord_id = if order.ord_id.is_empty() {
8057        match order.ord_id_list.as_slice() {
8058            [child_order_id] => child_order_id.clone(),
8059            _ => String::new(),
8060        }
8061    } else {
8062        order.ord_id.clone()
8063    };
8064    let ord_px = if order.ord_px.is_empty() {
8065        "-1".to_string()
8066    } else {
8067        order.ord_px.clone()
8068    };
8069
8070    let reduce_only = if order.reduce_only.is_empty() {
8071        "false".to_string()
8072    } else {
8073        order.reduce_only.clone()
8074    };
8075
8076    let msg = OKXAlgoOrderMsg {
8077        algo_id: order.algo_id.clone(),
8078        algo_cl_ord_id: order.algo_cl_ord_id.clone(),
8079        cl_ord_id: order.cl_ord_id.clone(),
8080        ord_id,
8081        ord_id_list: order.ord_id_list.clone(),
8082        inst_id: order.inst_id,
8083        inst_type: order.inst_type,
8084        ord_type: order.ord_type,
8085        state: order.state,
8086        side: order.side,
8087        pos_side: order.pos_side,
8088        sz: order.sz.clone(),
8089        trigger_px: order.trigger_px.clone(),
8090        trigger_px_type: order.trigger_px_type.unwrap_or(OKXTriggerType::None),
8091        sl_trigger_px: order.sl_trigger_px.clone(),
8092        sl_ord_px: order.sl_ord_px.clone(),
8093        sl_trigger_px_type: order.sl_trigger_px_type.unwrap_or(OKXTriggerType::None),
8094        tp_trigger_px: order.tp_trigger_px.clone(),
8095        tp_ord_px: order.tp_ord_px.clone(),
8096        tp_trigger_px_type: order.tp_trigger_px_type.unwrap_or(OKXTriggerType::None),
8097        ord_px,
8098        td_mode: order.td_mode,
8099        lever: order.lever.clone(),
8100        reduce_only,
8101        close_fraction: order.close_fraction.clone(),
8102        actual_px: order.actual_px.clone(),
8103        actual_sz: order.actual_sz.clone(),
8104        notional_usd: order.notional_usd.clone(),
8105        c_time: order.c_time,
8106        u_time: order.u_time,
8107        trigger_time: order.trigger_time.clone(),
8108        fail_code: String::new(),
8109        tag: order.tag.clone(),
8110        callback_ratio: order.callback_ratio.clone(),
8111        callback_spread: order.callback_spread.clone(),
8112        active_px: order.active_px.clone(),
8113        ccy: None,
8114        tgt_ccy: None,
8115        fee: None,
8116        fee_ccy: None,
8117        advance_ord_type: None,
8118    };
8119
8120    parse_algo_order_status_report(&msg, instrument, account_id, ts_init)
8121}
8122
8123fn reconciliation_history_page_limit(max_pages: Option<u32>) -> usize {
8124    max_pages.map_or(MAX_RECONCILIATION_PAGES, |pages| {
8125        (pages as usize).min(MAX_RECONCILIATION_PAGES)
8126    })
8127}
8128
8129/// Returns the base currency whose cash balance a wallet-derived position report covers for
8130/// `instrument`, or `None` when the instrument is not a spot pair quoted in `quote_currency`.
8131fn spot_position_base_currency(
8132    instrument: &InstrumentAny,
8133    quote_currency: Ustr,
8134) -> Option<Currency> {
8135    if !matches!(instrument, InstrumentAny::CurrencyPair(_))
8136        || instrument.quote_currency().code != quote_currency
8137    {
8138        return None;
8139    }
8140
8141    instrument.base_currency()
8142}