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