Skip to main content

nautilus_kraken/http/futures/
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//! HTTP client for the Kraken Futures REST API.
17
18use std::{
19    collections::HashMap,
20    fmt::Debug,
21    num::NonZeroU32,
22    sync::{
23        Arc,
24        atomic::{AtomicBool, Ordering},
25    },
26};
27
28use ahash::{AHashMap, AHashSet};
29use indexmap::IndexMap;
30use jiff::Timestamp;
31use nautilus_common::cache::InstrumentLookupError;
32use nautilus_core::{
33    AtomicMap, AtomicTime, UUID4, nanos::UnixNanos, time::get_atomic_clock_realtime,
34};
35use nautilus_model::{
36    data::{Bar, BarType, BookOrder, FundingRateUpdate, TradeTick},
37    enums::{
38        AccountType, BookType, CurrencyType, MarketStatusAction, OrderSide, OrderType, TimeInForce,
39        TriggerType,
40    },
41    events::AccountState,
42    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, VenueOrderId},
43    instruments::{Instrument, InstrumentAny},
44    orderbook::OrderBook,
45    reports::{FillReport, OrderStatusReport, PositionStatusReport},
46    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
47};
48use nautilus_network::{
49    ConnectionUrl,
50    http::{
51        HttpClient, HttpRedirectPolicy, HttpResponse, Method, create_standard_nautilus_headers,
52    },
53    ratelimiter::quota::Quota,
54    retry::{RetryConfig, RetryError, RetryManager},
55};
56use parking_lot::RwLock;
57use rust_decimal::Decimal;
58use serde::de::DeserializeOwned;
59use tokio_util::sync::CancellationToken;
60use ustr::Ustr;
61
62use super::{models::*, query::*};
63use crate::{
64    common::{
65        consts::{KRAKEN_VENUE, NAUTILUS_KRAKEN_BROKER_ID},
66        credential::KrakenCredential,
67        enums::{
68            KrakenApiResult, KrakenEnvironment, KrakenFuturesOrderStatus, KrakenFuturesOrderType,
69            KrakenFuturesQtyMode, KrakenOrderSide, KrakenProductType, KrakenSendStatus,
70            KrakenTriggerSignal, product_type_from_symbol,
71        },
72        parse::{
73            bar_type_to_futures_resolution, normalize_asset_key, parse_bar,
74            parse_futures_fill_report, parse_futures_instrument,
75            parse_futures_order_event_status_report, parse_futures_order_status_details_report,
76            parse_futures_order_status_report, parse_futures_position_status_report,
77            parse_futures_public_execution, parse_venue_order_id,
78        },
79        urls::get_kraken_http_base_url,
80    },
81    http::{
82        apply_count_limit,
83        coverage::ReportCoverage,
84        error::{
85            KrakenBatchOrderError, KrakenHttpError, KrakenModifyOrderError, KrakenSubmitOrderError,
86            kraken_http_should_retry,
87        },
88        models::OhlcData,
89    },
90};
91
92/// Default Kraken Futures REST API rate limit (requests per second).
93pub const KRAKEN_FUTURES_DEFAULT_RATE_LIMIT_PER_SECOND: u32 = 5;
94
95const KRAKEN_GLOBAL_RATE_KEY: &str = "kraken:futures:global";
96
97/// Maximum orders per batch cancel request for Kraken Futures API.
98const BATCH_CANCEL_LIMIT: usize = 50;
99
100/// Maximum operations per batch order request for Kraken Futures API.
101const BATCH_ORDER_LIMIT: usize = 10;
102
103/// The largest order history page: the venue caps a larger `count` here silently and documents no
104/// default for this endpoint. A page costs one token whatever its size.
105const ORDER_HISTORY_PAGE_SIZE: usize = 1000;
106
107/// The response header Kraken documents for the order history continuation token; the body's
108/// `continuationToken` is read first and this header stands in when the body carries none.
109const NEXT_CONTINUATION_TOKEN_HEADER: &str = "Next-Continuation-Token";
110
111/// Raw HTTP client for low-level Kraken Futures API operations.
112///
113/// This client handles request/response operations with the Kraken Futures API,
114/// returning venue-specific response types. It does not parse to Nautilus domain types.
115pub struct KrakenFuturesRawHttpClient {
116    base_url: ConnectionUrl,
117    client: HttpClient,
118    credential: Option<KrakenCredential>,
119    retry_manager: RetryManager<KrakenHttpError>,
120    cancellation_token: RwLock<CancellationToken>,
121    clock: &'static AtomicTime,
122    /// Mutex to serialize authenticated requests, ensuring nonces arrive at Kraken in order
123    auth_mutex: tokio::sync::Mutex<()>,
124}
125
126impl Default for KrakenFuturesRawHttpClient {
127    fn default() -> Self {
128        Self::new(
129            KrakenEnvironment::Live,
130            None,
131            60,
132            None,
133            None,
134            None,
135            None,
136            KRAKEN_FUTURES_DEFAULT_RATE_LIMIT_PER_SECOND,
137        )
138        .expect("Failed to create default KrakenFuturesRawHttpClient")
139    }
140}
141
142impl Debug for KrakenFuturesRawHttpClient {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.debug_struct(stringify!(KrakenFuturesRawHttpClient))
145            .field("base_url", &self.base_url)
146            .field("has_credentials", &self.credential.is_some())
147            .finish()
148    }
149}
150
151impl KrakenFuturesRawHttpClient {
152    /// Creates a new [`KrakenFuturesRawHttpClient`].
153    #[expect(clippy::too_many_arguments)]
154    pub fn new(
155        environment: KrakenEnvironment,
156        base_url_override: Option<String>,
157        timeout_secs: u64,
158        max_retries: Option<u32>,
159        retry_delay_ms: Option<u64>,
160        retry_delay_max_ms: Option<u64>,
161        proxy_url: Option<String>,
162        max_requests_per_second: u32,
163    ) -> anyhow::Result<Self> {
164        let retry_config = RetryConfig {
165            max_retries: max_retries.unwrap_or(3),
166            initial_delay_ms: retry_delay_ms.unwrap_or(1000),
167            max_delay_ms: retry_delay_max_ms.unwrap_or(10_000),
168            backoff_factor: 2.0,
169            jitter_ms: 1000,
170            operation_timeout_ms: Some(60_000),
171            immediate_first: false,
172            max_elapsed_ms: Some(180_000),
173        };
174
175        let retry_manager = RetryManager::new(retry_config);
176        let base_url = base_url_override.unwrap_or_else(|| {
177            get_kraken_http_base_url(KrakenProductType::Futures, environment).to_string()
178        });
179
180        Ok(Self {
181            base_url: base_url.into(),
182            client: HttpClient::builder()
183                .headers(Self::default_headers())
184                .header_keys(vec![NEXT_CONTINUATION_TOKEN_HEADER.to_string()])
185                .keyed_quotas(Self::rate_limiter_quotas(max_requests_per_second)?)
186                .default_quota(Self::default_quota(max_requests_per_second)?)
187                .timeout_secs(timeout_secs)
188                .maybe_proxy_url(proxy_url)
189                .build()
190                .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?,
191            credential: None,
192            retry_manager,
193            cancellation_token: RwLock::new(CancellationToken::new()),
194            clock: get_atomic_clock_realtime(),
195            auth_mutex: tokio::sync::Mutex::new(()),
196        })
197    }
198
199    /// Creates a new [`KrakenFuturesRawHttpClient`] with credentials.
200    #[expect(clippy::too_many_arguments)]
201    pub fn with_credentials(
202        api_key: String,
203        api_secret: String,
204        environment: KrakenEnvironment,
205        base_url_override: Option<String>,
206        timeout_secs: u64,
207        max_retries: Option<u32>,
208        retry_delay_ms: Option<u64>,
209        retry_delay_max_ms: Option<u64>,
210        proxy_url: Option<String>,
211        max_requests_per_second: u32,
212    ) -> anyhow::Result<Self> {
213        let retry_config = RetryConfig {
214            max_retries: max_retries.unwrap_or(3),
215            initial_delay_ms: retry_delay_ms.unwrap_or(1000),
216            max_delay_ms: retry_delay_max_ms.unwrap_or(10_000),
217            backoff_factor: 2.0,
218            jitter_ms: 1000,
219            operation_timeout_ms: Some(60_000),
220            immediate_first: false,
221            max_elapsed_ms: Some(180_000),
222        };
223
224        let retry_manager = RetryManager::new(retry_config);
225        let base_url = base_url_override.unwrap_or_else(|| {
226            get_kraken_http_base_url(KrakenProductType::Futures, environment).to_string()
227        });
228
229        Ok(Self {
230            base_url: base_url.into(),
231            client: HttpClient::builder()
232                .redirect_policy(HttpRedirectPolicy::Reject)
233                .headers(Self::default_headers())
234                .header_keys(vec![NEXT_CONTINUATION_TOKEN_HEADER.to_string()])
235                .keyed_quotas(Self::rate_limiter_quotas(max_requests_per_second)?)
236                .default_quota(Self::default_quota(max_requests_per_second)?)
237                .timeout_secs(timeout_secs)
238                .maybe_proxy_url(proxy_url)
239                .build()
240                .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?,
241            credential: Some(KrakenCredential::new(api_key, api_secret)),
242            retry_manager,
243            cancellation_token: RwLock::new(CancellationToken::new()),
244            clock: get_atomic_clock_realtime(),
245            auth_mutex: tokio::sync::Mutex::new(()),
246        })
247    }
248
249    /// Generates a unique nonce for Kraken Futures API requests.
250    ///
251    /// Uses `AtomicTime` for strict monotonicity. The nanosecond timestamp
252    /// guarantees uniqueness even for rapid consecutive calls.
253    fn generate_nonce(&self) -> u64 {
254        self.clock.get_time_ns().as_u64()
255    }
256
257    /// Returns the base URL for this client.
258    pub fn base_url(&self) -> &str {
259        self.base_url.expose()
260    }
261
262    /// Returns the credential for this client, if set.
263    pub fn credential(&self) -> Option<&KrakenCredential> {
264        self.credential.as_ref()
265    }
266
267    /// Cancels all pending HTTP requests.
268    pub fn cancel_all_requests(&self) {
269        self.cancellation_token.read().cancel();
270    }
271
272    /// Replaces the canceled token so requests can proceed after reconnect.
273    pub fn reset_cancellation_token(&self) {
274        *self.cancellation_token.write() = CancellationToken::new();
275    }
276
277    /// Returns a clone of the current cancellation token.
278    pub fn cancellation_token(&self) -> CancellationToken {
279        self.cancellation_token.read().clone()
280    }
281
282    fn default_headers() -> HashMap<String, String> {
283        create_standard_nautilus_headers().into_iter().collect()
284    }
285
286    fn default_quota(max_requests_per_second: u32) -> anyhow::Result<Quota> {
287        let burst = NonZeroU32::new(max_requests_per_second).unwrap_or(
288            NonZeroU32::new(KRAKEN_FUTURES_DEFAULT_RATE_LIMIT_PER_SECOND).expect("non-zero"),
289        );
290        Quota::per_second(burst).ok_or_else(|| {
291            anyhow::anyhow!(
292                "Invalid max_requests_per_second: {max_requests_per_second} exceeds maximum"
293            )
294        })
295    }
296
297    fn rate_limiter_quotas(max_requests_per_second: u32) -> anyhow::Result<Vec<(String, Quota)>> {
298        Ok(vec![(
299            KRAKEN_GLOBAL_RATE_KEY.to_string(),
300            Self::default_quota(max_requests_per_second)?,
301        )])
302    }
303
304    fn rate_limit_keys(endpoint: &str) -> Vec<String> {
305        let normalized = endpoint.split('?').next().unwrap_or(endpoint);
306        let route = format!("kraken:futures:{normalized}");
307        vec![KRAKEN_GLOBAL_RATE_KEY.to_string(), route]
308    }
309
310    async fn send_request<T: DeserializeOwned>(
311        &self,
312        method: Method,
313        endpoint: &str,
314        url: String,
315        authenticate: bool,
316    ) -> anyhow::Result<T, KrakenHttpError> {
317        // Serialize authenticated requests to ensure nonces arrive at Kraken in order.
318        // Without this, concurrent requests can race through the network and arrive
319        // out-of-order, causing "Invalid nonce" errors.
320        let _guard = if authenticate {
321            Some(self.auth_mutex.lock().await)
322        } else {
323            None
324        };
325
326        let endpoint = endpoint.to_string();
327        let method_clone = method.clone();
328        let url_clone = url.clone();
329        let credential = self.credential.clone();
330
331        let operation = || {
332            let url = url_clone.clone();
333            let method = method_clone.clone();
334            let endpoint = endpoint.clone();
335            let credential = credential.clone();
336
337            async move {
338                let mut headers = Self::default_headers();
339
340                if authenticate {
341                    let cred = credential.as_ref().ok_or_else(|| {
342                        KrakenHttpError::AuthenticationError(
343                            "Missing credentials for authenticated request".to_string(),
344                        )
345                    })?;
346
347                    let nonce = self.generate_nonce();
348
349                    let signature = cred.sign_futures(&endpoint, "", nonce).map_err(|e| {
350                        KrakenHttpError::AuthenticationError(format!("Failed to sign request: {e}"))
351                    })?;
352
353                    log::debug!(
354                        "Kraken Futures auth: endpoint={endpoint}, nonce={nonce}, base_url={}",
355                        self.base_url.origin()
356                    );
357
358                    headers.insert("APIKey".to_string(), cred.api_key().to_string());
359                    headers.insert("Authent".to_string(), signature);
360                    headers.insert("Nonce".to_string(), nonce.to_string());
361                }
362
363                let rate_limit_keys = Self::rate_limit_keys(&endpoint);
364
365                let response = self
366                    .client
367                    .request(
368                        method,
369                        url,
370                        None,
371                        Some(headers),
372                        None,
373                        None,
374                        Some(rate_limit_keys),
375                    )
376                    .await
377                    .map_err(|e| {
378                        KrakenHttpError::NetworkError(format!(
379                            "Request to {} failed: {e}",
380                            self.base_url.origin()
381                        ))
382                    })?;
383
384                let status = response.status.as_u16();
385                if status >= 400 {
386                    let body = String::from_utf8_lossy(&response.body).to_string();
387                    // Don't retry authentication errors
388                    if status == 401 || status == 403 {
389                        return Err(KrakenHttpError::AuthenticationError(format!(
390                            "HTTP error {status}: {body}"
391                        )));
392                    }
393                    return Err(KrakenHttpError::NetworkError(format!(
394                        "HTTP error {status}: {body}"
395                    )));
396                }
397
398                let response_text = String::from_utf8(response.body.to_vec()).map_err(|e| {
399                    KrakenHttpError::ParseError(format!("Failed to parse response as UTF-8: {e}"))
400                })?;
401
402                serde_json::from_str(&response_text).map_err(|e| {
403                    KrakenHttpError::ParseError(format!(
404                        "Failed to deserialize futures response: {e}"
405                    ))
406                })
407            }
408        };
409
410        let should_retry = kraken_http_should_retry;
411        let create_error = |error: RetryError| KrakenHttpError::NetworkError(error.to_string());
412
413        let cancellation_token = self.cancellation_token();
414
415        self.retry_manager
416            .invocation(&endpoint, operation, should_retry, create_error)
417            .cancellation_token(&cancellation_token)
418            .execute()
419            .await
420    }
421
422    /// Sends authenticated GET request with query parameters included in signature.
423    ///
424    /// For Kraken Futures, GET requests with query params must include them in postData
425    /// for signing: message = postData + nonce + endpoint
426    async fn send_get_with_query<T: DeserializeOwned>(
427        &self,
428        endpoint: &str,
429        url: String,
430        query_string: &str,
431    ) -> anyhow::Result<T, KrakenHttpError> {
432        let response = self
433            .send_get_with_query_raw(endpoint, url, query_string)
434            .await?;
435
436        Self::deserialize_body(&response)
437    }
438
439    /// Sends the authenticated GET of [`Self::send_get_with_query`] and hands back the whole
440    /// response, for an endpoint that answers in its headers as well as its body.
441    async fn send_get_with_query_raw(
442        &self,
443        endpoint: &str,
444        url: String,
445        query_string: &str,
446    ) -> anyhow::Result<HttpResponse, KrakenHttpError> {
447        let _guard = self.auth_mutex.lock().await;
448        let cancellation_token = self.cancellation_token();
449
450        if cancellation_token.is_cancelled() {
451            return Err(KrakenHttpError::NetworkError(
452                "Request cancelled".to_string(),
453            ));
454        }
455
456        let credential = self.credential.as_ref().ok_or_else(|| {
457            KrakenHttpError::AuthenticationError("Missing credentials".to_string())
458        })?;
459
460        let nonce = self.generate_nonce();
461
462        // Query params go in postData for signing (not in endpoint)
463        let signature = credential
464            .sign_futures(endpoint, query_string, nonce)
465            .map_err(|e| {
466                KrakenHttpError::AuthenticationError(format!("Failed to sign request: {e}"))
467            })?;
468
469        log::debug!(
470            "Kraken Futures GET with query: endpoint={endpoint}, query={query_string}, nonce={nonce}"
471        );
472
473        let mut headers = Self::default_headers();
474        headers.insert("APIKey".to_string(), credential.api_key().to_string());
475        headers.insert("Authent".to_string(), signature);
476        headers.insert("Nonce".to_string(), nonce.to_string());
477
478        let rate_limit_keys = Self::rate_limit_keys(endpoint);
479
480        let response = self
481            .client
482            .request(
483                Method::GET,
484                url,
485                None,
486                Some(headers),
487                None,
488                None,
489                Some(rate_limit_keys),
490            )
491            .await
492            .map_err(|e| {
493                KrakenHttpError::NetworkError(format!(
494                    "Request to {} failed: {e}",
495                    self.base_url.origin()
496                ))
497            })?;
498
499        let status = response.status.as_u16();
500        if status >= 400 {
501            let body = String::from_utf8_lossy(&response.body).to_string();
502
503            if status == 401 || status == 403 {
504                return Err(KrakenHttpError::AuthenticationError(format!(
505                    "HTTP error {status}: {body}"
506                )));
507            }
508            return Err(KrakenHttpError::NetworkError(format!(
509                "HTTP error {status}: {body}"
510            )));
511        }
512
513        Ok(response)
514    }
515
516    fn deserialize_body<T: DeserializeOwned>(
517        response: &HttpResponse,
518    ) -> anyhow::Result<T, KrakenHttpError> {
519        let response_text = std::str::from_utf8(&response.body).map_err(|e| {
520            KrakenHttpError::ParseError(format!("Failed to parse response as UTF-8: {e}"))
521        })?;
522
523        serde_json::from_str(response_text).map_err(|e| {
524            KrakenHttpError::ParseError(format!("Failed to deserialize futures response: {e}"))
525        })
526    }
527
528    async fn send_request_with_body<T: DeserializeOwned>(
529        &self,
530        endpoint: &str,
531        params: HashMap<String, String>,
532    ) -> anyhow::Result<T, KrakenHttpError> {
533        let post_data = serde_urlencoded::to_string(&params).map_err(|e| {
534            KrakenHttpError::RequestNotStarted(format!("Failed to encode params: {e}"))
535        })?;
536        self.send_authenticated_post(endpoint, post_data).await
537    }
538
539    /// Sends a request with typed parameters (serializable struct).
540    async fn send_request_with_params<P: serde::Serialize, T: DeserializeOwned>(
541        &self,
542        endpoint: &str,
543        params: &P,
544    ) -> anyhow::Result<T, KrakenHttpError> {
545        let post_data = serde_urlencoded::to_string(params).map_err(|e| {
546            KrakenHttpError::RequestNotStarted(format!("Failed to encode params: {e}"))
547        })?;
548        self.send_authenticated_post(endpoint, post_data).await
549    }
550
551    /// Core authenticated POST request - takes raw post_data string.
552    async fn send_authenticated_post<T: DeserializeOwned>(
553        &self,
554        endpoint: &str,
555        post_data: String,
556    ) -> anyhow::Result<T, KrakenHttpError> {
557        let cancellation_token = self.cancellation_token();
558        if cancellation_token.is_cancelled() {
559            return Err(KrakenHttpError::RequestNotStarted(
560                "Request cancelled".to_string(),
561            ));
562        }
563
564        // Serialize authenticated requests to ensure nonces arrive at Kraken in order
565        let _guard = tokio::select! {
566            biased;
567            () = cancellation_token.cancelled() => {
568                return Err(KrakenHttpError::RequestNotStarted(
569                    "Request cancelled".to_string(),
570                ));
571            }
572            guard = self.auth_mutex.lock() => guard,
573        };
574
575        let credential = self
576            .credential
577            .as_ref()
578            .ok_or(KrakenHttpError::MissingCredentials)?;
579
580        let nonce = self.generate_nonce();
581        log::debug!("Generated nonce {nonce} for {endpoint}");
582
583        let signature = credential
584            .sign_futures(endpoint, &post_data, nonce)
585            .map_err(|e| {
586                KrakenHttpError::RequestNotStarted(format!("Failed to sign request: {e}"))
587            })?;
588
589        let url = format!("{}{endpoint}", self.base_url.expose());
590        let mut headers = Self::default_headers();
591        headers.insert(
592            "Content-Type".to_string(),
593            "application/x-www-form-urlencoded".to_string(),
594        );
595        headers.insert("APIKey".to_string(), credential.api_key().to_string());
596        headers.insert("Authent".to_string(), signature);
597        headers.insert("Nonce".to_string(), nonce.to_string());
598
599        let rate_limit_keys = Self::rate_limit_keys(endpoint);
600
601        let response = self
602            .send_order_request(
603                url,
604                headers,
605                post_data.into_bytes(),
606                rate_limit_keys,
607                &cancellation_token,
608            )
609            .await?;
610
611        if response.status.as_u16() >= 400 {
612            let status = response.status.as_u16();
613            let body = String::from_utf8_lossy(&response.body).to_string();
614            return Err(KrakenHttpError::NetworkError(format!(
615                "HTTP error {status}: {body}"
616            )));
617        }
618
619        let response_text = String::from_utf8(response.body.to_vec()).map_err(|e| {
620            KrakenHttpError::ParseError(format!("Failed to parse response as UTF-8: {e}"))
621        })?;
622
623        serde_json::from_str(&response_text).map_err(|e| {
624            log::warn!("Failed to parse response from {endpoint}: {response_text}");
625            KrakenHttpError::ParseError(format!("Failed to deserialize response: {e}"))
626        })
627    }
628
629    async fn send_order_request(
630        &self,
631        url: String,
632        headers: HashMap<String, String>,
633        body: Vec<u8>,
634        rate_limit_keys: Vec<String>,
635        cancellation_token: &CancellationToken,
636    ) -> anyhow::Result<HttpResponse, KrakenHttpError> {
637        if cancellation_token.is_cancelled() {
638            return Err(KrakenHttpError::RequestNotStarted(
639                "Request cancelled".to_string(),
640            ));
641        }
642
643        let request_started = AtomicBool::new(false);
644        let request = async {
645            request_started.store(true, Ordering::Relaxed);
646            self.client
647                .request(
648                    Method::POST,
649                    url,
650                    None,
651                    Some(headers),
652                    Some(body),
653                    None,
654                    Some(rate_limit_keys),
655                )
656                .await
657        };
658        tokio::pin!(request);
659
660        tokio::select! {
661            biased;
662            () = cancellation_token.cancelled() => {
663                if request_started.load(Ordering::Relaxed) {
664                    Err(KrakenHttpError::NetworkError(
665                        "Request cancelled after transport invocation".to_string(),
666                    ))
667                } else {
668                    Err(KrakenHttpError::RequestNotStarted(
669                        "Request cancelled".to_string(),
670                    ))
671                }
672            }
673            response = &mut request => response
674                .map_err(|e| KrakenHttpError::NetworkError(
675                    format!("Request to {} failed: {e}", self.base_url.origin())
676                )),
677        }
678    }
679
680    /// Requests tradable instruments from Kraken Futures.
681    pub async fn get_instruments(
682        &self,
683    ) -> anyhow::Result<FuturesInstrumentsResponse, KrakenHttpError> {
684        let endpoint = "/derivatives/api/v3/instruments";
685        let url = format!("{}{endpoint}", self.base_url.expose());
686
687        self.send_request(Method::GET, endpoint, url, false).await
688    }
689
690    /// Requests ticker information for all futures instruments.
691    pub async fn get_tickers(&self) -> anyhow::Result<FuturesTickersResponse, KrakenHttpError> {
692        let endpoint = "/derivatives/api/v3/tickers";
693        let url = format!("{}{endpoint}", self.base_url.expose());
694
695        self.send_request(Method::GET, endpoint, url, false).await
696    }
697
698    /// Requests order book depth for a futures symbol.
699    pub async fn get_orderbook(
700        &self,
701        symbol: &str,
702    ) -> anyhow::Result<FuturesOrderBookResponse, KrakenHttpError> {
703        let endpoint = format!("/derivatives/api/v3/orderbook?symbol={symbol}");
704        let url = format!("{}{endpoint}", self.base_url.expose());
705
706        self.send_request(Method::GET, &endpoint, url, false).await
707    }
708
709    /// Requests historical funding rates for a futures symbol.
710    pub async fn get_historical_funding_rates(
711        &self,
712        symbol: &str,
713    ) -> anyhow::Result<FuturesHistoricalFundingRatesResponse, KrakenHttpError> {
714        let endpoint = format!("/derivatives/api/v4/historicalfundingrates?symbol={symbol}");
715        let url = format!("{}{endpoint}", self.base_url.expose());
716
717        self.send_request(Method::GET, &endpoint, url, false).await
718    }
719
720    /// Requests OHLC candlestick data for a futures symbol.
721    pub async fn get_ohlc(
722        &self,
723        tick_type: &str,
724        symbol: &str,
725        resolution: &str,
726        from: Option<i64>,
727        to: Option<i64>,
728    ) -> anyhow::Result<FuturesCandlesResponse, KrakenHttpError> {
729        let endpoint = format!("/api/charts/v1/{tick_type}/{symbol}/{resolution}");
730
731        let mut url = format!("{}{endpoint}", self.base_url.expose());
732
733        let mut query_params = Vec::new();
734
735        if let Some(from_ts) = from {
736            query_params.push(format!("from={from_ts}"));
737        }
738
739        if let Some(to_ts) = to {
740            query_params.push(format!("to={to_ts}"));
741        }
742
743        if !query_params.is_empty() {
744            url.push('?');
745            url.push_str(&query_params.join("&"));
746        }
747
748        self.send_request(Method::GET, &endpoint, url, false).await
749    }
750
751    /// Gets public execution events (trades) for a futures symbol.
752    pub async fn get_public_executions(
753        &self,
754        symbol: &str,
755        since: Option<i64>,
756        before: Option<i64>,
757        sort: Option<&str>,
758        continuation_token: Option<&str>,
759    ) -> anyhow::Result<FuturesPublicExecutionsResponse, KrakenHttpError> {
760        let endpoint = format!("/api/history/v3/market/{symbol}/executions");
761
762        let mut url = format!("{}{endpoint}", self.base_url.expose());
763
764        let mut query_params = Vec::new();
765
766        if let Some(since_ts) = since {
767            query_params.push(format!("since={since_ts}"));
768        }
769
770        if let Some(before_ts) = before {
771            query_params.push(format!("before={before_ts}"));
772        }
773
774        if let Some(sort_order) = sort {
775            query_params.push(format!("sort={sort_order}"));
776        }
777
778        if let Some(token) = continuation_token {
779            query_params.push(format!("continuationToken={token}"));
780        }
781
782        if !query_params.is_empty() {
783            url.push('?');
784            url.push_str(&query_params.join("&"));
785        }
786
787        self.send_request(Method::GET, &endpoint, url, false).await
788    }
789
790    /// Requests all open orders (requires authentication).
791    pub async fn get_open_orders(
792        &self,
793    ) -> anyhow::Result<FuturesOpenOrdersResponse, KrakenHttpError> {
794        if self.credential.is_none() {
795            return Err(KrakenHttpError::AuthenticationError(
796                "API credentials required for futures open orders".to_string(),
797            ));
798        }
799
800        let endpoint = "/derivatives/api/v3/openorders";
801        let url = format!("{}{endpoint}", self.base_url.expose());
802
803        self.send_request(Method::GET, endpoint, url, true).await
804    }
805
806    /// Requests historical order events (requires authentication).
807    pub async fn get_order_events(
808        &self,
809        before: Option<i64>,
810        since: Option<i64>,
811        continuation_token: Option<&str>,
812    ) -> anyhow::Result<FuturesOrderEventsResponse, KrakenHttpError> {
813        if self.credential.is_none() {
814            return Err(KrakenHttpError::AuthenticationError(
815                "API credentials required for futures order events".to_string(),
816            ));
817        }
818
819        let endpoint = "/api/history/v3/orders";
820        let mut query_params = Vec::new();
821
822        if let Some(before_ts) = before {
823            query_params.push(format!("before={before_ts}"));
824        }
825
826        if let Some(since_ts) = since {
827            query_params.push(format!("since={since_ts}"));
828        }
829
830        if let Some(token) = continuation_token {
831            query_params.push(format!("continuation_token={token}"));
832        }
833
834        // A page that hands back a continuation token must hold the newest events, which the
835        // single-order lookup relies on to tell how far back the page reaches, so the order is
836        // pinned rather than left to the venue default
837        query_params.push("sort=desc".to_string());
838        query_params.push(format!("count={ORDER_HISTORY_PAGE_SIZE}"));
839
840        // Build URL with query params
841        let query_string = query_params.join("&");
842
843        let url = if query_string.is_empty() {
844            format!("{}{endpoint}", self.base_url.expose())
845        } else {
846            format!("{}{endpoint}?{query_string}", self.base_url.expose())
847        };
848
849        // For signing: query params go in postData, not endpoint
850        // Kraken: message = postData + nonce + endpoint
851        let response = self
852            .send_get_with_query_raw(endpoint, url, &query_string)
853            .await?;
854        let page: FuturesOrderHistoryResponse = Self::deserialize_body(&response)?;
855        let mut events = page.into_order_events()?;
856
857        // Kraken documents the token in the response header and shows it in the body, so a page
858        // that carries it in the header alone must not read as the last one.
859        if events
860            .continuation_token
861            .as_deref()
862            .is_none_or(str::is_empty)
863        {
864            events.continuation_token = response
865                .headers
866                .get(NEXT_CONTINUATION_TOKEN_HEADER)
867                .filter(|token| !token.is_empty())
868                .cloned();
869        }
870
871        Ok(events)
872    }
873
874    /// Requests the status of specific orders (requires authentication).
875    ///
876    /// The venue reports orders which are open or were filled/cancelled in
877    /// the last 5 seconds, which covers the Maker Protection race where an
878    /// order is absent from `/openorders` because its terminal transition is
879    /// younger than the open-orders snapshot.
880    pub async fn get_orders_status(
881        &self,
882        order_ids: &[String],
883        cli_ord_ids: &[String],
884    ) -> anyhow::Result<FuturesOrdersStatusResponse, KrakenHttpError> {
885        if self.credential.is_none() {
886            return Err(KrakenHttpError::AuthenticationError(
887                "API credentials required for futures orders status".to_string(),
888            ));
889        }
890
891        let pairs: Vec<(&str, &str)> = order_ids
892            .iter()
893            .map(|order_id| ("orderIds", order_id.as_str()))
894            .chain(
895                cli_ord_ids
896                    .iter()
897                    .map(|cli_ord_id| ("cliOrdIds", cli_ord_id.as_str())),
898            )
899            .collect();
900
901        let post_data = serde_urlencoded::to_string(&pairs).map_err(|e| {
902            KrakenHttpError::RequestNotStarted(format!("Failed to encode params: {e}"))
903        })?;
904
905        let endpoint = "/derivatives/api/v3/orders/status";
906        self.send_authenticated_post(endpoint, post_data).await
907    }
908
909    /// Requests fill/trade history (requires authentication).
910    pub async fn get_fills(
911        &self,
912        last_fill_time: Option<&str>,
913    ) -> anyhow::Result<FuturesFillsResponse, KrakenHttpError> {
914        if self.credential.is_none() {
915            return Err(KrakenHttpError::AuthenticationError(
916                "API credentials required for futures fills".to_string(),
917            ));
918        }
919
920        let endpoint = "/derivatives/api/v3/fills";
921        let query_string = last_fill_time
922            .map(|t| format!("lastFillTime={t}"))
923            .unwrap_or_default();
924
925        let url = if query_string.is_empty() {
926            format!("{}{endpoint}", self.base_url.expose())
927        } else {
928            format!("{}{endpoint}?{query_string}", self.base_url.expose())
929        };
930
931        // Query params go in postData for signing
932        self.send_get_with_query(endpoint, url, &query_string).await
933    }
934
935    /// Requests open positions (requires authentication).
936    pub async fn get_open_positions(
937        &self,
938    ) -> anyhow::Result<FuturesOpenPositionsResponse, KrakenHttpError> {
939        if self.credential.is_none() {
940            return Err(KrakenHttpError::AuthenticationError(
941                "API credentials required for futures open positions".to_string(),
942            ));
943        }
944
945        let endpoint = "/derivatives/api/v3/openpositions";
946        let url = format!("{}{endpoint}", self.base_url.expose());
947
948        self.send_request(Method::GET, endpoint, url, true).await
949    }
950
951    /// Requests all accounts (cash and margin) with balances and margin info.
952    pub async fn get_accounts(&self) -> anyhow::Result<FuturesAccountsResponse, KrakenHttpError> {
953        if self.credential.is_none() {
954            return Err(KrakenHttpError::AuthenticationError(
955                "API credentials required for futures accounts".to_string(),
956            ));
957        }
958
959        let endpoint = "/derivatives/api/v3/accounts";
960        let url = format!("{}{endpoint}", self.base_url.expose());
961
962        self.send_request(Method::GET, endpoint, url, true).await
963    }
964
965    /// Submits a new order (requires authentication).
966    pub async fn send_order(
967        &self,
968        params: HashMap<String, String>,
969    ) -> anyhow::Result<FuturesSendOrderResponse, KrakenHttpError> {
970        if self.credential.is_none() {
971            return Err(KrakenHttpError::AuthenticationError(
972                "API credentials required for sending orders".to_string(),
973            ));
974        }
975
976        let endpoint = "/derivatives/api/v3/sendorder";
977        self.send_request_with_body(endpoint, params).await
978    }
979
980    /// Submits a new order using typed parameters (requires authentication).
981    pub async fn send_order_params(
982        &self,
983        params: &KrakenFuturesSendOrderParams,
984    ) -> anyhow::Result<FuturesSendOrderResponse, KrakenHttpError> {
985        if self.credential.is_none() {
986            return Err(KrakenHttpError::MissingCredentials);
987        }
988
989        let endpoint = "/derivatives/api/v3/sendorder";
990        self.send_request_with_params(endpoint, params).await
991    }
992
993    /// Cancels an open order (requires authentication).
994    pub async fn cancel_order(
995        &self,
996        order_id: Option<String>,
997        cli_ord_id: Option<String>,
998    ) -> anyhow::Result<FuturesCancelOrderResponse, KrakenHttpError> {
999        if self.credential.is_none() {
1000            return Err(KrakenHttpError::MissingCredentials);
1001        }
1002
1003        let mut params = HashMap::new();
1004
1005        if let Some(id) = order_id {
1006            params.insert("order_id".to_string(), id);
1007        }
1008
1009        if let Some(id) = cli_ord_id {
1010            params.insert("cliOrdId".to_string(), id);
1011        }
1012
1013        let endpoint = "/derivatives/api/v3/cancelorder";
1014        self.send_request_with_body(endpoint, params).await
1015    }
1016
1017    /// Edits an existing order (requires authentication).
1018    pub async fn edit_order(
1019        &self,
1020        params: &KrakenFuturesEditOrderParams,
1021    ) -> anyhow::Result<FuturesEditOrderResponse, KrakenHttpError> {
1022        if self.credential.is_none() {
1023            return Err(KrakenHttpError::MissingCredentials);
1024        }
1025
1026        let endpoint = "/derivatives/api/v3/editorder";
1027        self.send_request_with_params(endpoint, params).await
1028    }
1029
1030    /// Submits multiple orders in a single batch request (requires authentication).
1031    pub async fn batch_order(
1032        &self,
1033        params: HashMap<String, String>,
1034    ) -> anyhow::Result<FuturesBatchOrderResponse, KrakenHttpError> {
1035        if self.credential.is_none() {
1036            return Err(KrakenHttpError::AuthenticationError(
1037                "API credentials required for batch orders".to_string(),
1038            ));
1039        }
1040
1041        let endpoint = "/derivatives/api/v3/batchorder";
1042        self.send_request_with_body(endpoint, params).await
1043    }
1044
1045    /// Cancels multiple orders in a single batch request (requires authentication).
1046    pub async fn cancel_orders_batch(
1047        &self,
1048        order_ids: Vec<String>,
1049    ) -> anyhow::Result<FuturesBatchCancelResponse, KrakenHttpError> {
1050        let batch_items: Vec<KrakenFuturesBatchCancelItem> = order_ids
1051            .into_iter()
1052            .map(KrakenFuturesBatchCancelItem::from_order_id)
1053            .collect();
1054
1055        self.cancel_order_items_batch(batch_items).await
1056    }
1057
1058    /// Cancels multiple order IDs or client order IDs in a single batch request
1059    /// (requires authentication).
1060    pub async fn cancel_order_items_batch(
1061        &self,
1062        batch_items: Vec<KrakenFuturesBatchCancelItem>,
1063    ) -> anyhow::Result<FuturesBatchCancelResponse, KrakenHttpError> {
1064        if self.credential.is_none() {
1065            return Err(KrakenHttpError::MissingCredentials);
1066        }
1067
1068        let params = KrakenFuturesBatchOrderParams::new(batch_items);
1069        let post_data = params
1070            .to_body()
1071            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to serialize batch: {e}")))?;
1072
1073        let endpoint = "/derivatives/api/v3/batchorder";
1074        self.send_authenticated_post(endpoint, post_data).await
1075    }
1076
1077    /// Submits multiple orders in a single batch request (requires authentication).
1078    pub async fn submit_orders_batch(
1079        &self,
1080        items: Vec<KrakenFuturesBatchSendItem>,
1081    ) -> anyhow::Result<FuturesBatchOrderResponse, KrakenHttpError> {
1082        if self.credential.is_none() {
1083            return Err(KrakenHttpError::MissingCredentials);
1084        }
1085
1086        let params = KrakenFuturesBatchOrderParams::new(items);
1087        let post_data = params.to_body().map_err(|e| {
1088            KrakenHttpError::RequestNotStarted(format!("Failed to serialize batch: {e}"))
1089        })?;
1090
1091        let endpoint = "/derivatives/api/v3/batchorder";
1092        self.send_authenticated_post(endpoint, post_data).await
1093    }
1094
1095    /// Edits multiple orders in a single batch request (requires authentication).
1096    pub async fn edit_orders_batch(
1097        &self,
1098        items: Vec<KrakenFuturesBatchEditItem>,
1099    ) -> anyhow::Result<FuturesBatchOrderResponse, KrakenHttpError> {
1100        if self.credential.is_none() {
1101            return Err(KrakenHttpError::AuthenticationError(
1102                "API credentials required for batch orders".to_string(),
1103            ));
1104        }
1105
1106        let params = KrakenFuturesBatchOrderParams::new(items);
1107        let post_data = params
1108            .to_body()
1109            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to serialize batch: {e}")))?;
1110
1111        let endpoint = "/derivatives/api/v3/batchorder";
1112        self.send_authenticated_post(endpoint, post_data).await
1113    }
1114
1115    /// Cancels all open orders, optionally filtered by symbol (requires authentication).
1116    pub async fn cancel_all_orders(
1117        &self,
1118        symbol: Option<String>,
1119    ) -> anyhow::Result<FuturesCancelAllOrdersResponse, KrakenHttpError> {
1120        if self.credential.is_none() {
1121            return Err(KrakenHttpError::MissingCredentials);
1122        }
1123
1124        let mut params = HashMap::new();
1125
1126        if let Some(sym) = symbol {
1127            params.insert("symbol".to_string(), sym);
1128        }
1129
1130        let endpoint = "/derivatives/api/v3/cancelallorders";
1131        self.send_request_with_body(endpoint, params).await
1132    }
1133}
1134
1135pub(crate) type FuturesBatchOrder = (
1136    InstrumentId,
1137    ClientOrderId,
1138    OrderSide,
1139    OrderType,
1140    Quantity,
1141    TimeInForce,
1142    Option<Price>,
1143    Option<Price>,
1144    Option<TriggerType>,
1145    bool,
1146    bool,
1147);
1148
1149pub(crate) struct FuturesBatchSubmitItem {
1150    pub result: KrakenApiResult,
1151    pub status: FuturesSendStatus,
1152}
1153
1154/// High-level HTTP client for the Kraken Futures REST API.
1155///
1156/// This client wraps the raw client and provides Nautilus domain types.
1157/// It maintains an instrument cache and uses it to parse venue responses
1158/// into Nautilus domain objects.
1159#[cfg_attr(
1160    feature = "python",
1161    pyo3::pyclass(module = "nautilus_trader.adapters.kraken", from_py_object)
1162)]
1163#[cfg_attr(
1164    feature = "python",
1165    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.kraken")
1166)]
1167pub struct KrakenFuturesHttpClient {
1168    pub(crate) inner: Arc<KrakenFuturesRawHttpClient>,
1169    pub(crate) instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
1170    clock: &'static AtomicTime,
1171    cache_initialized: Arc<AtomicBool>,
1172}
1173
1174impl Clone for KrakenFuturesHttpClient {
1175    fn clone(&self) -> Self {
1176        Self {
1177            inner: self.inner.clone(),
1178            instruments_cache: self.instruments_cache.clone(),
1179            cache_initialized: self.cache_initialized.clone(),
1180            clock: self.clock,
1181        }
1182    }
1183}
1184
1185impl Default for KrakenFuturesHttpClient {
1186    fn default() -> Self {
1187        Self::new(
1188            KrakenEnvironment::Live,
1189            None,
1190            60,
1191            None,
1192            None,
1193            None,
1194            None,
1195            KRAKEN_FUTURES_DEFAULT_RATE_LIMIT_PER_SECOND,
1196        )
1197        .expect("Failed to create default KrakenFuturesHttpClient")
1198    }
1199}
1200
1201impl Debug for KrakenFuturesHttpClient {
1202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1203        f.debug_struct(stringify!(KrakenFuturesHttpClient))
1204            .field("inner", &self.inner)
1205            .finish()
1206    }
1207}
1208
1209impl KrakenFuturesHttpClient {
1210    /// Creates a new [`KrakenFuturesHttpClient`].
1211    #[expect(clippy::too_many_arguments)]
1212    pub fn new(
1213        environment: KrakenEnvironment,
1214        base_url_override: Option<String>,
1215        timeout_secs: u64,
1216        max_retries: Option<u32>,
1217        retry_delay_ms: Option<u64>,
1218        retry_delay_max_ms: Option<u64>,
1219        proxy_url: Option<String>,
1220        max_requests_per_second: u32,
1221    ) -> anyhow::Result<Self> {
1222        Ok(Self {
1223            inner: Arc::new(KrakenFuturesRawHttpClient::new(
1224                environment,
1225                base_url_override,
1226                timeout_secs,
1227                max_retries,
1228                retry_delay_ms,
1229                retry_delay_max_ms,
1230                proxy_url,
1231                max_requests_per_second,
1232            )?),
1233            instruments_cache: Arc::new(AtomicMap::new()),
1234            cache_initialized: Arc::new(AtomicBool::new(false)),
1235            clock: get_atomic_clock_realtime(),
1236        })
1237    }
1238
1239    /// Creates a new [`KrakenFuturesHttpClient`] with credentials.
1240    #[expect(clippy::too_many_arguments)]
1241    pub fn with_credentials(
1242        api_key: String,
1243        api_secret: String,
1244        environment: KrakenEnvironment,
1245        base_url_override: Option<String>,
1246        timeout_secs: u64,
1247        max_retries: Option<u32>,
1248        retry_delay_ms: Option<u64>,
1249        retry_delay_max_ms: Option<u64>,
1250        proxy_url: Option<String>,
1251        max_requests_per_second: u32,
1252    ) -> anyhow::Result<Self> {
1253        Ok(Self {
1254            inner: Arc::new(KrakenFuturesRawHttpClient::with_credentials(
1255                api_key,
1256                api_secret,
1257                environment,
1258                base_url_override,
1259                timeout_secs,
1260                max_retries,
1261                retry_delay_ms,
1262                retry_delay_max_ms,
1263                proxy_url,
1264                max_requests_per_second,
1265            )?),
1266            instruments_cache: Arc::new(AtomicMap::new()),
1267            cache_initialized: Arc::new(AtomicBool::new(false)),
1268            clock: get_atomic_clock_realtime(),
1269        })
1270    }
1271
1272    /// Creates a new [`KrakenFuturesHttpClient`] loading credentials from environment variables.
1273    ///
1274    /// Looks for `KRAKEN_FUTURES_API_KEY` and `KRAKEN_FUTURES_API_SECRET` (live)
1275    /// or `KRAKEN_FUTURES_DEMO_API_KEY` and `KRAKEN_FUTURES_DEMO_API_SECRET` (demo).
1276    ///
1277    /// Falls back to unauthenticated client if credentials are not set.
1278    #[expect(clippy::too_many_arguments)]
1279    pub fn from_env(
1280        environment: KrakenEnvironment,
1281        base_url_override: Option<String>,
1282        timeout_secs: u64,
1283        max_retries: Option<u32>,
1284        retry_delay_ms: Option<u64>,
1285        retry_delay_max_ms: Option<u64>,
1286        proxy_url: Option<String>,
1287        max_requests_per_second: u32,
1288    ) -> anyhow::Result<Self> {
1289        let demo = environment == KrakenEnvironment::Demo;
1290
1291        if let Some(credential) = KrakenCredential::from_env_futures(demo) {
1292            let (api_key, api_secret) = credential.into_parts();
1293            Self::with_credentials(
1294                api_key,
1295                api_secret,
1296                environment,
1297                base_url_override,
1298                timeout_secs,
1299                max_retries,
1300                retry_delay_ms,
1301                retry_delay_max_ms,
1302                proxy_url,
1303                max_requests_per_second,
1304            )
1305        } else {
1306            Self::new(
1307                environment,
1308                base_url_override,
1309                timeout_secs,
1310                max_retries,
1311                retry_delay_ms,
1312                retry_delay_max_ms,
1313                proxy_url,
1314                max_requests_per_second,
1315            )
1316        }
1317    }
1318
1319    /// Cancels all pending HTTP requests.
1320    pub fn cancel_all_requests(&self) {
1321        self.inner.cancel_all_requests();
1322    }
1323
1324    /// Replaces the canceled token so requests can proceed after reconnect.
1325    pub fn reset_cancellation_token(&self) {
1326        self.inner.reset_cancellation_token();
1327    }
1328
1329    /// Returns a clone of the current cancellation token.
1330    pub fn cancellation_token(&self) -> CancellationToken {
1331        self.inner.cancellation_token()
1332    }
1333
1334    /// Caches an instrument for symbol lookup.
1335    pub fn cache_instrument(&self, instrument: InstrumentAny) {
1336        self.instruments_cache
1337            .insert(instrument.symbol().inner(), instrument);
1338        self.cache_initialized.store(true, Ordering::Release);
1339    }
1340
1341    /// Caches multiple instruments for symbol lookup.
1342    pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
1343        self.instruments_cache.rcu(|m| {
1344            for instrument in instruments {
1345                m.insert(instrument.symbol().inner(), instrument.clone());
1346            }
1347        });
1348        self.cache_initialized.store(true, Ordering::Release);
1349    }
1350
1351    /// Gets an instrument from the cache by symbol.
1352    pub fn get_cached_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
1353        self.instruments_cache.get_cloned(symbol)
1354    }
1355
1356    fn get_instrument_by_raw_symbol(&self, raw_symbol: &str) -> Option<InstrumentAny> {
1357        self.instruments_cache
1358            .load()
1359            .values()
1360            .find(|inst| inst.raw_symbol().as_str() == raw_symbol)
1361            .cloned()
1362    }
1363
1364    /// Resolves the contract a history row names, which the venue may spell in another case than
1365    /// the listing (the documented example is `pi_xbtusd`), so the exact spelling is tried first
1366    /// and a case-insensitive match second. A spelling matching two contracts resolves to neither.
1367    fn get_instrument_by_history_tradeable(&self, tradeable: &str) -> Option<InstrumentAny> {
1368        self.get_instrument_by_raw_symbol(tradeable).or_else(|| {
1369            let instruments = self.instruments_cache.load();
1370            let mut matches = instruments
1371                .values()
1372                .filter(|inst| inst.raw_symbol().as_str().eq_ignore_ascii_case(tradeable));
1373            let instrument = matches.next()?;
1374
1375            matches.next().is_none().then(|| instrument.clone())
1376        })
1377    }
1378
1379    fn generate_ts_init(&self) -> UnixNanos {
1380        self.clock.get_time_ns()
1381    }
1382
1383    /// Requests the complete tradable instrument catalog from Kraken Futures.
1384    ///
1385    /// # Errors
1386    ///
1387    /// Returns an error if the underlying request fails or any instrument definition cannot be
1388    /// parsed. An instrument parse failure returns [`KrakenHttpError::ParseError`] without a
1389    /// partial catalog.
1390    pub async fn request_instruments(&self) -> anyhow::Result<Vec<InstrumentAny>, KrakenHttpError> {
1391        let ts_init = self.generate_ts_init();
1392        let response = self.inner.get_instruments().await?;
1393
1394        response
1395            .instruments
1396            .iter()
1397            .map(|fut_instrument| {
1398                parse_futures_instrument(fut_instrument, ts_init, ts_init)
1399                    .map_err(|e| KrakenHttpError::ParseError(e.to_string()))
1400            })
1401            .collect()
1402    }
1403
1404    /// Requests the current market status for Kraken Futures instruments.
1405    pub async fn request_instrument_statuses(
1406        &self,
1407    ) -> anyhow::Result<AHashMap<InstrumentId, MarketStatusAction>, KrakenHttpError> {
1408        let response = self.inner.get_instruments().await?;
1409
1410        Ok(response
1411            .instruments
1412            .iter()
1413            .map(|instrument| {
1414                let instrument_id =
1415                    InstrumentId::new(Symbol::new(&instrument.symbol), *KRAKEN_VENUE);
1416                let action = if instrument.tradeable {
1417                    MarketStatusAction::Trading
1418                } else {
1419                    MarketStatusAction::NotAvailableForTrading
1420                };
1421
1422                (instrument_id, action)
1423            })
1424            .collect())
1425    }
1426
1427    /// Requests the mark price for an instrument.
1428    pub async fn request_mark_price(
1429        &self,
1430        instrument_id: InstrumentId,
1431    ) -> anyhow::Result<Decimal, KrakenHttpError> {
1432        let instrument = self
1433            .get_cached_instrument(&instrument_id.symbol.inner())
1434            .ok_or_else(|| {
1435                KrakenHttpError::ParseError(
1436                    InstrumentLookupError::not_found(instrument_id).to_string(),
1437                )
1438            })?;
1439
1440        let raw_symbol = instrument.raw_symbol().to_string();
1441        let tickers = self.inner.get_tickers().await?;
1442
1443        tickers
1444            .tickers
1445            .iter()
1446            .find(|t| t.symbol == raw_symbol)
1447            .ok_or_else(|| {
1448                KrakenHttpError::ParseError(format!("Symbol {raw_symbol} not found in tickers"))
1449            })
1450            .and_then(|t| {
1451                t.mark_price.ok_or_else(|| {
1452                    KrakenHttpError::ParseError(format!(
1453                        "Mark price not available for {raw_symbol} (may not be available in testnet)"
1454                    ))
1455                })
1456            })
1457    }
1458
1459    pub async fn request_index_price(
1460        &self,
1461        instrument_id: InstrumentId,
1462    ) -> anyhow::Result<Decimal, KrakenHttpError> {
1463        let instrument = self
1464            .get_cached_instrument(&instrument_id.symbol.inner())
1465            .ok_or_else(|| {
1466                KrakenHttpError::ParseError(
1467                    InstrumentLookupError::not_found(instrument_id).to_string(),
1468                )
1469            })?;
1470
1471        let raw_symbol = instrument.raw_symbol().to_string();
1472        let tickers = self.inner.get_tickers().await?;
1473
1474        tickers
1475            .tickers
1476            .iter()
1477            .find(|t| t.symbol == raw_symbol)
1478            .ok_or_else(|| {
1479                KrakenHttpError::ParseError(format!("Symbol {raw_symbol} not found in tickers"))
1480            })
1481            .and_then(|t| {
1482                t.index_price.ok_or_else(|| {
1483                    KrakenHttpError::ParseError(format!(
1484                        "Index price not available for {raw_symbol} (may not be available in testnet)"
1485                    ))
1486                })
1487            })
1488    }
1489
1490    pub async fn request_trades(
1491        &self,
1492        instrument_id: InstrumentId,
1493        start: Option<Timestamp>,
1494        end: Option<Timestamp>,
1495        limit: Option<u64>,
1496    ) -> anyhow::Result<Vec<TradeTick>, KrakenHttpError> {
1497        let instrument = self
1498            .get_cached_instrument(&instrument_id.symbol.inner())
1499            .ok_or_else(|| {
1500                KrakenHttpError::ParseError(
1501                    InstrumentLookupError::not_found(instrument_id).to_string(),
1502                )
1503            })?;
1504
1505        let raw_symbol = instrument.raw_symbol().to_string();
1506        let ts_init = self.generate_ts_init();
1507
1508        let since = start.map(|dt| dt.as_millisecond());
1509        let before = end.map(|dt| dt.as_millisecond());
1510
1511        // Executions are oldest-anchored for `sort=asc`; count-only fetches the
1512        // newest page with `sort=desc` (reversed to ascending below)
1513        let sort = if start.is_some() { "asc" } else { "desc" };
1514
1515        let response = self
1516            .inner
1517            .get_public_executions(&raw_symbol, since, before, Some(sort), None)
1518            .await?;
1519
1520        let mut trades = Vec::new();
1521
1522        for element in &response.elements {
1523            let execution = &element.event.execution.execution;
1524            match parse_futures_public_execution(execution, &instrument, ts_init) {
1525                Ok(trade_tick) => trades.push(trade_tick),
1526                Err(e) => {
1527                    log::warn!("Failed to parse futures trade tick: {e}");
1528                }
1529            }
1530        }
1531
1532        if start.is_none() {
1533            trades.reverse();
1534        }
1535
1536        apply_count_limit(&mut trades, start, limit);
1537
1538        Ok(trades)
1539    }
1540
1541    pub async fn request_bars(
1542        &self,
1543        bar_type: BarType,
1544        start: Option<Timestamp>,
1545        end: Option<Timestamp>,
1546        limit: Option<u64>,
1547    ) -> anyhow::Result<Vec<Bar>, KrakenHttpError> {
1548        let instrument_id = bar_type.instrument_id();
1549        let instrument = self
1550            .get_cached_instrument(&instrument_id.symbol.inner())
1551            .ok_or_else(|| {
1552                KrakenHttpError::ParseError(
1553                    InstrumentLookupError::not_found(instrument_id).to_string(),
1554                )
1555            })?;
1556
1557        let raw_symbol = instrument.raw_symbol().to_string();
1558        let ts_init = self.generate_ts_init();
1559        let tick_type = "trade";
1560        let resolution = bar_type_to_futures_resolution(bar_type)
1561            .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
1562
1563        // Kraken Futures OHLC API expects Unix timestamp in seconds
1564        let from = start.map(|dt| dt.as_second());
1565        let to = end.map(|dt| dt.as_second());
1566        let end_ns = end.map(|dt| u64::try_from(dt.as_nanosecond()).unwrap_or(0));
1567
1568        let response = self
1569            .inner
1570            .get_ohlc(tick_type, &raw_symbol, resolution, from, to)
1571            .await?;
1572
1573        let mut bars = Vec::new();
1574
1575        for candle in response.candles {
1576            let ohlc = OhlcData {
1577                time: candle.time / 1000,
1578                open: candle.open,
1579                high: candle.high,
1580                low: candle.low,
1581                close: candle.close,
1582                vwap: "0".to_string(),
1583                volume: candle.volume,
1584                count: 0,
1585            };
1586
1587            match parse_bar(&ohlc, &instrument, bar_type, ts_init) {
1588                Ok(bar) => {
1589                    if let Some(end_nanos) = end_ns
1590                        && bar.ts_event.as_u64() > end_nanos
1591                    {
1592                        continue;
1593                    }
1594                    bars.push(bar);
1595                }
1596                Err(e) => {
1597                    log::warn!("Failed to parse futures bar: {e}");
1598                }
1599            }
1600        }
1601
1602        // Kraken returns the page oldest-first; keep the most recent `limit`
1603        // bars for count-only requests rather than the oldest (issue #4254).
1604        apply_count_limit(&mut bars, start, limit);
1605
1606        Ok(bars)
1607    }
1608
1609    /// Requests an order book snapshot for a futures instrument.
1610    pub async fn request_book_snapshot(
1611        &self,
1612        instrument_id: InstrumentId,
1613        depth: Option<u32>,
1614    ) -> anyhow::Result<OrderBook, KrakenHttpError> {
1615        let instrument = self
1616            .get_cached_instrument(&instrument_id.symbol.inner())
1617            .ok_or_else(|| {
1618                KrakenHttpError::ParseError(
1619                    InstrumentLookupError::not_found(instrument_id).to_string(),
1620                )
1621            })?;
1622
1623        let raw_symbol = instrument.raw_symbol().to_string();
1624        let price_precision = instrument.price_precision();
1625        let size_precision = instrument.size_precision();
1626        let ts_event = self.generate_ts_init();
1627
1628        let response = self.inner.get_orderbook(&raw_symbol).await?;
1629        let book_data = &response.order_book;
1630
1631        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
1632
1633        let bid_limit = depth.map_or(book_data.bids.len(), |d| {
1634            (d as usize).min(book_data.bids.len())
1635        });
1636        let ask_limit = depth.map_or(book_data.asks.len(), |d| {
1637            (d as usize).min(book_data.asks.len())
1638        });
1639
1640        // Pass sequence=0 so the snapshot does not advance the book's high-water sequence,
1641        // the WS subscription owns sequencing once it starts streaming deltas.
1642        for (i, level) in book_data.bids.iter().take(bid_limit).enumerate() {
1643            let price = Price::from_decimal_dp(level.price, price_precision)
1644                .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
1645            let size = Quantity::from_decimal_dp(level.qty, size_precision)
1646                .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
1647            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
1648            book.add(order, 0, 0, ts_event);
1649        }
1650
1651        for (i, level) in book_data.asks.iter().take(ask_limit).enumerate() {
1652            let price = Price::from_decimal_dp(level.price, price_precision)
1653                .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
1654            let size = Quantity::from_decimal_dp(level.qty, size_precision)
1655                .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
1656            let order = BookOrder::new(OrderSide::Sell, price, size, (bid_limit + i) as u64);
1657            book.add(order, 0, 0, ts_event);
1658        }
1659
1660        Ok(book)
1661    }
1662
1663    /// Requests historical funding rates for a futures instrument.
1664    ///
1665    /// Kraken returns all available rates; client-side filtering applies
1666    /// the `start`, `end`, and `limit` constraints from the caller.
1667    pub async fn request_funding_rates(
1668        &self,
1669        instrument_id: InstrumentId,
1670        start: Option<Timestamp>,
1671        end: Option<Timestamp>,
1672        limit: Option<usize>,
1673    ) -> anyhow::Result<Vec<FundingRateUpdate>, KrakenHttpError> {
1674        let instrument = self
1675            .get_cached_instrument(&instrument_id.symbol.inner())
1676            .ok_or_else(|| {
1677                KrakenHttpError::ParseError(
1678                    InstrumentLookupError::not_found(instrument_id).to_string(),
1679                )
1680            })?;
1681
1682        let raw_symbol = instrument.raw_symbol().to_string();
1683        let ts_init = self.generate_ts_init();
1684        let start_ns = start.map(|dt| u64::try_from(dt.as_nanosecond()).unwrap_or(0));
1685        let end_ns = end.map(|dt| u64::try_from(dt.as_nanosecond()).unwrap_or(0));
1686
1687        let response = self.inner.get_historical_funding_rates(&raw_symbol).await?;
1688
1689        let mut rates = Vec::new();
1690
1691        for entry in &response.rates {
1692            let ts_event = entry.timestamp.parse::<Timestamp>().map_or(ts_init, |dt| {
1693                UnixNanos::from(u64::try_from(dt.as_nanosecond()).unwrap_or(0))
1694            });
1695
1696            if let Some(s) = start_ns
1697                && ts_event.as_u64() < s
1698            {
1699                continue;
1700            }
1701
1702            if let Some(e) = end_ns
1703                && ts_event.as_u64() > e
1704            {
1705                continue;
1706            }
1707
1708            rates.push(FundingRateUpdate::new(
1709                instrument_id,
1710                entry.relative_funding_rate,
1711                None,
1712                None,
1713                ts_event,
1714                ts_init,
1715            ));
1716
1717            if let Some(lim) = limit
1718                && rates.len() >= lim
1719            {
1720                break;
1721            }
1722        }
1723
1724        // Kraken returns newest-first; reverse to ascending chronological order
1725        rates.reverse();
1726
1727        Ok(rates)
1728    }
1729
1730    /// Requests account state from the Kraken Futures exchange.
1731    ///
1732    /// This queries the accounts endpoint and converts the response into a
1733    /// Nautilus `AccountState` event containing balances and margin info.
1734    ///
1735    /// # Errors
1736    ///
1737    /// Returns an error if:
1738    /// - Credentials are missing.
1739    /// - The request fails.
1740    /// - Response parsing fails.
1741    pub async fn request_account_state(
1742        &self,
1743        account_id: AccountId,
1744    ) -> anyhow::Result<AccountState> {
1745        let accounts_response = self.inner.get_accounts().await?;
1746
1747        if accounts_response.result != KrakenApiResult::Success {
1748            let error_msg = accounts_response
1749                .error
1750                .unwrap_or_else(|| "Unknown error".to_string());
1751            anyhow::bail!("Failed to get futures accounts: {error_msg}");
1752        }
1753
1754        let ts_init = self.generate_ts_init();
1755        let (balances, margins) = parse_account_entries(&accounts_response.accounts);
1756
1757        Ok(AccountState::new(
1758            account_id,
1759            AccountType::Margin,
1760            balances,
1761            margins,
1762            true,
1763            UUID4::new(),
1764            ts_init,
1765            ts_init,
1766            None,
1767        ))
1768    }
1769
1770    pub async fn request_order_status_reports(
1771        &self,
1772        account_id: AccountId,
1773        instrument_id: Option<InstrumentId>,
1774        start: Option<Timestamp>,
1775        end: Option<Timestamp>,
1776        open_only: bool,
1777    ) -> anyhow::Result<Vec<OrderStatusReport>> {
1778        self.request_order_status_reports_checked(account_id, instrument_id, start, end, open_only)
1779            .await
1780            .map(|(reports, _)| reports)
1781    }
1782
1783    /// Requests order status reports, also reporting what the read covered.
1784    ///
1785    /// An in-scope open order whose instrument cannot be resolved, or that cannot be parsed, fails
1786    /// the read, except an untouched reduce-only trigger listed without an unfilled size that no
1787    /// open position sizes, which is skipped, and an order a read scoped to one instrument cannot
1788    /// resolve, which may be on another instrument and is skipped. The coverage records each such
1789    /// skip, each history row in scope that cannot be parsed, resolved or represented, and a
1790    /// continuation token, which cuts the read short at the page's oldest event: the read takes one
1791    /// page, since every Kraken `/history` endpoint draws on one pool of 100 tokens, replenished at
1792    /// 100 every 10 minutes, at a token per page. A read scoped to an unheld futures instrument
1793    /// reads nothing and rules out no order. `ExecutionMassStatus::set_report_window` records
1794    /// whether it is complete for bounded history, and the single-order lookup whether it rules out
1795    /// an order it did not return.
1796    ///
1797    /// A skipped history row is out of scope only when the open-order snapshot reports its order,
1798    /// or when a scoped read finds it names both an order and another contract; a row that
1799    /// establishes neither stays in scope. An undocumented kind is always in scope. A row in scope
1800    /// at least as new as the state an order would be reported from withholds that order, so an
1801    /// unreadable newest row cannot fall back to an older state, whether that state is open or
1802    /// closed. A row that names no order can withhold nothing, and leaves the read incomplete.
1803    pub(crate) async fn request_order_status_reports_checked(
1804        &self,
1805        account_id: AccountId,
1806        instrument_id: Option<InstrumentId>,
1807        start: Option<Timestamp>,
1808        end: Option<Timestamp>,
1809        open_only: bool,
1810    ) -> anyhow::Result<(Vec<OrderStatusReport>, ReportCoverage)> {
1811        let mut coverage = ReportCoverage::default();
1812
1813        // A scoped read for an instrument this client does not hold can match nothing, so
1814        // return before the request rather than reporting every instrument's rows. A spot
1815        // instrument names none of this client's orders, so that read is complete; a futures one
1816        // the listing lacks read nothing, so it rules out none of its orders.
1817        if let Some(ref target_id) = instrument_id
1818            && self
1819                .get_cached_instrument(&target_id.symbol.inner())
1820                .is_none()
1821        {
1822            if product_type_from_symbol(target_id.symbol.as_str()) == KrakenProductType::Futures {
1823                coverage.truncate(None);
1824            }
1825            return Ok((Vec::new(), coverage));
1826        }
1827        let ts_init = self.generate_ts_init();
1828        let mut all_reports = Vec::new();
1829
1830        let response = self
1831            .inner
1832            .get_open_orders()
1833            .await
1834            .map_err(|e| anyhow::anyhow!("get_open_orders failed: {e}"))?;
1835
1836        if response.result != KrakenApiResult::Success {
1837            let error_msg = response
1838                .error
1839                .unwrap_or_else(|| "Unknown error".to_string());
1840            anyhow::bail!("Failed to get open orders: {error_msg}");
1841        }
1842
1843        let position_sizes = if response
1844            .open_orders
1845            .iter()
1846            .any(|order| order.unfilled_size.is_none())
1847        {
1848            match self.inner.get_open_positions().await {
1849                Ok(response) if response.result == KrakenApiResult::Success => Ok(response
1850                    .open_positions
1851                    .into_iter()
1852                    .map(|position| (position.symbol, position.size))
1853                    .collect::<AHashMap<_, _>>()),
1854                Ok(response) => {
1855                    let reason = response
1856                        .error
1857                        .unwrap_or_else(|| "Unknown error".to_string());
1858                    log::warn!("Failed to get open positions for order quantities: {reason}");
1859                    Err(reason)
1860                }
1861                Err(e) => {
1862                    log::warn!("Failed to get open positions for order quantities: {e}");
1863                    Err(e.to_string())
1864                }
1865            }
1866        } else {
1867            Ok(AHashMap::new())
1868        };
1869        let mut skipped_open_order_ids = AHashSet::new();
1870
1871        for order in &response.open_orders {
1872            // Resolve the row and compare instrument ids, so a scoped read cannot match on a
1873            // spelling and cannot fall through to every instrument when the id is not held.
1874            let resolved = self.get_instrument_by_raw_symbol(&order.symbol);
1875            if let Some(ref target_id) = instrument_id {
1876                match &resolved {
1877                    Some(inst) if inst.id() != *target_id => continue,
1878                    // Unresolved, the row may be the scoped instrument's own
1879                    None => {
1880                        coverage.skip(&order.order_id);
1881                        continue;
1882                    }
1883                    Some(_) => {}
1884                }
1885            }
1886
1887            if let Some(instrument) = resolved {
1888                let sized_by_position = order.unfilled_size.is_none()
1889                    && matches!(
1890                        order.order_type,
1891                        KrakenFuturesOrderType::Stop
1892                            | KrakenFuturesOrderType::StopLower
1893                            | KrakenFuturesOrderType::StopLoss
1894                            | KrakenFuturesOrderType::TakeProfit
1895                    )
1896                    && order.status == KrakenFuturesOrderStatus::Untouched
1897                    && order.reduce_only == Some(true);
1898                let position_size = match &position_sizes {
1899                    Ok(sizes) if sized_by_position => sizes.get(&order.symbol).copied(),
1900                    _ => None,
1901                };
1902
1903                // Such a trigger has no size of its own until it fires. With no open position on
1904                // its contract it has none to report, and failing would fail every unscoped
1905                // futures order read while it rests, so it is skipped, its history rows with it;
1906                // a failed positions read leaves its size unknown instead, which fails the read.
1907                if sized_by_position && position_size.is_none() {
1908                    if let Err(reason) = &position_sizes {
1909                        anyhow::bail!(
1910                            "OpenOrders: futures order {} lists no unfilled size and the open \
1911                             positions read failed: {reason}",
1912                            order.order_id
1913                        );
1914                    }
1915                    log::warn!(
1916                        "Skipping futures order {} on {}: the venue lists no unfilled size and no \
1917                         open position sizes it; the set is incomplete",
1918                        order.order_id,
1919                        order.symbol
1920                    );
1921                    coverage.skip(&order.order_id);
1922
1923                    // No history row can carry an invalid ID, and `skip` has marked the set
1924                    // unidentified, so an invalid ID needs no entry here.
1925                    if let Ok(venue_order_id) = VenueOrderId::new_checked(order.order_id.as_str()) {
1926                        skipped_open_order_ids.insert(venue_order_id);
1927                    }
1928                    continue;
1929                }
1930
1931                // An in-scope open order the client cannot parse fails the read: dropped, it reads
1932                // to reconciliation as an order the venue does not have.
1933                let report = parse_futures_order_status_report(
1934                    order,
1935                    &instrument,
1936                    account_id,
1937                    position_size,
1938                    ts_init,
1939                )
1940                .map_err(|e| {
1941                    anyhow::anyhow!(
1942                        "OpenOrders: failed to parse futures order {}: {e}",
1943                        order.order_id
1944                    )
1945                })?;
1946                all_reports.push(report);
1947            } else {
1948                // An in-scope open order the client cannot resolve fails the read, as the spot
1949                // client's does: dropped, it reads to reconciliation as an order the venue never had.
1950                anyhow::bail!(
1951                    "OpenOrders: instrument not in cache for futures symbol {}",
1952                    order.symbol
1953                );
1954            }
1955        }
1956
1957        if !open_only {
1958            // Kraken Futures order events API expects Unix timestamp in milliseconds
1959            let start_ms = start.map(|dt| dt.as_millisecond());
1960            let end_ms = end.map(|dt| dt.as_millisecond());
1961            // Typed, so the mass status can tell a refusal from a fault; the message repeats the
1962            // cause for callers that print only the outermost context.
1963            let response = self
1964                .inner
1965                .get_order_events(end_ms, start_ms, None)
1966                .await
1967                .map_err(|e| {
1968                    let message = format!("get_order_events failed: {e}");
1969                    anyhow::Error::new(e).context(message)
1970                })?;
1971
1972            // A page that hands back a continuation token leaves events of the window unread.
1973            if response
1974                .continuation_token
1975                .as_deref()
1976                .is_some_and(|token| !token.is_empty())
1977            {
1978                log::warn!(
1979                    "Order history window since={start_ms:?} before={end_ms:?} holds more events than one page; the events beyond it are not read, marking the set incomplete"
1980                );
1981                // The page holds the newest events, so it covers every event from its oldest one
1982                // on; a page with no usable event time covers nothing it can place.
1983                coverage.truncate(
1984                    response
1985                        .oldest_event_ms
1986                        .and_then(UnixNanos::from_millis_checked),
1987                );
1988            }
1989
1990            // The history lists every lifecycle event, so an order appears once per event. Each
1991            // report reconciles against the same cached state, so the read hands back one report
1992            // per order: the open-order snapshot when the venue still lists it, else the latest
1993            // history state. An open order the snapshot skips is not reported from its history.
1994            let open_order_ids: AHashSet<VenueOrderId> = all_reports
1995                .iter()
1996                .map(|r| r.venue_order_id)
1997                .chain(skipped_open_order_ids.iter().copied())
1998                .collect();
1999            let mut latest: IndexMap<VenueOrderId, (OrderStatusReport, i64)> = IndexMap::new();
2000            let mut unread_ms: AHashMap<VenueOrderId, i64> = AHashMap::new();
2001            let mut skipped_in_scope = 0usize;
2002
2003            for row in &response.skipped_rows {
2004                let snapshot_covers = row
2005                    .order_id
2006                    .as_deref()
2007                    .is_some_and(|order_id| open_order_ids.contains(&VenueOrderId::new(order_id)));
2008                let on_another_contract = row.order_id.is_some()
2009                    && instrument_id.as_ref().is_some_and(|target_id| {
2010                        row.tradeable
2011                            .as_deref()
2012                            .and_then(|tradeable| {
2013                                self.get_instrument_by_history_tradeable(tradeable)
2014                            })
2015                            .is_some_and(|instrument| instrument.id() != *target_id)
2016                    });
2017
2018                if !row.undocumented && (snapshot_covers || on_another_contract) {
2019                    continue;
2020                }
2021                skipped_in_scope += 1;
2022
2023                if row.undocumented {
2024                    coverage.skip_unidentified();
2025                }
2026
2027                match row.order_id.as_deref() {
2028                    Some(order_id) => {
2029                        record_unread_row(&mut coverage, &mut unread_ms, order_id, row.event_ms);
2030                    }
2031                    None => coverage.skip_unidentified(),
2032                }
2033            }
2034
2035            if skipped_in_scope > 0 {
2036                log::warn!(
2037                    "Order history page had {skipped_in_scope} row(s) in scope the adapter could not represent; marking the set incomplete",
2038                );
2039            }
2040
2041            for event_wrapper in response.order_events {
2042                let event = &event_wrapper.order;
2043
2044                if open_order_ids.contains(&VenueOrderId::new(&event.order_id)) {
2045                    continue;
2046                }
2047
2048                // Resolve the row and compare instrument ids, so a scoped read cannot match on a
2049                // spelling and cannot fall through to every instrument when the id is not held.
2050                let resolved = self.get_instrument_by_history_tradeable(&event.symbol);
2051                if let Some(ref target_id) = instrument_id {
2052                    match &resolved {
2053                        Some(inst) if inst.id() != *target_id => continue,
2054                        // Unresolved, the row may be the scoped instrument's own
2055                        None => {
2056                            record_unread_row(
2057                                &mut coverage,
2058                                &mut unread_ms,
2059                                &event.order_id,
2060                                event_wrapper.event_ms,
2061                            );
2062                            continue;
2063                        }
2064                        Some(_) => {}
2065                    }
2066                }
2067
2068                if let Some(instrument) = resolved {
2069                    match parse_futures_order_event_status_report(
2070                        event,
2071                        Some(event_wrapper.event_type),
2072                        &instrument,
2073                        account_id,
2074                        ts_init,
2075                    ) {
2076                        Ok(report) => match latest.get(&report.venue_order_id) {
2077                            Some((existing, _)) if !supersedes(&report, existing) => {}
2078                            _ => {
2079                                latest.insert(
2080                                    report.venue_order_id,
2081                                    (report, event_wrapper.state_ms),
2082                                );
2083                            }
2084                        },
2085                        Err(e) => {
2086                            let order_id = &event.order_id;
2087                            log::warn!("Failed to parse futures order event {order_id}: {e}");
2088                            record_unread_row(
2089                                &mut coverage,
2090                                &mut unread_ms,
2091                                order_id,
2092                                event_wrapper.event_ms,
2093                            );
2094                        }
2095                    }
2096                } else {
2097                    log::warn!(
2098                        "Instrument not in cache for futures symbol {}, skipping order event",
2099                        event.symbol
2100                    );
2101                    record_unread_row(
2102                        &mut coverage,
2103                        &mut unread_ms,
2104                        &event.order_id,
2105                        event_wrapper.event_ms,
2106                    );
2107                }
2108            }
2109
2110            for (report, state_ms) in latest.into_values() {
2111                if unread_ms
2112                    .get(&report.venue_order_id)
2113                    .is_some_and(|newest_unread_ms| *newest_unread_ms >= state_ms)
2114                {
2115                    log::warn!(
2116                        "Withholding futures order {} from the order read: a history row that could not be read is not older than its latest readable state",
2117                        report.venue_order_id
2118                    );
2119                    coverage.withhold(report);
2120                } else {
2121                    all_reports.push(report);
2122                }
2123            }
2124        }
2125
2126        Ok((all_reports, coverage))
2127    }
2128
2129    /// Requests order status reports from the venue's `/orders/status`
2130    /// 5-second window for the given venue order IDs and client order IDs.
2131    ///
2132    /// Orders the venue no longer reports within that window are simply absent
2133    /// from the result, which callers treat as absence of recent evidence.
2134    ///
2135    /// # Errors
2136    ///
2137    /// Returns an error if the underlying request fails or the venue rejects
2138    /// it.
2139    pub async fn request_orders_status_reports(
2140        &self,
2141        account_id: AccountId,
2142        order_ids: &[String],
2143        cli_ord_ids: &[String],
2144    ) -> anyhow::Result<Vec<OrderStatusReport>> {
2145        let ts_init = self.generate_ts_init();
2146
2147        let response = self
2148            .inner
2149            .get_orders_status(order_ids, cli_ord_ids)
2150            .await
2151            .map_err(|e| anyhow::anyhow!("get_orders_status failed: {e}"))?;
2152
2153        if response.result != KrakenApiResult::Success {
2154            let error_msg = response
2155                .error
2156                .unwrap_or_else(|| "Unknown error".to_string());
2157            anyhow::bail!("Failed to get orders status: {error_msg}");
2158        }
2159
2160        let mut reports = Vec::with_capacity(response.orders.len());
2161        for details in &response.orders {
2162            let Some(instrument) = self.get_instrument_by_raw_symbol(&details.order.symbol) else {
2163                anyhow::bail!(
2164                    "No cached instrument for symbol: {}, order {} cannot be reported; \
2165                     treating the lookup as failed rather than the order as absent",
2166                    details.order.symbol,
2167                    details.order.order_id,
2168                );
2169            };
2170
2171            match parse_futures_order_status_details_report(
2172                details,
2173                &instrument,
2174                account_id,
2175                ts_init,
2176            ) {
2177                Ok(report) => reports.push(report),
2178                Err(e) => anyhow::bail!(
2179                    "Failed to parse futures order status {}: {e}; treating the lookup as \
2180                     failed rather than the order as absent",
2181                    details.order.order_id,
2182                ),
2183            }
2184        }
2185
2186        Ok(reports)
2187    }
2188
2189    pub async fn request_fill_reports(
2190        &self,
2191        account_id: AccountId,
2192        instrument_id: Option<InstrumentId>,
2193        start: Option<Timestamp>,
2194        end: Option<Timestamp>,
2195    ) -> anyhow::Result<Vec<FillReport>> {
2196        self.request_fill_reports_checked(account_id, instrument_id, start, end)
2197            .await
2198            .map(|(reports, _)| reports)
2199    }
2200
2201    /// Requests fill reports, also reporting whether the set is complete.
2202    ///
2203    /// The flag is `false` when an in-scope fill cannot be resolved or parsed, which
2204    /// `ExecutionMassStatus::set_report_window` records for bounded history.
2205    pub(crate) async fn request_fill_reports_checked(
2206        &self,
2207        account_id: AccountId,
2208        instrument_id: Option<InstrumentId>,
2209        start: Option<Timestamp>,
2210        end: Option<Timestamp>,
2211    ) -> anyhow::Result<(Vec<FillReport>, bool)> {
2212        let mut complete = true;
2213        let ts_init = self.generate_ts_init();
2214        let mut all_reports = Vec::new();
2215
2216        // As above: a scoped read for an instrument this client does not hold matches nothing.
2217        if let Some(ref target_id) = instrument_id
2218            && self
2219                .get_cached_instrument(&target_id.symbol.inner())
2220                .is_none()
2221        {
2222            return Ok((all_reports, complete));
2223        }
2224
2225        let response = self.inner.get_fills(None).await?;
2226        if response.result != KrakenApiResult::Success {
2227            let error_msg = response
2228                .error
2229                .unwrap_or_else(|| "Unknown error".to_string());
2230            anyhow::bail!("Failed to get fills: {error_msg}");
2231        }
2232
2233        let start_ms = start.map(|dt| dt.as_millisecond());
2234        let end_ms = end.map(|dt| dt.as_millisecond());
2235
2236        for fill in response.fills {
2237            if let Some(start_threshold) = start_ms
2238                && let Ok(fill_ts) = fill.fill_time.parse::<Timestamp>()
2239            {
2240                let fill_ms = fill_ts.as_millisecond();
2241                if fill_ms < start_threshold {
2242                    continue;
2243                }
2244            }
2245
2246            if let Some(end_threshold) = end_ms
2247                && let Ok(fill_ts) = fill.fill_time.parse::<Timestamp>()
2248            {
2249                let fill_ms = fill_ts.as_millisecond();
2250                if fill_ms > end_threshold {
2251                    continue;
2252                }
2253            }
2254
2255            // Resolve the row and compare instrument ids, so a scoped read cannot match on a
2256            // spelling and cannot fall through to every instrument when the id is not held.
2257            let resolved = self.get_instrument_by_raw_symbol(&fill.symbol);
2258            if let Some(ref target_id) = instrument_id
2259                && resolved.as_ref().is_none_or(|inst| inst.id() != *target_id)
2260            {
2261                continue;
2262            }
2263
2264            if let Some(instrument) = resolved {
2265                match parse_futures_fill_report(&fill, &instrument, account_id, ts_init) {
2266                    Ok(report) => all_reports.push(report),
2267                    Err(e) => {
2268                        let fill_id = &fill.fill_id;
2269                        log::warn!("Failed to parse futures fill {fill_id}: {e}");
2270                        complete = false;
2271                    }
2272                }
2273            } else {
2274                log::warn!(
2275                    "Instrument not in cache for futures symbol {}, skipping fill",
2276                    fill.symbol
2277                );
2278                complete = false;
2279            }
2280        }
2281
2282        Ok((all_reports, complete))
2283    }
2284
2285    pub async fn request_position_status_reports(
2286        &self,
2287        account_id: AccountId,
2288        instrument_id: Option<InstrumentId>,
2289    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2290        let ts_init = self.generate_ts_init();
2291        let mut all_reports = Vec::new();
2292
2293        // As above: a scoped read for an instrument this client does not hold matches nothing.
2294        if let Some(ref target_id) = instrument_id
2295            && self
2296                .get_cached_instrument(&target_id.symbol.inner())
2297                .is_none()
2298        {
2299            return Ok(all_reports);
2300        }
2301
2302        let response = self.inner.get_open_positions().await?;
2303        if response.result != KrakenApiResult::Success {
2304            let error_msg = response
2305                .error
2306                .unwrap_or_else(|| "Unknown error".to_string());
2307            anyhow::bail!("Failed to get open positions: {error_msg}");
2308        }
2309
2310        for position in response.open_positions {
2311            // Resolve the row and compare instrument ids, so a scoped read cannot match on a
2312            // spelling and cannot fall through to every instrument when the id is not held.
2313            let resolved = self.get_instrument_by_raw_symbol(&position.symbol);
2314            if let Some(ref target_id) = instrument_id
2315                && resolved.as_ref().is_none_or(|inst| inst.id() != *target_id)
2316            {
2317                continue;
2318            }
2319
2320            // An in-scope position the client cannot resolve or parse fails the read: dropped,
2321            // it reads to reconciliation as flat.
2322            let Some(instrument) = resolved else {
2323                anyhow::bail!(
2324                    "OpenPositions: instrument not in cache for futures symbol {}",
2325                    position.symbol
2326                );
2327            };
2328
2329            let report =
2330                parse_futures_position_status_report(&position, &instrument, account_id, ts_init)
2331                    .map_err(|e| {
2332                    anyhow::anyhow!(
2333                        "OpenPositions: failed to parse futures position {}: {e}",
2334                        position.symbol
2335                    )
2336                })?;
2337            all_reports.push(report);
2338        }
2339
2340        Ok(all_reports)
2341    }
2342
2343    #[expect(clippy::too_many_arguments)]
2344    fn build_send_order_params(
2345        &self,
2346        instrument_id: InstrumentId,
2347        client_order_id: ClientOrderId,
2348        order_side: OrderSide,
2349        order_type: OrderType,
2350        quantity: Quantity,
2351        time_in_force: TimeInForce,
2352        price: Option<Price>,
2353        trigger_price: Option<Price>,
2354        trigger_type: Option<TriggerType>,
2355        reduce_only: bool,
2356        post_only: bool,
2357    ) -> anyhow::Result<KrakenFuturesSendOrderParams> {
2358        let instrument = self
2359            .get_cached_instrument(&instrument_id.symbol.inner())
2360            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2361
2362        let raw_symbol = instrument.raw_symbol().inner();
2363
2364        // Map order type and time-in-force to Kraken order type
2365        // Kraken Futures encodes TIF in the orderType field:
2366        // - lmt = limit (GTC)
2367        // - ioc = immediate-or-cancel
2368        // - post = post-only (maker only)
2369        // - mkt = market
2370        let kraken_order_type = match order_type {
2371            OrderType::Market => KrakenFuturesOrderType::Market,
2372            OrderType::Limit => {
2373                if post_only {
2374                    KrakenFuturesOrderType::Post
2375                } else {
2376                    match time_in_force {
2377                        TimeInForce::Ioc => KrakenFuturesOrderType::Ioc,
2378                        TimeInForce::Fok => {
2379                            anyhow::bail!("FOK not supported by Kraken Futures, use IOC instead")
2380                        }
2381                        TimeInForce::Gtd => {
2382                            anyhow::bail!("GTD not supported by Kraken Futures, use GTC instead")
2383                        }
2384                        _ => KrakenFuturesOrderType::Limit, // GTC is default
2385                    }
2386                }
2387            }
2388            OrderType::StopMarket | OrderType::StopLimit => KrakenFuturesOrderType::Stop,
2389            OrderType::MarketIfTouched | OrderType::LimitIfTouched => {
2390                KrakenFuturesOrderType::TakeProfit
2391            }
2392            _ => anyhow::bail!("Unsupported order type: {order_type:?}"),
2393        };
2394
2395        let kraken_side = KrakenOrderSide::from(order_side);
2396
2397        let mut builder = KrakenFuturesSendOrderParamsBuilder::default();
2398        builder
2399            .cli_ord_id(client_order_id.to_string())
2400            .broker(NAUTILUS_KRAKEN_BROKER_ID)
2401            .symbol(raw_symbol)
2402            .side(kraken_side)
2403            .size(quantity.to_string())
2404            .order_type(kraken_order_type);
2405
2406        if matches!(
2407            order_type,
2408            OrderType::StopMarket
2409                | OrderType::StopLimit
2410                | OrderType::MarketIfTouched
2411                | OrderType::LimitIfTouched
2412        ) && let Some(signal) = map_futures_trigger_signal(trigger_type)?
2413        {
2414            builder.trigger_signal(signal);
2415        }
2416
2417        match order_type {
2418            OrderType::StopMarket => {
2419                if let Some(trigger) = trigger_price {
2420                    builder.stop_price(trigger.to_string());
2421                }
2422            }
2423            OrderType::StopLimit => {
2424                if let Some(trigger) = trigger_price {
2425                    builder.stop_price(trigger.to_string());
2426                }
2427
2428                if let Some(limit) = price {
2429                    builder.limit_price(limit.to_string());
2430                }
2431            }
2432            OrderType::MarketIfTouched | OrderType::LimitIfTouched => {
2433                if let Some(trigger) = trigger_price {
2434                    builder.stop_price(trigger.to_string());
2435                }
2436
2437                if let Some(limit) = price {
2438                    builder.limit_price(limit.to_string());
2439                }
2440            }
2441            _ => {
2442                if let Some(limit) = price {
2443                    builder.limit_price(limit.to_string());
2444                }
2445            }
2446        }
2447
2448        if reduce_only {
2449            builder.reduce_only(true);
2450        }
2451
2452        builder
2453            .build()
2454            .map_err(|e| anyhow::anyhow!("Failed to build order params: {e}"))
2455    }
2456
2457    /// Submits a new order to the Kraken Futures exchange.
2458    ///
2459    /// # Errors
2460    ///
2461    /// Returns an error if:
2462    /// - Credentials are missing.
2463    /// - The instrument is not found in cache.
2464    /// - The order type or time in force is not supported.
2465    /// - The request fails.
2466    /// - The order is rejected.
2467    #[expect(clippy::too_many_arguments)]
2468    pub async fn submit_order(
2469        &self,
2470        account_id: AccountId,
2471        instrument_id: InstrumentId,
2472        client_order_id: ClientOrderId,
2473        order_side: OrderSide,
2474        order_type: OrderType,
2475        quantity: Quantity,
2476        time_in_force: TimeInForce,
2477        price: Option<Price>,
2478        trigger_price: Option<Price>,
2479        trigger_type: Option<TriggerType>,
2480        reduce_only: bool,
2481        post_only: bool,
2482    ) -> anyhow::Result<OrderStatusReport> {
2483        let instrument = self
2484            .get_cached_instrument(&instrument_id.symbol.inner())
2485            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2486
2487        let params = self.build_send_order_params(
2488            instrument_id,
2489            client_order_id,
2490            order_side,
2491            order_type,
2492            quantity,
2493            time_in_force,
2494            price,
2495            trigger_price,
2496            trigger_type,
2497            reduce_only,
2498            post_only,
2499        )?;
2500
2501        let response = self.inner.send_order_params(&params).await?;
2502
2503        if response.result != KrakenApiResult::Success {
2504            return Err(KrakenSubmitOrderError::Rejected {
2505                reason: response
2506                    .error
2507                    .unwrap_or_else(|| "Unknown error".to_string()),
2508            }
2509            .into());
2510        }
2511
2512        let send_status = response
2513            .send_status
2514            .ok_or(KrakenSubmitOrderError::MissingStatus)?;
2515
2516        match send_status.status.as_str() {
2517            "placed" | "filled" => {}
2518            "postWouldExecute" => {
2519                let reason = send_status
2520                    .order_events
2521                    .as_ref()
2522                    .and_then(|events| events.first())
2523                    .and_then(|event| event.reason.clone())
2524                    .unwrap_or_else(|| "Post-only order would have crossed".to_string());
2525                return Err(KrakenSubmitOrderError::Rejected {
2526                    reason: format!("POST_ONLY_REJECTED: {reason}"),
2527                }
2528                .into());
2529            }
2530            status if is_futures_submit_rejection(status) => {
2531                return Err(KrakenSubmitOrderError::Rejected {
2532                    reason: status.to_string(),
2533                }
2534                .into());
2535            }
2536            status => {
2537                return Err(KrakenSubmitOrderError::UnknownStatus {
2538                    status: status.to_string(),
2539                }
2540                .into());
2541            }
2542        }
2543
2544        let venue_order_id =
2545            send_status
2546                .order_id
2547                .clone()
2548                .ok_or_else(|| KrakenSubmitOrderError::MissingOrderId {
2549                    detail: format!("send status was {}", send_status.status),
2550                })?;
2551
2552        let report: anyhow::Result<OrderStatusReport> = async {
2553            let ts_init = self.generate_ts_init();
2554
2555            let open_orders_response = self.inner.get_open_orders().await?;
2556            if let Some(order) = open_orders_response
2557                .open_orders
2558                .iter()
2559                .find(|o| o.order_id == venue_order_id)
2560            {
2561                return parse_futures_order_status_report(
2562                    order,
2563                    &instrument,
2564                    account_id,
2565                    Some(quantity.as_decimal()),
2566                    ts_init,
2567                );
2568            }
2569
2570            // Order not in open orders - may have filled immediately (market order or aggressive limit)
2571            // Try to use order_events from send_status first
2572            if let Some(order_events) = &send_status.order_events
2573                && let Some(send_event) = order_events.first()
2574            {
2575                // Handle regular orders, trigger orders, and execution events
2576                let event = if let Some(order_data) = &send_event.order {
2577                    FuturesOrderEvent {
2578                        order_id: order_data.order_id.clone(),
2579                        cli_ord_id: order_data.cli_ord_id.clone(),
2580                        order_type: order_data.order_type,
2581                        symbol: order_data.symbol.clone(),
2582                        side: order_data.side,
2583                        quantity: order_data.quantity,
2584                        filled: order_data.filled,
2585                        limit_price: order_data.limit_price,
2586                        stop_price: order_data.stop_price,
2587                        timestamp: order_data.timestamp.clone(),
2588                        last_update_timestamp: order_data.last_update_timestamp.clone(),
2589                        reduce_only: order_data.reduce_only,
2590                        time_in_force: TimeInForce::Gtc,
2591                        post_only: false,
2592                    }
2593                } else if let Some(trigger_data) = &send_event.order_trigger {
2594                    FuturesOrderEvent {
2595                        order_id: trigger_data.uid.clone(),
2596                        cli_ord_id: trigger_data.client_id.clone(),
2597                        order_type: trigger_data.order_type,
2598                        symbol: trigger_data.symbol.clone(),
2599                        side: trigger_data.side,
2600                        quantity: trigger_data.quantity,
2601                        filled: Decimal::ZERO,
2602                        limit_price: trigger_data.limit_price,
2603                        stop_price: Some(trigger_data.trigger_price),
2604                        timestamp: trigger_data.timestamp.clone(),
2605                        last_update_timestamp: trigger_data.last_update_timestamp.clone(),
2606                        reduce_only: trigger_data.reduce_only,
2607                        time_in_force: TimeInForce::Gtc,
2608                        post_only: false,
2609                    }
2610                } else if let Some(prior_exec) = &send_event.order_prior_execution {
2611                    // EXECUTION event - use orderPriorExecution data
2612                    FuturesOrderEvent {
2613                        order_id: prior_exec.order_id.clone(),
2614                        cli_ord_id: prior_exec.cli_ord_id.clone(),
2615                        order_type: prior_exec.order_type,
2616                        symbol: prior_exec.symbol.clone(),
2617                        side: prior_exec.side,
2618                        quantity: prior_exec.quantity,
2619                        filled: send_event.amount.unwrap_or(prior_exec.quantity), // Use execution amount
2620                        limit_price: prior_exec.limit_price,
2621                        stop_price: prior_exec.stop_price,
2622                        timestamp: prior_exec.timestamp.clone(),
2623                        last_update_timestamp: prior_exec.last_update_timestamp.clone(),
2624                        reduce_only: prior_exec.reduce_only,
2625                        time_in_force: TimeInForce::Gtc,
2626                        post_only: false,
2627                    }
2628                } else {
2629                    anyhow::bail!("No order, orderTrigger, or orderPriorExecution data in event");
2630                };
2631                return parse_futures_order_event_status_report(
2632                    &event,
2633                    Some(send_event.event_type),
2634                    &instrument,
2635                    account_id,
2636                    ts_init,
2637                );
2638            }
2639
2640            // Fall back to querying order events
2641            let events_response = self.inner.get_order_events(None, None, None).await?;
2642            let event_wrapper = events_response
2643                .order_events
2644                .iter()
2645                .find(|e| e.order.order_id == venue_order_id)
2646                .ok_or_else(|| {
2647                    anyhow::anyhow!("Order not found in open orders or events: {venue_order_id}")
2648                })?;
2649
2650            if events_response
2651                .skipped_rows
2652                .iter()
2653                .any(|row| row.may_supersede(&venue_order_id, event_wrapper.state_ms))
2654            {
2655                anyhow::bail!(
2656                    "Order {venue_order_id}: a history row that could not be read may hold a newer state than the one found"
2657                );
2658            }
2659
2660            parse_futures_order_event_status_report(
2661                &event_wrapper.order,
2662                Some(event_wrapper.event_type),
2663                &instrument,
2664                account_id,
2665                ts_init,
2666            )
2667        }
2668        .await;
2669
2670        report.map_err(|source| KrakenSubmitOrderError::PostSubmitLookup { source }.into())
2671    }
2672
2673    /// Modifies an existing order on the Kraken Futures exchange.
2674    ///
2675    /// Returns the new venue order ID assigned to the modified order.
2676    ///
2677    /// # Errors
2678    ///
2679    /// Returns an error if:
2680    /// - Neither `client_order_id` nor `venue_order_id` is provided.
2681    /// - The instrument is not found in cache.
2682    /// - The request fails.
2683    /// - The edit fails on the exchange.
2684    /// - The response carries an invalid order ID.
2685    pub async fn modify_order(
2686        &self,
2687        instrument_id: InstrumentId,
2688        client_order_id: Option<ClientOrderId>,
2689        venue_order_id: Option<VenueOrderId>,
2690        quantity: Option<Quantity>,
2691        price: Option<Price>,
2692        trigger_price: Option<Price>,
2693    ) -> anyhow::Result<VenueOrderId> {
2694        let params = self.build_edit_order_params(
2695            instrument_id,
2696            client_order_id,
2697            venue_order_id,
2698            quantity,
2699            price,
2700            trigger_price,
2701        )?;
2702        let original_order_id = params.order_id.clone();
2703
2704        let response = self.inner.edit_order(&params).await?;
2705        let status = response.edit_status.status.as_str();
2706
2707        if response.result != KrakenApiResult::Success {
2708            return Err(KrakenModifyOrderError::Rejected {
2709                reason: status.to_string(),
2710            }
2711            .into());
2712        }
2713
2714        match status {
2715            "edited" => {}
2716            status if is_futures_modify_rejection(status) => {
2717                return Err(KrakenModifyOrderError::Rejected {
2718                    reason: status.to_string(),
2719                }
2720                .into());
2721            }
2722            status => {
2723                return Err(KrakenModifyOrderError::UnknownStatus {
2724                    status: status.to_string(),
2725                }
2726                .into());
2727            }
2728        }
2729
2730        // Return the new order_id from the response, or fall back to the original
2731        let new_venue_order_id = response
2732            .edit_status
2733            .order_id
2734            .or(response.edit_status.order_id_snake_case)
2735            .or(original_order_id)
2736            .ok_or(KrakenModifyOrderError::MissingOrderId)?;
2737
2738        parse_venue_order_id(&new_venue_order_id, "futures edit response").map_err(|e| {
2739            KrakenModifyOrderError::InvalidOrderId {
2740                detail: format!("{e:#}"),
2741            }
2742            .into()
2743        })
2744    }
2745
2746    /// Cancels an order on the Kraken Futures exchange.
2747    ///
2748    /// # Errors
2749    ///
2750    /// Returns an error if:
2751    /// - Credentials are missing.
2752    /// - Neither client_order_id nor venue_order_id is provided.
2753    /// - The request fails.
2754    /// - The order cancellation is rejected.
2755    pub async fn cancel_order(
2756        &self,
2757        _account_id: AccountId,
2758        instrument_id: InstrumentId,
2759        client_order_id: Option<ClientOrderId>,
2760        venue_order_id: Option<VenueOrderId>,
2761    ) -> anyhow::Result<()> {
2762        let _ = self
2763            .get_cached_instrument(&instrument_id.symbol.inner())
2764            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2765
2766        let (order_id, cli_ord_id) =
2767            order_identifier(client_order_id.as_ref(), venue_order_id.as_ref());
2768
2769        if order_id.is_none() && cli_ord_id.is_none() {
2770            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
2771        }
2772
2773        let response = self.inner.cancel_order(order_id, cli_ord_id).await?;
2774
2775        if response.result != KrakenApiResult::Success {
2776            let status = &response.cancel_status.status;
2777            anyhow::bail!("Order cancellation failed: {status}");
2778        }
2779
2780        Ok(())
2781    }
2782
2783    /// Cancels multiple orders on the Kraken Futures exchange.
2784    ///
2785    /// Automatically chunks requests into batches of 50 orders.
2786    ///
2787    /// # Parameters
2788    /// - `venue_order_ids` - List of venue order IDs to cancel.
2789    ///
2790    /// # Returns
2791    /// The total number of successfully cancelled orders.
2792    pub async fn cancel_orders_batch(
2793        &self,
2794        venue_order_ids: Vec<VenueOrderId>,
2795    ) -> anyhow::Result<usize> {
2796        if venue_order_ids.is_empty() {
2797            return Ok(0);
2798        }
2799
2800        let mut total_cancelled = 0;
2801
2802        for chunk in venue_order_ids.chunks(BATCH_CANCEL_LIMIT) {
2803            let order_ids: Vec<String> = chunk.iter().map(|id| id.to_string()).collect();
2804            let response = self.inner.cancel_orders_batch(order_ids).await?;
2805
2806            if response.result != KrakenApiResult::Success {
2807                let error_msg = response.error.as_deref().unwrap_or("Unknown error");
2808                anyhow::bail!("Batch cancel failed: {error_msg}");
2809            }
2810
2811            let success_count = response
2812                .batch_status
2813                .iter()
2814                .filter(|s| {
2815                    s.status == Some(KrakenSendStatus::Cancelled)
2816                        || s.cancel_status
2817                            .as_ref()
2818                            .is_some_and(|cs| cs.status == KrakenSendStatus::Cancelled)
2819                })
2820                .count();
2821
2822            total_cancelled += success_count;
2823        }
2824
2825        Ok(total_cancelled)
2826    }
2827
2828    /// Submits multiple orders in a single batch request.
2829    ///
2830    /// Builds batch send items from order parameters, chunks at the batch limit,
2831    /// and returns per-item send statuses.
2832    ///
2833    /// # Errors
2834    ///
2835    /// Returns an error if the batch request fails at the API level.
2836    #[expect(clippy::type_complexity)]
2837    pub async fn submit_orders_batch(
2838        &self,
2839        orders: Vec<(
2840            InstrumentId,
2841            ClientOrderId,
2842            OrderSide,
2843            OrderType,
2844            Quantity,
2845            TimeInForce,
2846            Option<Price>,
2847            Option<Price>,
2848            Option<TriggerType>,
2849            bool,
2850            bool,
2851        )>,
2852    ) -> anyhow::Result<Vec<FuturesSendStatus>> {
2853        Ok(self
2854            .send_order_batches(orders)
2855            .await
2856            .into_iter()
2857            .map(|result| match result {
2858                Ok(item) if item.result == KrakenApiResult::Success => item.status,
2859                Ok(mut item) => {
2860                    item.status.status = format!("api_error: {}", item.status.status);
2861                    item.status
2862                }
2863                Err(e) => FuturesSendStatus {
2864                    order_id: None,
2865                    order_tag: None,
2866                    status: if matches!(
2867                        e.downcast_ref::<KrakenBatchOrderError>(),
2868                        Some(KrakenBatchOrderError::Validation { .. })
2869                    ) {
2870                        format!("validation_error: {e}")
2871                    } else {
2872                        format!("batch_error: {e}")
2873                    },
2874                    order_events: None,
2875                    cli_ord_id: None,
2876                    received_time: None,
2877                },
2878            })
2879            .collect())
2880    }
2881
2882    pub(crate) async fn send_order_batches(
2883        &self,
2884        orders: Vec<FuturesBatchOrder>,
2885    ) -> Vec<anyhow::Result<FuturesBatchSubmitItem>> {
2886        let count = orders.len();
2887        if count == 0 {
2888            return Vec::new();
2889        }
2890
2891        let mut results: Vec<Option<anyhow::Result<FuturesBatchSubmitItem>>> =
2892            (0..count).map(|_| None).collect();
2893        let mut valid_items = Vec::with_capacity(count);
2894
2895        for (
2896            idx,
2897            (
2898                instrument_id,
2899                client_order_id,
2900                order_side,
2901                order_type,
2902                quantity,
2903                time_in_force,
2904                price,
2905                trigger_price,
2906                trigger_type,
2907                reduce_only,
2908                post_only,
2909            ),
2910        ) in orders.into_iter().enumerate()
2911        {
2912            match self.build_send_order_params(
2913                instrument_id,
2914                client_order_id,
2915                order_side,
2916                order_type,
2917                quantity,
2918                time_in_force,
2919                price,
2920                trigger_price,
2921                trigger_type,
2922                reduce_only,
2923                post_only,
2924            ) {
2925                Ok(params) => {
2926                    valid_items.push((
2927                        idx,
2928                        KrakenFuturesBatchSendItem::from_params(params, idx.to_string()),
2929                    ));
2930                }
2931                Err(e) => {
2932                    results[idx] = Some(Err(KrakenBatchOrderError::Validation {
2933                        reason: e.to_string(),
2934                    }
2935                    .into()));
2936                }
2937            }
2938        }
2939
2940        if valid_items.is_empty() {
2941            return results.into_iter().flatten().collect();
2942        }
2943
2944        let chunks: Vec<_> = valid_items.chunks(BATCH_ORDER_LIMIT).collect();
2945        for (chunk_index, chunk) in chunks.iter().enumerate() {
2946            let items = chunk.iter().map(|(_, item)| item.clone()).collect();
2947            match self.inner.submit_orders_batch(items).await {
2948                Ok(response) => {
2949                    let mut by_tag: HashMap<String, Option<FuturesSendStatus>> = HashMap::new();
2950                    let response_result = response.result;
2951
2952                    for status in response.batch_status {
2953                        if let Some(tag) = status.order_tag.clone() {
2954                            by_tag
2955                                .entry(tag)
2956                                .and_modify(|entry| *entry = None)
2957                                .or_insert(Some(status));
2958                        }
2959                    }
2960
2961                    for (idx, item) in *chunk {
2962                        let result = match by_tag.remove(&item.order_tag) {
2963                            Some(Some(status)) => Ok(FuturesBatchSubmitItem {
2964                                result: response_result,
2965                                status,
2966                            }),
2967                            Some(None) => Err(KrakenBatchOrderError::DuplicateResponse {
2968                                key: format!("order_tag {}", item.order_tag),
2969                            }
2970                            .into()),
2971                            None => Err(KrakenBatchOrderError::MissingResponse {
2972                                key: format!("order_tag {}", item.order_tag),
2973                            }
2974                            .into()),
2975                        };
2976                        results[*idx] = Some(result);
2977                    }
2978                }
2979                Err(e) => {
2980                    for (idx, _) in *chunk {
2981                        results[*idx] = Some(Err(anyhow::Error::new(e.clone())));
2982                    }
2983
2984                    for later_chunk in &chunks[chunk_index + 1..] {
2985                        for (idx, _) in *later_chunk {
2986                            results[*idx] = Some(Err(KrakenBatchOrderError::NotAttempted.into()));
2987                        }
2988                    }
2989                    break;
2990                }
2991            }
2992        }
2993
2994        results
2995            .into_iter()
2996            .map(|result| result.unwrap_or_else(|| Err(KrakenBatchOrderError::NotAttempted.into())))
2997            .collect()
2998    }
2999
3000    /// Modifies multiple orders in a single batch request.
3001    #[expect(clippy::type_complexity)]
3002    pub async fn edit_orders_batch(
3003        &self,
3004        orders: Vec<(
3005            InstrumentId,
3006            Option<ClientOrderId>,
3007            Option<VenueOrderId>,
3008            Option<Quantity>,
3009            Option<Price>,
3010            Option<Price>,
3011        )>,
3012    ) -> anyhow::Result<Vec<String>> {
3013        let count = orders.len();
3014        if count == 0 {
3015            return Ok(Vec::new());
3016        }
3017
3018        let mut all_statuses: Vec<Option<String>> = vec![None; count];
3019        let mut valid_items = Vec::with_capacity(count);
3020        let mut valid_indices = Vec::with_capacity(count);
3021
3022        for (
3023            idx,
3024            (instrument_id, client_order_id, venue_order_id, quantity, price, trigger_price),
3025        ) in orders.into_iter().enumerate()
3026        {
3027            match self.build_edit_order_params(
3028                instrument_id,
3029                client_order_id,
3030                venue_order_id,
3031                quantity,
3032                price,
3033                trigger_price,
3034            ) {
3035                Ok(params) => {
3036                    valid_items.push(KrakenFuturesBatchEditItem::from_params(
3037                        params,
3038                        idx.to_string(),
3039                    ));
3040                    valid_indices.push(idx);
3041                }
3042                Err(e) => {
3043                    all_statuses[idx] = Some(format!("validation_error: {e}"));
3044                }
3045            }
3046        }
3047
3048        if valid_items.is_empty() {
3049            return Ok(all_statuses.into_iter().flatten().collect());
3050        }
3051
3052        let mut batch_statuses: Vec<String> = Vec::with_capacity(valid_items.len());
3053
3054        for chunk in valid_items.chunks(BATCH_ORDER_LIMIT) {
3055            match self.inner.edit_orders_batch(chunk.to_vec()).await {
3056                Ok(response) => {
3057                    if response.result == KrakenApiResult::Success {
3058                        batch_statuses.extend(response.batch_status.into_iter().map(|s| s.status));
3059                    } else {
3060                        let error_msg = response
3061                            .batch_status
3062                            .first()
3063                            .map_or("Unknown error", |s| s.status.as_str());
3064
3065                        for _ in 0..chunk.len() {
3066                            batch_statuses.push(format!("api_error: {error_msg}"));
3067                        }
3068                    }
3069                }
3070                Err(e) => {
3071                    let remaining = valid_items.len() - batch_statuses.len();
3072                    for _ in 0..remaining {
3073                        batch_statuses.push(format!("batch_error: {e}"));
3074                    }
3075                    break;
3076                }
3077            }
3078        }
3079
3080        for (batch_idx, &original_idx) in valid_indices.iter().enumerate() {
3081            if let Some(status) = batch_statuses.get(batch_idx) {
3082                all_statuses[original_idx] = Some(status.clone());
3083            }
3084        }
3085
3086        Ok(all_statuses.into_iter().flatten().collect())
3087    }
3088
3089    fn build_edit_order_params(
3090        &self,
3091        instrument_id: InstrumentId,
3092        client_order_id: Option<ClientOrderId>,
3093        venue_order_id: Option<VenueOrderId>,
3094        quantity: Option<Quantity>,
3095        price: Option<Price>,
3096        trigger_price: Option<Price>,
3097    ) -> anyhow::Result<KrakenFuturesEditOrderParams> {
3098        let _ = self
3099            .get_cached_instrument(&instrument_id.symbol.inner())
3100            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
3101
3102        let (order_id, cli_ord_id) =
3103            order_identifier(client_order_id.as_ref(), venue_order_id.as_ref());
3104
3105        if order_id.is_none() && cli_ord_id.is_none() {
3106            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
3107        }
3108
3109        let mut builder = KrakenFuturesEditOrderParamsBuilder::default();
3110
3111        if let Some(ref id) = order_id {
3112            builder.order_id(id.clone());
3113        }
3114
3115        if let Some(ref id) = cli_ord_id {
3116            builder.cli_ord_id(id.clone());
3117        }
3118
3119        // A Nautilus quantity is the order's total, fills included, while the venue reads a bare
3120        // size as the open size
3121        if let Some(qty) = quantity {
3122            builder.size(qty.to_string());
3123            builder.qty_mode(KrakenFuturesQtyMode::Absolute);
3124        }
3125
3126        if let Some(p) = price {
3127            builder.limit_price(p.to_string());
3128        }
3129
3130        if let Some(tp) = trigger_price {
3131            builder.stop_price(tp.to_string());
3132        }
3133
3134        builder
3135            .build()
3136            .map_err(|e| anyhow::anyhow!("Failed to build edit order params: {e}"))
3137    }
3138}
3139
3140/// The identifiers a cancel or edit names an order by, as `(order_id, cliOrdId)`: its venue order
3141/// ID when known, else its full client order ID. An order sent with a shortened client order ID is
3142/// held under that form, so its full ID beside the venue order ID could name no order.
3143pub(crate) fn order_identifier(
3144    client_order_id: Option<&ClientOrderId>,
3145    venue_order_id: Option<&VenueOrderId>,
3146) -> (Option<String>, Option<String>) {
3147    match venue_order_id {
3148        Some(venue_order_id) => (Some(venue_order_id.to_string()), None),
3149        None => (None, client_order_id.map(ToString::to_string)),
3150    }
3151}
3152
3153pub(crate) fn is_futures_submit_rejection(status: &str) -> bool {
3154    matches!(
3155        status.parse::<KrakenSendStatus>(),
3156        Ok(KrakenSendStatus::InsufficientAvailableFunds
3157            | KrakenSendStatus::InvalidOrderType
3158            | KrakenSendStatus::InvalidSize
3159            | KrakenSendStatus::WouldCauseLiquidation
3160            | KrakenSendStatus::PostWouldExecute
3161            | KrakenSendStatus::IocWouldNotExecute
3162            | KrakenSendStatus::ReduceOnlyWouldIncreasePosition
3163            | KrakenSendStatus::ClientOrderIdAlreadyExist
3164            | KrakenSendStatus::ClientOrderIdTooBig
3165            | KrakenSendStatus::ClientOrderIdTooLong
3166            | KrakenSendStatus::ClientOrderIdInvalid)
3167    )
3168}
3169
3170fn is_futures_modify_rejection(status: &str) -> bool {
3171    status.parse::<KrakenSendStatus>().is_ok_and(|status| {
3172        status == KrakenSendStatus::NotFound || is_futures_submit_rejection(status.as_ref())
3173    })
3174}
3175
3176fn map_futures_trigger_signal(
3177    trigger_type: Option<TriggerType>,
3178) -> anyhow::Result<Option<KrakenTriggerSignal>> {
3179    match trigger_type {
3180        None => Ok(None),
3181        Some(TriggerType::Default | TriggerType::LastPrice) => Ok(Some(KrakenTriggerSignal::Last)),
3182        Some(TriggerType::MarkPrice) => Ok(Some(KrakenTriggerSignal::Mark)),
3183        Some(TriggerType::IndexPrice) => Ok(Some(KrakenTriggerSignal::Index)),
3184        Some(other) => anyhow::bail!(
3185            "Unsupported trigger type for Kraken Futures: {other:?} (only LastPrice, MarkPrice, and IndexPrice supported)"
3186        ),
3187    }
3188}
3189
3190/// Accumulated `(total, locked)` balance amounts per standard code.
3191type AmountsByCode = AHashMap<Ustr, (Decimal, Decimal)>;
3192
3193/// Combines the per-wallet balances and margins of a Kraken Futures accounts response.
3194///
3195/// The venue keys the same asset differently per wallet, `xbt` in the cash and single-collateral
3196/// wallets against `XBT` in the flex wallet, and every spelling maps to one standard code. The
3197/// accounts map is unordered, so balances accumulate per code and are emitted once in code order.
3198/// Pushing them into a flat vector instead would leave the surviving entry to iteration order,
3199/// since the account keys its balances by currency.
3200///
3201/// A wallet the venue lists at zero contributes a zero, so an asset drawn down to nothing is
3202/// reported at zero rather than left at its previous value: the engine only ever inserts
3203/// balances, and nothing downstream can clear one.
3204///
3205/// Margins are summed per currency the same way. A single-collateral wallet's requirement is in
3206/// its `currency` and a flex wallet's in USD, and `MarginAccount` keys account-wide margins by
3207/// currency, so two entries under one code would collapse by iteration order.
3208fn parse_account_entries(
3209    accounts: &AHashMap<String, FuturesAccount>,
3210) -> (Vec<AccountBalance>, Vec<MarginBalance>) {
3211    let mut balances: AmountsByCode = AHashMap::new();
3212    let mut margins: AmountsByCode = AHashMap::new();
3213
3214    for account in accounts.values() {
3215        match account.account_type {
3216            KrakenFuturesAccountType::MultiCollateralMarginAccount => {
3217                parse_multi_collateral_balances(account, &mut balances);
3218                parse_multi_collateral_margins(account, &mut margins);
3219            }
3220            KrakenFuturesAccountType::MarginAccount => {
3221                let currency = margin_account_currency(account);
3222
3223                if currency.is_none() {
3224                    // Labeling the requirement, or attributing the available funds, with a
3225                    // guessed currency would misstate them.
3226                    log::warn!(
3227                        "Single-collateral wallet currency unresolved (currency {:?}): its margin requirement is skipped and none of its assets is reported as locked; balances {:?}",
3228                        account.currency,
3229                        account.balances.keys().collect::<Vec<_>>()
3230                    );
3231                }
3232
3233                parse_margin_account_balances(account, currency.as_deref(), &mut balances);
3234                parse_margin_account_margins(account, currency.as_deref(), &mut margins);
3235            }
3236            KrakenFuturesAccountType::CashAccount => {
3237                parse_cash_account_balances(account, &mut balances);
3238            }
3239            KrakenFuturesAccountType::Unknown => {
3240                log::debug!("Unknown account type: {:?}", account.account_type);
3241            }
3242        }
3243    }
3244
3245    (emit_balances(&balances), emit_margins(&margins))
3246}
3247
3248/// Resolves the currency a futures balance or margin requirement is emitted in.
3249///
3250/// Every balance and margin keeps an eight-decimal currency, so wallet amounts are never rounded;
3251/// resolving USD to the registered two-decimal currency would round cash and single-collateral
3252/// USD balances, and the flex USD requirement, to cents.
3253fn futures_balance_currency(code: &str) -> anyhow::Result<Currency> {
3254    Currency::new_checked(code, 8, 0, code, CurrencyType::Crypto)
3255        .map_err(|e| anyhow::anyhow!("Invalid currency code {code:?}: {e}"))
3256}
3257
3258/// Returns the codes of `amounts` in a stable order.
3259fn sorted_codes(amounts: &AmountsByCode) -> Vec<Ustr> {
3260    let mut codes: Vec<Ustr> = amounts.keys().copied().collect();
3261    codes.sort_unstable();
3262    codes
3263}
3264
3265fn emit_balances(amounts: &AmountsByCode) -> Vec<AccountBalance> {
3266    let mut balances = Vec::with_capacity(amounts.len());
3267
3268    for code in sorted_codes(amounts) {
3269        let (total, locked) = amounts[&code];
3270        match futures_balance_currency(code.as_str())
3271            .and_then(|currency| aggregate_balance(total, locked, currency))
3272        {
3273            Ok(balance) => balances.push(balance),
3274            Err(e) => log::warn!("Skipping {code} balance: {e}"),
3275        }
3276    }
3277
3278    balances
3279}
3280
3281/// Builds the balance for amounts already bounded per wallet and summed.
3282///
3283/// `AccountBalance::from_total_and_locked` would clamp the aggregate's locked amount into
3284/// `[0, total]` a second time, which hides a shortfall: a margin wallet at -1 with -2 available
3285/// reserves 1, and combined with 1.5 in cash the sums are 0.5 total and 1 locked, so free is -0.5.
3286/// Clamping would report 0.5 locked and 0 free. The sums are therefore emitted as they are, with
3287/// free derived in fixed point so `total == locked + free` holds exactly.
3288fn aggregate_balance(
3289    total: Decimal,
3290    locked: Decimal,
3291    currency: Currency,
3292) -> anyhow::Result<AccountBalance> {
3293    let total = Money::from_decimal(total, currency)?;
3294    let locked = Money::from_decimal(locked, currency)?;
3295    let free = total
3296        .checked_sub(locked)
3297        .ok_or_else(|| anyhow::anyhow!("Derived `free` for {currency} exceeds Money bounds"))?;
3298
3299    AccountBalance::new_checked(total, locked, free).map_err(Into::into)
3300}
3301
3302/// Adds one wallet's `total` and `locked` to the entry for `code`.
3303///
3304/// The wallet's `locked` is bounded first, exactly as `AccountBalance::from_total_and_locked`
3305/// bounds a single balance: clamped into `[0, total]` for a non-negative total, and passed
3306/// through unchanged for a negative one. Summing the raw figure instead would let one wallet
3307/// cancel another's reservation. A flex wallet holding 1 BTC with 1.6 BTC-equivalent available
3308/// margin reports a raw locked of -0.6, which would erase the 0.6 a single-collateral wallet
3309/// holding 1 BTC with 0.4 available has genuinely reserved.
3310fn accumulate_balance(amounts: &mut AmountsByCode, code: &str, total: Decimal, locked: Decimal) {
3311    let locked = if total.is_sign_negative() {
3312        locked
3313    } else {
3314        locked.clamp(Decimal::ZERO, total)
3315    };
3316
3317    let entry = amounts
3318        .entry(Ustr::from(code))
3319        .or_insert((Decimal::ZERO, Decimal::ZERO));
3320    entry.0 += total;
3321    entry.1 += locked;
3322}
3323
3324fn parse_multi_collateral_balances(account: &FuturesAccount, balances: &mut AmountsByCode) {
3325    // `portfolioValue` is the USD valuation of the whole flex collateral set, so adding the USD
3326    // collateral entry on top of it would count the same funds twice.
3327    let emits_portfolio_value = account
3328        .portfolio_value
3329        .is_some_and(|value| value > Decimal::ZERO);
3330
3331    for (currency_code, currency_info) in &account.currencies {
3332        // The venue keys these by its own spelling and casing, so map to the standard code.
3333        let code = normalize_asset_key(currency_code.as_str());
3334
3335        if emits_portfolio_value && code == "USD" {
3336            continue;
3337        }
3338
3339        let total_amount = currency_info.quantity;
3340        let available_amount = currency_info.available.unwrap_or(total_amount);
3341        let locked_amount = total_amount - available_amount;
3342
3343        accumulate_balance(balances, &code, total_amount, locked_amount);
3344    }
3345
3346    // Multi-collateral accounts track margin in USD even though the
3347    // actual collateral is held in various crypto currencies.
3348    if let Some(portfolio_value) = account.portfolio_value
3349        && portfolio_value > Decimal::ZERO
3350    {
3351        let available_usd = account.available_margin.unwrap_or(portfolio_value);
3352        let locked_usd = portfolio_value - available_usd;
3353
3354        accumulate_balance(balances, "USD", portfolio_value, locked_usd);
3355    }
3356}
3357
3358fn parse_multi_collateral_margins(account: &FuturesAccount, margins: &mut AmountsByCode) {
3359    // The flex wallet reports its requirement in USD in `initialMargin` and `maintenanceMargin`;
3360    // its schema carries no `marginRequirements`.
3361    let initial_margin = account.initial_margin.unwrap_or(Decimal::ZERO);
3362    let maintenance = account.maintenance_margin.unwrap_or(Decimal::ZERO);
3363
3364    // The same gate as the single-collateral wallet: a requirement counts when either figure is
3365    // positive.
3366    if initial_margin > Decimal::ZERO || maintenance > Decimal::ZERO {
3367        accumulate_margin(margins, "USD", initial_margin, maintenance);
3368    }
3369}
3370
3371/// `wallet_currency` is the wallet's resolved `currency`, or `None` when it cannot be resolved.
3372fn parse_margin_account_balances(
3373    account: &FuturesAccount,
3374    wallet_currency: Option<&str>,
3375    balances: &mut AmountsByCode,
3376) {
3377    // `auxiliary.af` is the wallet's available funds in its `currency`, so it bounds that asset
3378    // alone; another asset the wallet holds has nothing reserved against it. Locked is derived so
3379    // that free equals the venue's available funds, which already net unrealized PnL. Without a
3380    // resolved currency the figure cannot be attributed, and no asset is reported as locked.
3381    let available = account.auxiliary.as_ref().and_then(|aux| aux.af);
3382
3383    for (currency_code, &amount) in &account.balances {
3384        // The venue keys this map by contract symbol as well as by currency, for example
3385        // `FI_XBTUSD_171215`, and those entries are positions rather than balances. No Kraken
3386        // asset code contains an underscore.
3387        if currency_code.contains('_') {
3388            continue;
3389        }
3390
3391        // The venue keys these by its own spelling and casing, so map to the standard code.
3392        let code = normalize_asset_key(currency_code.as_str());
3393
3394        let locked = match available {
3395            Some(af) if wallet_currency == Some(code.as_str()) => amount - af,
3396            _ => Decimal::ZERO,
3397        };
3398
3399        accumulate_balance(balances, &code, amount, locked);
3400    }
3401}
3402
3403/// Returns the currency a single-collateral wallet's figures are denominated in.
3404///
3405/// The wallet schema requires `currency` and states that `auxiliary` and `marginRequirements` are
3406/// in it. Guessing it from the asset keys in `balances` could label a requirement with dust held in
3407/// another asset, so a wallet without a usable field resolves to `None`.
3408fn margin_account_currency(account: &FuturesAccount) -> Option<String> {
3409    account
3410        .currency
3411        .as_deref()
3412        .map(str::trim)
3413        .filter(|code| !code.is_empty())
3414        .map(normalize_asset_key)
3415}
3416
3417/// `wallet_currency` is the wallet's resolved `currency`; a wallet without one contributes no
3418/// margin entry, since labeling the requirement with a guess would misstate it.
3419fn parse_margin_account_margins(
3420    account: &FuturesAccount,
3421    wallet_currency: Option<&str>,
3422    margins: &mut AmountsByCode,
3423) {
3424    if let (Some(mr), Some(code)) = (account.margin_requirements.as_ref(), wallet_currency) {
3425        let im = mr.im.unwrap_or(Decimal::ZERO);
3426        let mm = mr.mm.unwrap_or(Decimal::ZERO);
3427
3428        if im > Decimal::ZERO || mm > Decimal::ZERO {
3429            accumulate_margin(margins, code, im, mm);
3430        }
3431    }
3432}
3433
3434/// Adds one wallet's requirement to the entry for `code`.
3435fn accumulate_margin(
3436    margins: &mut AmountsByCode,
3437    code: &str,
3438    initial: Decimal,
3439    maintenance: Decimal,
3440) {
3441    let entry = margins
3442        .entry(Ustr::from(code))
3443        .or_insert((Decimal::ZERO, Decimal::ZERO));
3444    entry.0 += initial;
3445    entry.1 += maintenance;
3446}
3447
3448fn emit_margins(amounts: &AmountsByCode) -> Vec<MarginBalance> {
3449    let mut margins = Vec::with_capacity(amounts.len());
3450
3451    for code in sorted_codes(amounts) {
3452        let (initial, maintenance) = amounts[&code];
3453        let margin = futures_balance_currency(code.as_str()).and_then(|currency| {
3454            let initial = Money::from_decimal(initial, currency)?;
3455            let maintenance = Money::from_decimal(maintenance, currency)?;
3456            Ok(MarginBalance::new(initial, maintenance, None))
3457        });
3458
3459        match margin {
3460            Ok(margin) => margins.push(margin),
3461            Err(e) => log::warn!("Skipping {code} margin: {e}"),
3462        }
3463    }
3464
3465    margins
3466}
3467
3468fn parse_cash_account_balances(account: &FuturesAccount, balances: &mut AmountsByCode) {
3469    for (currency_code, &amount) in &account.balances {
3470        // The venue keys these by its own spelling and casing, so map to the standard code.
3471        let code = normalize_asset_key(currency_code.as_str());
3472
3473        accumulate_balance(balances, &code, amount, Decimal::ZERO);
3474    }
3475}
3476
3477/// Records a history row in scope that the read could not use, keeping the newest such row per
3478/// order so the fold can withhold an order it would otherwise report from an older state.
3479fn record_unread_row(
3480    coverage: &mut ReportCoverage,
3481    unread_ms: &mut AHashMap<VenueOrderId, i64>,
3482    order_id: &str,
3483    event_ms: i64,
3484) {
3485    coverage.skip(order_id);
3486
3487    let newest = unread_ms
3488        .entry(VenueOrderId::new(order_id))
3489        .or_insert(event_ms);
3490    *newest = (*newest).max(event_ms);
3491}
3492
3493/// Whether `candidate` describes a later state of the same order than `existing`.
3494///
3495/// A closed order does not reopen, so a closed state beats an open one whatever their stamps: an
3496/// open state stamped later, such as a refused edit logged after a cancel, describes the order as
3497/// it stood before it closed. Between two states of the same kind the later `ts_last` wins, and on
3498/// a tie, which the venue's millisecond stamps allow, the larger filled quantity.
3499pub(crate) fn supersedes(candidate: &OrderStatusReport, existing: &OrderStatusReport) -> bool {
3500    match (
3501        candidate.order_status.is_closed(),
3502        existing.order_status.is_closed(),
3503    ) {
3504        (true, false) => true,
3505        (false, true) => false,
3506        _ if candidate.ts_last != existing.ts_last => candidate.ts_last > existing.ts_last,
3507        _ => candidate.filled_qty > existing.filled_qty,
3508    }
3509}
3510
3511#[cfg(test)]
3512mod tests {
3513    use std::{sync::Arc, time::Duration};
3514
3515    use ahash::AHashMap;
3516    use nautilus_model::{enums::OrderStatus, instruments::CryptoPerpetual};
3517    use nautilus_testkit::http::assert_http_redirect_rejected;
3518    use rstest::rstest;
3519    use rust_decimal_macros::dec;
3520
3521    use super::*;
3522
3523    #[tokio::test]
3524    async fn test_authenticated_client_rejects_redirects() {
3525        let client = KrakenFuturesRawHttpClient::with_credentials(
3526            "key".into(),
3527            "secret".into(),
3528            KrakenEnvironment::Live,
3529            None,
3530            3,
3531            Some(0),
3532            None,
3533            None,
3534            None,
3535            10,
3536        )
3537        .unwrap()
3538        .client;
3539        assert_http_redirect_rejected(|url| async move {
3540            client
3541                .get(url, None, None, Some(3), None)
3542                .await
3543                .unwrap()
3544                .status
3545                .as_u16()
3546        })
3547        .await;
3548    }
3549
3550    #[rstest]
3551    fn test_raw_client_creation() {
3552        let client = KrakenFuturesRawHttpClient::default();
3553        assert!(client.credential.is_none());
3554        assert!(client.base_url().contains("futures"));
3555    }
3556
3557    #[rstest]
3558    fn test_raw_client_with_credentials() {
3559        let client = KrakenFuturesRawHttpClient::with_credentials(
3560            "test_key".to_string(),
3561            "test_secret".to_string(),
3562            KrakenEnvironment::Live,
3563            None,
3564            60,
3565            None,
3566            None,
3567            None,
3568            None,
3569            KRAKEN_FUTURES_DEFAULT_RATE_LIMIT_PER_SECOND,
3570        )
3571        .unwrap();
3572        assert!(client.credential.is_some());
3573    }
3574
3575    #[rstest]
3576    #[tokio::test]
3577    async fn test_order_request_cancellation_before_transport() {
3578        let client = Arc::new(KrakenFuturesRawHttpClient::default());
3579        let guard = client.auth_mutex.lock().await;
3580        let waiting_client = Arc::clone(&client);
3581        let waiting = tokio::spawn(async move {
3582            waiting_client
3583                .send_authenticated_post::<serde_json::Value>(
3584                    "/derivatives/api/v3/sendorder",
3585                    "orderType=lmt".to_string(),
3586                )
3587                .await
3588        });
3589
3590        tokio::task::yield_now().await;
3591        client.cancel_all_requests();
3592        let waiting_result = tokio::time::timeout(Duration::from_secs(1), waiting)
3593            .await
3594            .expect("auth lock wait should stop on cancellation")
3595            .expect("auth request task should complete");
3596        drop(guard);
3597        client.reset_cancellation_token();
3598        let reset_token = client.cancellation_token();
3599
3600        assert!(matches!(
3601            waiting_result,
3602            Err(KrakenHttpError::RequestNotStarted(ref message))
3603                if message == "Request cancelled"
3604        ));
3605        assert!(!reset_token.is_cancelled());
3606    }
3607
3608    #[rstest]
3609    fn test_client_creation() {
3610        let client = KrakenFuturesHttpClient::default();
3611        assert!(client.instruments_cache.is_empty());
3612    }
3613
3614    #[rstest]
3615    fn test_client_with_credentials() {
3616        let client = KrakenFuturesHttpClient::with_credentials(
3617            "test_key".to_string(),
3618            "test_secret".to_string(),
3619            KrakenEnvironment::Live,
3620            None,
3621            60,
3622            None,
3623            None,
3624            None,
3625            None,
3626            KRAKEN_FUTURES_DEFAULT_RATE_LIMIT_PER_SECOND,
3627        )
3628        .unwrap();
3629        assert!(client.instruments_cache.is_empty());
3630    }
3631
3632    fn entries_for(
3633        accounts: &[(&str, FuturesAccount)],
3634    ) -> (Vec<AccountBalance>, Vec<MarginBalance>) {
3635        let map: AHashMap<String, FuturesAccount> = accounts
3636            .iter()
3637            .map(|(name, account)| ((*name).to_string(), account.clone()))
3638            .collect();
3639
3640        parse_account_entries(&map)
3641    }
3642
3643    fn flex_wallet(
3644        currencies: &[(&str, Decimal)],
3645        portfolio_value: Option<Decimal>,
3646    ) -> FuturesAccount {
3647        FuturesAccount {
3648            account_type: KrakenFuturesAccountType::MultiCollateralMarginAccount,
3649            currency: None,
3650            balances: AHashMap::new(),
3651            currencies: currencies
3652                .iter()
3653                .map(|(code, quantity)| {
3654                    (
3655                        (*code).to_string(),
3656                        FuturesFlexCurrency {
3657                            quantity: *quantity,
3658                            value: None,
3659                            collateral: None,
3660                            available: Some(*quantity),
3661                        },
3662                    )
3663                })
3664                .collect(),
3665            auxiliary: None,
3666            margin_requirements: None,
3667            portfolio_value,
3668            available_margin: portfolio_value,
3669            initial_margin: None,
3670            maintenance_margin: None,
3671            pnl: None,
3672        }
3673    }
3674
3675    fn cash_wallet(balances: &[(&str, Decimal)]) -> FuturesAccount {
3676        FuturesAccount {
3677            account_type: KrakenFuturesAccountType::CashAccount,
3678            currency: None,
3679            balances: balances
3680                .iter()
3681                .map(|(code, amount)| ((*code).to_string(), *amount))
3682                .collect(),
3683            currencies: AHashMap::new(),
3684            auxiliary: None,
3685            margin_requirements: None,
3686            portfolio_value: None,
3687            available_margin: None,
3688            initial_margin: None,
3689            maintenance_margin: None,
3690            pnl: None,
3691        }
3692    }
3693
3694    /// One asset held in two wallets must produce exactly one balance, holding both amounts.
3695    ///
3696    /// The cash wallet keys it `xbt` and the flex wallet `XBT`; both map to `BTC`. Emitting two
3697    /// entries would leave the survivor to hash-map order, since the account keys balances by
3698    /// currency.
3699    #[rstest]
3700    fn test_parse_account_entries_combines_one_asset_across_wallets() {
3701        let (balances, _) = entries_for(&[
3702            ("cash", cash_wallet(&[("xbt", dec!(1.5))])),
3703            ("flex", flex_wallet(&[("XBT", dec!(0.25))], None)),
3704        ]);
3705
3706        let btc: Vec<_> = balances
3707            .iter()
3708            .filter(|b| b.currency.code.as_str() == "BTC")
3709            .collect();
3710        assert_eq!(btc.len(), 1, "expected one BTC balance: {balances:?}");
3711        assert_eq!(btc[0].total.as_decimal(), dec!(1.75));
3712    }
3713
3714    /// Entry order must not depend on hash-map iteration order.
3715    #[rstest]
3716    fn test_parse_account_entries_emits_balances_in_code_order() {
3717        let (balances, _) = entries_for(&[(
3718            "cash",
3719            cash_wallet(&[("xrp", dec!(10)), ("xbt", dec!(1)), ("eth", dec!(2))]),
3720        )]);
3721
3722        let codes: Vec<&str> = balances.iter().map(|b| b.currency.code.as_str()).collect();
3723        assert_eq!(codes, vec!["BTC", "ETH", "XRP"]);
3724    }
3725
3726    /// `portfolioValue` already values the flex collateral set, so its USD entry wins alone.
3727    #[rstest]
3728    fn test_parse_account_entries_does_not_double_count_flex_usd() {
3729        let (balances, _) = entries_for(&[(
3730            "flex",
3731            flex_wallet(&[("USD", dec!(5000))], Some(dec!(34995.52))),
3732        )]);
3733
3734        let usd: Vec<_> = balances
3735            .iter()
3736            .filter(|b| b.currency.code.as_str() == "USD")
3737            .collect();
3738        assert_eq!(usd.len(), 1, "expected one USD balance: {balances:?}");
3739        assert_eq!(usd[0].total.as_decimal(), dec!(34995.52));
3740    }
3741
3742    /// Each wallet's `locked` is bounded before the sum, so one wallet cannot cancel another's.
3743    ///
3744    /// A single-collateral wallet with 1 BTC and 0.4 available has reserved 0.6. A flex wallet
3745    /// with 1 BTC and 1.6 BTC-equivalent available margin reports a raw locked of -0.6, which
3746    /// summed unbounded would erase that reservation.
3747    #[rstest]
3748    fn test_parse_account_entries_bounds_locked_per_wallet() {
3749        let single = FuturesAccount {
3750            account_type: KrakenFuturesAccountType::MarginAccount,
3751            currency: Some("xbt".to_string()),
3752            balances: [("xbt".to_string(), dec!(1))].into_iter().collect(),
3753            currencies: AHashMap::new(),
3754            auxiliary: Some(FuturesAuxiliary {
3755                usd: None,
3756                pv: None,
3757                pnl: None,
3758                af: Some(dec!(0.4)),
3759                funding: None,
3760            }),
3761            margin_requirements: None,
3762            portfolio_value: None,
3763            available_margin: None,
3764            initial_margin: None,
3765            maintenance_margin: None,
3766            pnl: None,
3767        };
3768
3769        let mut flex = flex_wallet(&[], None);
3770        flex.currencies.insert(
3771            "XBT".to_string(),
3772            FuturesFlexCurrency {
3773                quantity: dec!(1),
3774                value: None,
3775                collateral: None,
3776                available: Some(dec!(1.6)),
3777            },
3778        );
3779
3780        let (balances, _) = entries_for(&[("fi_xbtusd", single), ("flex", flex)]);
3781
3782        let btc = balances
3783            .iter()
3784            .find(|b| b.currency.code.as_str() == "BTC")
3785            .expect("one BTC balance");
3786        assert_eq!(btc.total.as_decimal(), dec!(2));
3787        assert_eq!(
3788            btc.locked.as_decimal(),
3789            dec!(0.6),
3790            "the flex wallet's negative raw locked must not cancel the reservation"
3791        );
3792        assert_eq!(btc.free.as_decimal(), dec!(1.4));
3793    }
3794
3795    /// Summed wallet-local amounts are emitted as summed, so a shortfall stays visible.
3796    ///
3797    /// A margin wallet at -1 BTC with -2 BTC available reserves 1 BTC. Combined with 1.5 BTC in
3798    /// cash the sums are 0.5 total and 1 locked, leaving free at -0.5. Clamping the aggregate
3799    /// would report 0.5 locked and 0 free, dropping half the reservation.
3800    #[rstest]
3801    fn test_parse_account_entries_preserves_summed_amounts_across_mixed_sign_wallets() {
3802        let margin = FuturesAccount {
3803            account_type: KrakenFuturesAccountType::MarginAccount,
3804            currency: Some("xbt".to_string()),
3805            balances: [("xbt".to_string(), dec!(-1))].into_iter().collect(),
3806            currencies: AHashMap::new(),
3807            auxiliary: Some(FuturesAuxiliary {
3808                usd: None,
3809                pv: None,
3810                pnl: None,
3811                af: Some(dec!(-2)),
3812                funding: None,
3813            }),
3814            margin_requirements: None,
3815            portfolio_value: None,
3816            available_margin: None,
3817            initial_margin: None,
3818            maintenance_margin: None,
3819            pnl: None,
3820        };
3821
3822        let (balances, _) = entries_for(&[
3823            ("fi_xbtusd", margin),
3824            ("cash", cash_wallet(&[("xbt", dec!(1.5))])),
3825        ]);
3826
3827        let btc = balances
3828            .iter()
3829            .find(|b| b.currency.code.as_str() == "BTC")
3830            .expect("one BTC balance");
3831        assert_eq!(btc.total.as_decimal(), dec!(0.5));
3832        assert_eq!(
3833            btc.locked.as_decimal(),
3834            dec!(1),
3835            "the margin wallet's reservation must survive the aggregate"
3836        );
3837        assert_eq!(
3838            btc.free.as_decimal(),
3839            dec!(-0.5),
3840            "the shortfall must stay visible rather than clamp to zero"
3841        );
3842    }
3843
3844    /// A negative total keeps its reported `locked`, as a single balance always has.
3845    #[rstest]
3846    fn test_parse_account_entries_passes_a_negative_total_through() {
3847        let account = FuturesAccount {
3848            account_type: KrakenFuturesAccountType::MarginAccount,
3849            currency: Some("xbt".to_string()),
3850            balances: [("xbt".to_string(), dec!(-1))].into_iter().collect(),
3851            currencies: AHashMap::new(),
3852            auxiliary: Some(FuturesAuxiliary {
3853                usd: None,
3854                pv: None,
3855                pnl: None,
3856                af: Some(dec!(-0.4)),
3857                funding: None,
3858            }),
3859            margin_requirements: None,
3860            portfolio_value: None,
3861            available_margin: None,
3862            initial_margin: None,
3863            maintenance_margin: None,
3864            pnl: None,
3865        };
3866
3867        let (balances, _) = entries_for(&[("fi_xbtusd", account)]);
3868
3869        assert_eq!(balances.len(), 1);
3870        assert_eq!(balances[0].total.as_decimal(), dec!(-1));
3871        assert_eq!(balances[0].locked.as_decimal(), dec!(-0.6));
3872        assert_eq!(balances[0].free.as_decimal(), dec!(-0.4));
3873    }
3874
3875    /// A USD wallet balance keeps eight decimals rather than rounding to cents.
3876    #[rstest]
3877    fn test_parse_account_entries_keeps_usd_balance_at_eight_decimals() {
3878        let (balances, _) = entries_for(&[("cash", cash_wallet(&[("usd", dec!(1234.56789012))]))]);
3879
3880        let usd = balances
3881            .iter()
3882            .find(|b| b.currency.code.as_str() == "USD")
3883            .expect("one USD balance");
3884        assert_eq!(usd.currency.precision, 8);
3885        assert_eq!(usd.total.as_decimal(), dec!(1234.56789012));
3886    }
3887
3888    /// Margins are keyed by currency: a single-collateral wallet's in its `currency`, the flex
3889    /// wallet's in USD, so requirements in different currencies stay apart.
3890    #[rstest]
3891    fn test_parse_account_entries_keeps_margins_per_currency() {
3892        let mut flex = flex_wallet(&[], Some(dec!(10000)));
3893        flex.initial_margin = Some(dec!(500));
3894        flex.maintenance_margin = Some(dec!(250));
3895
3896        let single = FuturesAccount {
3897            account_type: KrakenFuturesAccountType::MarginAccount,
3898            currency: Some("xbt".to_string()),
3899            balances: [("xbt".to_string(), dec!(2))].into_iter().collect(),
3900            currencies: AHashMap::new(),
3901            auxiliary: None,
3902            margin_requirements: Some(FuturesMarginRequirements {
3903                im: Some(dec!(0.1)),
3904                mm: Some(dec!(0.05)),
3905                lt: None,
3906                tt: None,
3907            }),
3908            portfolio_value: None,
3909            available_margin: None,
3910            initial_margin: None,
3911            maintenance_margin: None,
3912            pnl: None,
3913        };
3914
3915        let (_, margins) = entries_for(&[("flex", flex), ("fi_xbtusd", single)]);
3916
3917        assert_eq!(
3918            margins.len(),
3919            2,
3920            "one margin entry per currency: {margins:?}"
3921        );
3922        let mut entries: Vec<(String, Decimal)> = margins
3923            .iter()
3924            .map(|m| (m.currency.code.to_string(), m.initial.as_decimal()))
3925            .collect();
3926        entries.sort();
3927        assert_eq!(
3928            entries,
3929            vec![
3930                ("BTC".to_string(), dec!(0.1)),
3931                ("USD".to_string(), dec!(500))
3932            ],
3933            "each currency keeps its own entry"
3934        );
3935    }
3936
3937    /// The wallet's available funds bound its own currency alone; another asset it holds has
3938    /// nothing reserved against it.
3939    #[rstest]
3940    fn test_parse_margin_account_balances_bound_locked_to_the_wallet_currency() {
3941        let wallet = FuturesAccount {
3942            account_type: KrakenFuturesAccountType::MarginAccount,
3943            currency: Some("xbt".to_string()),
3944            balances: [("xbt".to_string(), dec!(0.3)), ("xrp".to_string(), dec!(5))]
3945                .into_iter()
3946                .collect(),
3947            currencies: AHashMap::new(),
3948            auxiliary: Some(FuturesAuxiliary {
3949                usd: None,
3950                pv: None,
3951                pnl: None,
3952                af: Some(dec!(0.1)),
3953                funding: None,
3954            }),
3955            margin_requirements: None,
3956            portfolio_value: None,
3957            available_margin: None,
3958            initial_margin: None,
3959            maintenance_margin: None,
3960            pnl: None,
3961        };
3962
3963        let (balances, _) = entries_for(&[("fi_xbtusd", wallet)]);
3964
3965        let by_code = |code: &str| {
3966            balances
3967                .iter()
3968                .find(|b| b.currency.code.as_str() == code)
3969                .unwrap_or_else(|| panic!("{code} balance"))
3970        };
3971        assert_eq!(by_code("BTC").locked.as_decimal(), dec!(0.2));
3972        assert_eq!(by_code("XRP").locked.as_decimal(), dec!(0));
3973        assert_eq!(by_code("XRP").free.as_decimal(), dec!(5));
3974    }
3975
3976    /// Contract-symbol keys in `balances` are positions, not balances, and are skipped.
3977    #[rstest]
3978    fn test_parse_margin_account_balances_skip_contract_symbol_keys() {
3979        let wallet = FuturesAccount {
3980            account_type: KrakenFuturesAccountType::MarginAccount,
3981            currency: Some("xbt".to_string()),
3982            balances: [
3983                ("xbt".to_string(), dec!(0.5)),
3984                ("FI_XBTUSD_171215".to_string(), dec!(50000)),
3985                ("FI_XBTUSD_180615".to_string(), dec!(-15000)),
3986            ]
3987            .into_iter()
3988            .collect(),
3989            currencies: AHashMap::new(),
3990            auxiliary: None,
3991            margin_requirements: None,
3992            portfolio_value: None,
3993            available_margin: None,
3994            initial_margin: None,
3995            maintenance_margin: None,
3996            pnl: None,
3997        };
3998
3999        let (balances, _) = entries_for(&[("fi_xbtusd", wallet)]);
4000
4001        assert_eq!(balances.len(), 1, "{balances:?}");
4002        assert_eq!(balances[0].currency.code.as_str(), "BTC");
4003    }
4004
4005    /// A flex wallet reports its requirement in USD in the top-level `initialMargin` and
4006    /// `maintenanceMargin` fields, and both figures reach the account-wide entry.
4007    ///
4008    /// Kraken's documented `flex` wallet shape, with the two requirement figures set.
4009    #[rstest]
4010    fn test_parse_multi_collateral_margins_read_the_documented_fields() {
4011        let json = r#"{
4012            "type": "multiCollateralMarginAccount",
4013            "currencies": {
4014                "XBT": {"quantity": 0.1185308247, "value": 4998.721054420551, "collateral": 4886.49976674881, "available": 0.1185308247},
4015                "USD": {"quantity": 5000, "value": 5000, "collateral": 5000, "available": 5000}
4016            },
4017            "balanceValue": 9998.72,
4018            "portfolioValue": 9998.72,
4019            "collateralValue": 9886.5,
4020            "initialMargin": 500,
4021            "initialMarginWithOrders": 500,
4022            "maintenanceMargin": 250,
4023            "pnl": 0,
4024            "unrealizedFunding": 0,
4025            "totalUnrealized": 0,
4026            "totalUnrealizedAsMargin": 0,
4027            "marginEquity": 9886.5,
4028            "availableMargin": 9386.5
4029        }"#;
4030        let account: FuturesAccount = serde_json::from_str(json).unwrap();
4031
4032        let (_, margins) = entries_for(&[("flex", account)]);
4033
4034        assert_eq!(margins.len(), 1, "{margins:?}");
4035        assert_eq!(margins[0].currency.code.as_str(), "USD");
4036        assert_eq!(margins[0].initial.as_decimal(), dec!(500));
4037        assert_eq!(margins[0].maintenance.as_decimal(), dec!(250));
4038        assert_eq!(margins[0].instrument_id, None);
4039    }
4040
4041    /// A flex wallet with no requirement contributes no entry; one with a requirement contributes
4042    /// an account-wide USD entry, so the maintenance figure alone is enough as on the
4043    /// single-collateral wallet.
4044    #[rstest]
4045    #[case::none(None, None, 0)]
4046    #[case::initial_only(Some(dec!(100)), None, 1)]
4047    #[case::maintenance_only(None, Some(dec!(40)), 1)]
4048    fn test_parse_multi_collateral_margins_follow_the_requirement_gate(
4049        #[case] initial_margin: Option<Decimal>,
4050        #[case] maintenance: Option<Decimal>,
4051        #[case] expected: usize,
4052    ) {
4053        let mut flex = flex_wallet(&[("USD", dec!(1000))], Some(dec!(1000)));
4054        flex.initial_margin = initial_margin;
4055        flex.maintenance_margin = maintenance;
4056
4057        let (_, margins) = entries_for(&[("flex", flex)]);
4058
4059        assert_eq!(margins.len(), expected, "{margins:?}");
4060        for margin in &margins {
4061            assert_eq!(margin.currency.code.as_str(), "USD");
4062            assert_eq!(
4063                margin.instrument_id, None,
4064                "the requirement is account-wide"
4065            );
4066        }
4067    }
4068
4069    /// A single-collateral wallet's requirement is denominated in the wallet's `currency`.
4070    ///
4071    /// Kraken's documented `fi_xbtusd` wallet: `currency: xbt`, a funded `xbt` key, an `xrp: 0` key
4072    /// and two contract-symbol keys. The requirement is reported in BTC at eight decimals.
4073    #[rstest]
4074    fn test_parse_margin_account_margins_use_the_wallet_currency() {
4075        let json = r#"{
4076            "auxiliary": {"af": 100.73891563, "funding": 100.73891563, "pnl": 12.42134766, "pv": 153.73891563, "usd": 0},
4077            "balances": {"FI_XBTUSD_171215": "50000", "FI_XBTUSD_180615": "-15000", "xbt": "141.31756797", "xrp": "0"},
4078            "currency": "xbt",
4079            "marginRequirements": {"im": 52.8, "lt": 39.6, "mm": 23.76, "tt": 15.84},
4080            "triggerEstimates": {"im": 3110, "lt": 2890, "mm": 3000, "tt": 2830},
4081            "type": "marginAccount"
4082        }"#;
4083        let account: FuturesAccount = serde_json::from_str(json).unwrap();
4084
4085        let (balances, margins) = entries_for(&[("fi_xbtusd", account)]);
4086
4087        assert_eq!(margins.len(), 1, "{margins:?}");
4088        assert_eq!(margins[0].currency.code.as_str(), "BTC");
4089        assert_eq!(margins[0].currency.precision, 8);
4090        assert_eq!(margins[0].initial.as_decimal(), dec!(52.8));
4091        assert_eq!(margins[0].maintenance.as_decimal(), dec!(23.76));
4092        let btc = balances
4093            .iter()
4094            .find(|b| b.currency.code.as_str() == "BTC")
4095            .expect("BTC balance");
4096        assert_eq!(btc.total.as_decimal(), dec!(141.31756797));
4097    }
4098
4099    /// A requirement whose currency cannot be resolved is skipped rather than labeled by a guess.
4100    ///
4101    /// Without the `currency` field, or with an empty one, the funded `xbt` key beside dust in
4102    /// `xrp` is not evidence of the denomination, and an empty code must not reach the currency
4103    /// constructor.
4104    #[rstest]
4105    #[case::absent(None)]
4106    #[case::empty(Some(""))]
4107    #[case::blank(Some("  "))]
4108    fn test_parse_margin_account_margins_skip_a_wallet_whose_currency_is_unresolved(
4109        #[case] currency: Option<&str>,
4110    ) {
4111        let mut wallet = cash_wallet(&[("xbt", dec!(1.5)), ("xrp", Decimal::ZERO)]);
4112        wallet.account_type = KrakenFuturesAccountType::MarginAccount;
4113        wallet.currency = currency.map(str::to_string);
4114        wallet.margin_requirements = Some(FuturesMarginRequirements {
4115            im: Some(dec!(0.05)),
4116            mm: Some(dec!(0.025)),
4117            lt: None,
4118            tt: None,
4119        });
4120
4121        let (_, margins) = entries_for(&[("fi_xbtusd", wallet)]);
4122
4123        assert!(margins.is_empty(), "no guessed denomination: {margins:?}");
4124    }
4125
4126    /// Wallets sharing a currency sum into one margin entry.
4127    ///
4128    /// `MarginAccount` keys account-wide margins by currency, so two entries under one code would
4129    /// survive by iteration order instead.
4130    #[rstest]
4131    fn test_parse_account_entries_sums_margins_of_wallets_sharing_a_currency() {
4132        let requirement = |im: Decimal, mm: Decimal| {
4133            Some(FuturesMarginRequirements {
4134                im: Some(im),
4135                mm: Some(mm),
4136                lt: None,
4137                tt: None,
4138            })
4139        };
4140        let mut first = cash_wallet(&[("xbt", dec!(2))]);
4141        first.account_type = KrakenFuturesAccountType::MarginAccount;
4142        first.currency = Some("xbt".to_string());
4143        first.margin_requirements = requirement(dec!(0.1), dec!(0.05));
4144        let mut second = cash_wallet(&[("xbt", dec!(1))]);
4145        second.account_type = KrakenFuturesAccountType::MarginAccount;
4146        second.currency = Some("XBT".to_string());
4147        second.margin_requirements = requirement(dec!(0.02), dec!(0.01));
4148
4149        let (_, margins) = entries_for(&[("fi_a", first), ("fi_b", second)]);
4150
4151        assert_eq!(margins.len(), 1, "one entry per currency: {margins:?}");
4152        assert_eq!(margins[0].currency.code.as_str(), "BTC");
4153        assert_eq!(margins[0].initial.as_decimal(), dec!(0.12));
4154        assert_eq!(margins[0].maintenance.as_decimal(), dec!(0.06));
4155    }
4156
4157    /// An asset key the currency constructor rejects is skipped, not a panic.
4158    #[rstest]
4159    fn test_parse_account_entries_skips_an_empty_asset_key() {
4160        let (balances, _) =
4161            entries_for(&[("cash", cash_wallet(&[("", dec!(1)), ("xbt", dec!(2))]))]);
4162
4163        assert_eq!(balances.len(), 1, "{balances:?}");
4164        assert_eq!(balances[0].currency.code.as_str(), "BTC");
4165    }
4166
4167    #[rstest]
4168    fn test_parse_margin_account_margins() {
4169        let account = FuturesAccount {
4170            account_type: KrakenFuturesAccountType::MarginAccount,
4171            currency: Some("xbt".to_string()),
4172            balances: [("xbt".to_string(), dec!(2))].into_iter().collect(),
4173            currencies: AHashMap::new(),
4174            auxiliary: None,
4175            margin_requirements: Some(FuturesMarginRequirements {
4176                im: Some(dec!(100)),
4177                mm: Some(dec!(50)),
4178                lt: None,
4179                tt: None,
4180            }),
4181            portfolio_value: None,
4182            available_margin: None,
4183            initial_margin: None,
4184            maintenance_margin: None,
4185            pnl: None,
4186        };
4187
4188        let (_, margins) = entries_for(&[("wallet", account)]);
4189
4190        assert_eq!(margins.len(), 1);
4191        let margin = &margins[0];
4192        assert_eq!(margin.currency.code.as_str(), "BTC");
4193        assert_eq!(margin.initial.as_decimal(), dec!(100));
4194        assert_eq!(margin.maintenance.as_decimal(), dec!(50));
4195    }
4196
4197    #[rstest]
4198    fn test_parse_margin_account_margins_no_requirements() {
4199        let account = FuturesAccount {
4200            account_type: KrakenFuturesAccountType::MarginAccount,
4201            currency: None,
4202            balances: AHashMap::new(),
4203            currencies: AHashMap::new(),
4204            auxiliary: None,
4205            margin_requirements: None,
4206            portfolio_value: None,
4207            available_margin: None,
4208            initial_margin: None,
4209            maintenance_margin: None,
4210            pnl: None,
4211        };
4212
4213        let (_, margins) = entries_for(&[("wallet", account)]);
4214
4215        assert_eq!(margins.len(), 0);
4216    }
4217
4218    #[rstest]
4219    fn test_parse_multi_collateral_balances() {
4220        let mut currencies = AHashMap::new();
4221        currencies.insert(
4222            "BTC".to_string(),
4223            FuturesFlexCurrency {
4224                quantity: dec!(1.5),
4225                value: None,
4226                collateral: None,
4227                available: Some(dec!(1.2)),
4228            },
4229        );
4230
4231        let account = FuturesAccount {
4232            account_type: KrakenFuturesAccountType::MultiCollateralMarginAccount,
4233            currency: None,
4234            balances: AHashMap::new(),
4235            currencies,
4236            auxiliary: None,
4237            margin_requirements: None,
4238            portfolio_value: Some(dec!(50000)),
4239            available_margin: Some(dec!(45000)),
4240            initial_margin: None,
4241            maintenance_margin: None,
4242            pnl: None,
4243        };
4244
4245        let (balances, _) = entries_for(&[("wallet", account)]);
4246
4247        // BTC balance + USD portfolio balance
4248        assert_eq!(balances.len(), 2);
4249    }
4250
4251    #[rstest]
4252    fn test_parse_margin_account_balances_preserves_exact_values() {
4253        let mut bals = AHashMap::new();
4254        bals.insert("XBT".to_string(), dec!(10.00000003));
4255
4256        let account = FuturesAccount {
4257            account_type: KrakenFuturesAccountType::MarginAccount,
4258            currency: Some("xbt".to_string()),
4259            balances: bals,
4260            currencies: AHashMap::new(),
4261            auxiliary: Some(FuturesAuxiliary {
4262                usd: None,
4263                pv: None,
4264                pnl: None,
4265                af: Some(dec!(0.00000004)),
4266                funding: None,
4267            }),
4268            margin_requirements: None,
4269            portfolio_value: None,
4270            available_margin: None,
4271            initial_margin: None,
4272            maintenance_margin: None,
4273            pnl: None,
4274        };
4275
4276        let (balances, _) = entries_for(&[("wallet", account)]);
4277
4278        assert_eq!(balances.len(), 1);
4279        let balance = &balances[0];
4280        assert_eq!(balance.total.as_decimal(), dec!(10.00000003));
4281        assert_eq!(balance.locked.as_decimal(), dec!(9.99999999));
4282        assert_eq!(balance.free.as_decimal(), dec!(0.00000004));
4283        assert_eq!(balance.total, balance.locked + balance.free);
4284    }
4285
4286    #[rstest]
4287    fn test_parse_cash_account_balances() {
4288        let mut bals = AHashMap::new();
4289        bals.insert("ETH".to_string(), dec!(10));
4290        bals.insert("BTC".to_string(), Decimal::ZERO);
4291
4292        let account = FuturesAccount {
4293            account_type: KrakenFuturesAccountType::CashAccount,
4294            currency: None,
4295            balances: bals,
4296            currencies: AHashMap::new(),
4297            auxiliary: None,
4298            margin_requirements: None,
4299            portfolio_value: None,
4300            available_margin: None,
4301            initial_margin: None,
4302            maintenance_margin: None,
4303            pnl: None,
4304        };
4305
4306        let (balances, _) = entries_for(&[("wallet", account)]);
4307
4308        assert_eq!(
4309            balances.len(),
4310            2,
4311            "a wallet listed at zero is reported: {balances:?}"
4312        );
4313        let eth = balances
4314            .iter()
4315            .find(|b| b.currency.code.as_str() == "ETH")
4316            .expect("ETH balance");
4317        assert_eq!(eth.total.as_decimal(), dec!(10));
4318        assert_eq!(eth.locked.as_decimal(), Decimal::ZERO);
4319        let btc = balances
4320            .iter()
4321            .find(|b| b.currency.code.as_str() == "BTC")
4322            .expect("BTC balance");
4323        assert_eq!(btc.total.as_decimal(), Decimal::ZERO);
4324        assert_eq!(btc.free.as_decimal(), Decimal::ZERO);
4325    }
4326
4327    /// A flex collateral currency at zero quantity is reported at zero.
4328    #[rstest]
4329    fn test_parse_multi_collateral_balances_reports_zero_quantity() {
4330        let (balances, _) = entries_for(&[("flex", flex_wallet(&[("XBT", Decimal::ZERO)], None))]);
4331
4332        assert_eq!(balances.len(), 1, "{balances:?}");
4333        assert_eq!(balances[0].currency.code.as_str(), "BTC");
4334        assert_eq!(balances[0].total.as_decimal(), Decimal::ZERO);
4335        assert_eq!(balances[0].free.as_decimal(), Decimal::ZERO);
4336    }
4337
4338    /// A single-collateral wallet drawn down to zero is reported at zero.
4339    #[rstest]
4340    fn test_parse_margin_account_balances_reports_zero_wallet() {
4341        let mut wallet = cash_wallet(&[("xbt", Decimal::ZERO)]);
4342        wallet.account_type = KrakenFuturesAccountType::MarginAccount;
4343
4344        let (balances, _) = entries_for(&[("fi_xbtusd", wallet)]);
4345
4346        assert_eq!(balances.len(), 1, "{balances:?}");
4347        assert_eq!(balances[0].currency.code.as_str(), "BTC");
4348        assert_eq!(balances[0].total.as_decimal(), Decimal::ZERO);
4349        assert_eq!(balances[0].free.as_decimal(), Decimal::ZERO);
4350    }
4351
4352    /// An empty wallet joins the per-currency sum, so it cannot displace a funded wallet.
4353    #[rstest]
4354    fn test_parse_account_entries_zero_wallet_does_not_displace_a_funded_one() {
4355        let mut margin = cash_wallet(&[("xbt", dec!(1.5))]);
4356        margin.account_type = KrakenFuturesAccountType::MarginAccount;
4357
4358        let (balances, _) = entries_for(&[
4359            ("cash", cash_wallet(&[("xbt", Decimal::ZERO)])),
4360            ("fi_xbtusd", margin),
4361            ("flex", flex_wallet(&[("XBT", Decimal::ZERO)], None)),
4362        ]);
4363
4364        assert_eq!(balances.len(), 1, "one BTC balance: {balances:?}");
4365        assert_eq!(balances[0].currency.code.as_str(), "BTC");
4366        assert_eq!(balances[0].total.as_decimal(), dec!(1.5));
4367        assert_eq!(balances[0].free.as_decimal(), dec!(1.5));
4368    }
4369
4370    /// An asset every wallet lists at zero is reported once, at zero.
4371    #[rstest]
4372    fn test_parse_account_entries_reports_an_asset_all_wallets_hold_at_zero() {
4373        let mut margin = cash_wallet(&[("xbt", Decimal::ZERO)]);
4374        margin.account_type = KrakenFuturesAccountType::MarginAccount;
4375
4376        let (balances, _) = entries_for(&[
4377            ("cash", cash_wallet(&[("xbt", Decimal::ZERO)])),
4378            ("fi_xbtusd", margin),
4379            ("flex", flex_wallet(&[("XBT", Decimal::ZERO)], None)),
4380        ]);
4381
4382        assert_eq!(balances.len(), 1, "one BTC balance: {balances:?}");
4383        assert_eq!(balances[0].currency.code.as_str(), "BTC");
4384        assert_eq!(balances[0].total.as_decimal(), Decimal::ZERO);
4385        assert_eq!(balances[0].locked.as_decimal(), Decimal::ZERO);
4386        assert_eq!(balances[0].free.as_decimal(), Decimal::ZERO);
4387    }
4388
4389    #[rstest]
4390    #[case(None, None)]
4391    #[case(Some(TriggerType::Default), Some(KrakenTriggerSignal::Last))]
4392    #[case(Some(TriggerType::LastPrice), Some(KrakenTriggerSignal::Last))]
4393    #[case(Some(TriggerType::MarkPrice), Some(KrakenTriggerSignal::Mark))]
4394    #[case(Some(TriggerType::IndexPrice), Some(KrakenTriggerSignal::Index))]
4395    fn test_build_send_order_params_maps_supported_trigger_signals(
4396        #[case] trigger_type: Option<TriggerType>,
4397        #[case] expected_signal: Option<KrakenTriggerSignal>,
4398    ) {
4399        let client = KrakenFuturesHttpClient::default();
4400        let instrument_id = cache_test_futures_instrument(&client);
4401
4402        let params = client
4403            .build_send_order_params(
4404                instrument_id,
4405                ClientOrderId::new("futures-trigger"),
4406                OrderSide::Buy,
4407                OrderType::StopMarket,
4408                Quantity::from("1"),
4409                TimeInForce::Gtc,
4410                None,
4411                Some(Price::from("45000")),
4412                trigger_type,
4413                false,
4414                false,
4415            )
4416            .unwrap();
4417
4418        assert_eq!(params.trigger_signal, expected_signal);
4419    }
4420
4421    #[rstest]
4422    fn test_build_send_order_params_rejects_unsupported_trigger_signal() {
4423        let client = KrakenFuturesHttpClient::default();
4424        let instrument_id = cache_test_futures_instrument(&client);
4425
4426        let error = client
4427            .build_send_order_params(
4428                instrument_id,
4429                ClientOrderId::new("futures-trigger-invalid"),
4430                OrderSide::Buy,
4431                OrderType::StopMarket,
4432                Quantity::from("1"),
4433                TimeInForce::Gtc,
4434                None,
4435                Some(Price::from("45000")),
4436                Some(TriggerType::BidAsk),
4437                false,
4438                false,
4439            )
4440            .unwrap_err();
4441
4442        assert!(
4443            error
4444                .to_string()
4445                .contains("Unsupported trigger type for Kraken Futures")
4446        );
4447    }
4448
4449    /// A history page of two rows on `PF_XBTUSD`; the first row's order type is `first_order_type`
4450    /// and the page hands back `continuation_token` when one is given.
4451    fn history_page(first_order_type: &str, continuation_token: Option<&str>) -> String {
4452        let token = continuation_token
4453            .map(|token| format!(r#","continuationToken":"{token}""#))
4454            .unwrap_or_default();
4455        format!(
4456            r#"{{"elements":[{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderPlaced":{{"order":{{"uid":"H-SKIP-1","tradeable":"PF_XBTUSD","direction":"Sell","quantity":"3","filled":"1","limitPrice":"70000","orderType":"{first_order_type}","clientId":"cl-1","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":1680876930250}}}}}}}},{{"uid":"e2","timestamp":1680877245500,"event":{{"OrderPlaced":{{"order":{{"uid":"H-KEEP-2","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"2","filled":"0.5","limitPrice":"69500","orderType":"Limit","clientId":"cl-2","reduceOnly":false,"timestamp":1680877245500,"lastUpdateTimestamp":1680877245500}}}}}}}}]{token}}}"#
4457        )
4458    }
4459
4460    /// A client against a mock venue with no open orders whose order history serves `history`,
4461    /// with `header_token` in the `Next-Continuation-Token` header when one is given.
4462    async fn history_test_client(
4463        history: Arc<RwLock<String>>,
4464        header_token: Option<&'static str>,
4465    ) -> KrakenFuturesHttpClient {
4466        history_test_client_with_open_orders(
4467            r#"{"result":"success","openOrders":[]}"#.to_string(),
4468            history,
4469            header_token,
4470        )
4471        .await
4472    }
4473
4474    /// As [`history_test_client`], for a venue serving `open_orders` as its open-orders response.
4475    async fn history_test_client_with_open_orders(
4476        open_orders: String,
4477        history: Arc<RwLock<String>>,
4478        header_token: Option<&'static str>,
4479    ) -> KrakenFuturesHttpClient {
4480        use axum::{
4481            Router, body::Body, extract::State, http::header, response::Response, routing::any,
4482        };
4483
4484        let app = Router::new()
4485            .route(
4486                "/derivatives/api/v3/openorders",
4487                any(move || {
4488                    let open_orders = open_orders.clone();
4489                    async move { ([(header::CONTENT_TYPE, "application/json")], open_orders) }
4490                }),
4491            )
4492            .route(
4493                "/api/history/v3/orders",
4494                any(
4495                    move |State(history): State<Arc<RwLock<String>>>| async move {
4496                        let mut response =
4497                            Response::builder().header(header::CONTENT_TYPE, "application/json");
4498
4499                        if let Some(token) = header_token {
4500                            response = response.header(NEXT_CONTINUATION_TOKEN_HEADER, token);
4501                        }
4502                        response.body(Body::from(history.read().clone())).unwrap()
4503                    },
4504                ),
4505            )
4506            .with_state(history);
4507        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4508        let addr = listener.local_addr().unwrap();
4509        tokio::spawn(async move {
4510            axum::serve(listener, app).await.unwrap();
4511        });
4512
4513        KrakenFuturesHttpClient::with_credentials(
4514            "test".to_string(),
4515            "test".to_string(),
4516            KrakenEnvironment::Live,
4517            Some(format!("http://{addr}")),
4518            10,
4519            None,
4520            None,
4521            None,
4522            None,
4523            10,
4524        )
4525        .unwrap()
4526    }
4527
4528    /// A page that hands back a continuation token, in the body or only in the
4529    /// `Next-Continuation-Token` header, leaves events of the window unread, so the read reports
4530    /// the page's rows and marks the set incomplete; without a token the same page reads complete.
4531    #[rstest]
4532    #[case::body_token(Some("c2ltYjE3OA=="), None, false)]
4533    #[case::header_token(None, Some("c2ltYjE3OA=="), false)]
4534    #[case::no_token(None, None, true)]
4535    #[tokio::test]
4536    async fn test_request_order_status_reports_marks_a_page_with_a_continuation_token_incomplete(
4537        #[case] body_token: Option<&str>,
4538        #[case] header_token: Option<&'static str>,
4539        #[case] expected_complete: bool,
4540    ) {
4541        let history = Arc::new(RwLock::new(history_page("Limit", body_token)));
4542        let client = history_test_client(history, header_token).await;
4543        cache_test_futures_instrument(&client);
4544
4545        let (reports, coverage) = client
4546            .request_order_status_reports_checked(
4547                AccountId::from("KRAKEN-001"),
4548                None,
4549                None,
4550                None,
4551                false,
4552            )
4553            .await
4554            .unwrap();
4555
4556        assert_eq!(coverage.is_complete(), expected_complete);
4557        assert_eq!(
4558            reports
4559                .iter()
4560                .map(|report| report.venue_order_id.as_str())
4561                .collect::<Vec<_>>(),
4562            vec!["H-SKIP-1", "H-KEEP-2"],
4563            "the page's rows are reported either way"
4564        );
4565    }
4566
4567    /// An edit that resizes the order sends its size as the order's total, fills included, since
4568    /// the venue reads a bare size as the open size, on the single and the batch edit alike; a
4569    /// price-only edit sends no size and no mode.
4570    #[rstest]
4571    #[case::resize(Some("5"), Some("ABSOLUTE"))]
4572    #[case::price_only(None, None)]
4573    #[tokio::test]
4574    async fn test_build_edit_order_params_sends_a_size_as_the_total(
4575        #[case] size: Option<&str>,
4576        #[case] expected_qty_mode: Option<&str>,
4577    ) {
4578        let client = history_test_client(Arc::new(RwLock::new(String::new())), None).await;
4579        let instrument_id = cache_test_futures_instrument(&client);
4580
4581        let params = client
4582            .build_edit_order_params(
4583                instrument_id,
4584                None,
4585                Some(VenueOrderId::from("V-EDIT-1")),
4586                size.map(Quantity::from),
4587                Some(Price::from("70000")),
4588                None,
4589            )
4590            .unwrap();
4591
4592        let form: Vec<(String, String)> =
4593            serde_urlencoded::from_str(&serde_urlencoded::to_string(&params).unwrap()).unwrap();
4594        let form_field = |name: &str| {
4595            form.iter()
4596                .find(|(key, _)| key == name)
4597                .map(|(_, value)| value.as_str())
4598        };
4599        assert_eq!(form_field("size"), size, "{form:?}");
4600        assert_eq!(form_field("qtyMode"), expected_qty_mode, "{form:?}");
4601
4602        let item =
4603            serde_json::to_value(KrakenFuturesBatchEditItem::from_params(params, "tag-1")).unwrap();
4604        let item_field = |name: &str| item.get(name).and_then(|value| value.as_str());
4605        assert_eq!(item_field("size"), size, "{item}");
4606        assert_eq!(item_field("qtyMode"), expected_qty_mode, "{item}");
4607    }
4608
4609    /// A closed order does not reopen: a refused edit logged after the cancel carries the order as
4610    /// it stood before the cancel, so the order is reported canceled although the refusal is
4611    /// stamped later.
4612    #[rstest]
4613    #[tokio::test]
4614    async fn test_request_order_status_reports_keep_a_closed_order_closed_after_a_refused_edit() {
4615        let order = |last_update_ms: u64| {
4616            format!(
4617                r#"{{"uid":"H-CLOSED","tradeable":"PF_XBTUSD","direction":"Buy","quantity":"1","filled":"0","limitPrice":"70000","orderType":"Limit","clientId":"","reduceOnly":false,"timestamp":1680876930250,"lastUpdateTimestamp":{last_update_ms}}}"#
4618            )
4619        };
4620        // Newest first, as the venue sorts: the refused edit at T2, the cancel at T1, the
4621        // placement at T0.
4622        let page = format!(
4623            r#"{{"elements":[{{"uid":"e3","timestamp":1680877400000,"event":{{"OrderEditRejected":{{"oldOrder":{},"reason":"order_for_edit_not_found"}}}}}},{{"uid":"e2","timestamp":1680877300000,"event":{{"OrderCancelled":{{"order":{},"reason":"cancelled_by_user"}}}}}},{{"uid":"e1","timestamp":1680876930250,"event":{{"OrderPlaced":{{"order":{},"reason":"new_user_order"}}}}}}]}}"#,
4624            order(1680876930250),
4625            order(1680877300000),
4626            order(1680876930250),
4627        );
4628        let client = history_test_client(Arc::new(RwLock::new(page)), None).await;
4629        cache_test_futures_instrument(&client);
4630
4631        let (reports, coverage) = client
4632            .request_order_status_reports_checked(
4633                AccountId::from("KRAKEN-001"),
4634                None,
4635                None,
4636                None,
4637                false,
4638            )
4639            .await
4640            .unwrap();
4641
4642        assert!(coverage.is_complete());
4643        assert_eq!(reports.len(), 1, "{reports:?}");
4644        assert_eq!(reports[0].venue_order_id, VenueOrderId::from("H-CLOSED"));
4645        assert_eq!(reports[0].order_status, OrderStatus::Canceled);
4646    }
4647
4648    /// A history row the projection cannot represent marks the checked read incomplete while
4649    /// the rows it can represent are still reported.
4650    #[rstest]
4651    #[tokio::test]
4652    async fn test_request_order_status_reports_marks_the_set_incomplete_for_a_skipped_history_row()
4653    {
4654        let history = Arc::new(RwLock::new(history_page("Limit", None)));
4655        let client = history_test_client(history.clone(), None).await;
4656        let instrument_id = cache_test_futures_instrument(&client);
4657        let account_id = AccountId::from("KRAKEN-001");
4658
4659        // Control: the same page with a decodable type reads complete, so the flag below is
4660        // driven by the undecodable type rather than by the page itself.
4661        let (control, coverage) = client
4662            .request_order_status_reports_checked(account_id, None, None, None, false)
4663            .await
4664            .unwrap();
4665        assert!(
4666            coverage.is_complete(),
4667            "the control must be complete, or the skip proves nothing"
4668        );
4669        assert_eq!(control.len(), 2);
4670
4671        *history.write() = history_page("Unknown", None);
4672        let (reports, coverage) = client
4673            .request_order_status_reports_checked(account_id, None, None, None, false)
4674            .await
4675            .unwrap();
4676
4677        assert!(
4678            !coverage.is_complete(),
4679            "a skipped history row must leave the set incomplete"
4680        );
4681        assert_eq!(reports.len(), 1);
4682        let report = &reports[0];
4683        assert_eq!(report.venue_order_id, VenueOrderId::from("H-KEEP-2"));
4684        assert_eq!(report.instrument_id, instrument_id);
4685        assert_eq!(report.account_id, account_id);
4686        assert_eq!(report.client_order_id, Some(ClientOrderId::from("cl-2")));
4687        assert_eq!(report.order_side, Some(OrderSide::Buy));
4688        assert_eq!(report.order_type, OrderType::Limit);
4689        assert_eq!(report.quantity, Quantity::from("2"));
4690        assert_eq!(report.filled_qty, Quantity::from("0.5"));
4691        assert_eq!(report.price, Some(Price::from("69500")));
4692    }
4693
4694    /// The order history request asks for the newest events first rather than relying on the
4695    /// venue default, since a page with a continuation token is read as reaching back to its
4696    /// oldest event, and for the largest page, since a read takes only one.
4697    #[rstest]
4698    #[tokio::test]
4699    async fn test_get_order_events_asks_for_a_full_page_of_the_newest_events() {
4700        use axum::{Router, extract::RawQuery, routing::any};
4701
4702        let query: Arc<RwLock<Option<String>>> = Arc::new(RwLock::new(None));
4703        let recorded = query.clone();
4704        let app = Router::new().route(
4705            "/api/history/v3/orders",
4706            any(move |RawQuery(raw): RawQuery| {
4707                let recorded = recorded.clone();
4708                async move {
4709                    *recorded.write() = raw;
4710                    r#"{"elements":[]}"#
4711                }
4712            }),
4713        );
4714        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4715        let addr = listener.local_addr().unwrap();
4716        tokio::spawn(async move {
4717            axum::serve(listener, app).await.unwrap();
4718        });
4719        let client = KrakenFuturesHttpClient::with_credentials(
4720            "test".to_string(),
4721            "test".to_string(),
4722            KrakenEnvironment::Live,
4723            Some(format!("http://{addr}")),
4724            10,
4725            None,
4726            None,
4727            None,
4728            None,
4729            10,
4730        )
4731        .unwrap();
4732
4733        client
4734            .inner
4735            .get_order_events(None, None, None)
4736            .await
4737            .unwrap();
4738
4739        let query = query.read().clone().unwrap_or_default();
4740        assert!(
4741            query.split('&').any(|param| param == "sort=desc"),
4742            "{query}"
4743        );
4744        assert!(
4745            query.split('&').any(|param| param == "count=1000"),
4746            "{query}"
4747        );
4748    }
4749
4750    const HISTORY_T0: i64 = 1_680_877_000_000;
4751    const HISTORY_T1: i64 = HISTORY_T0 + 1_000;
4752    const HISTORY_T2: i64 = HISTORY_T0 + 2_000;
4753    const HISTORY_T3: i64 = HISTORY_T0 + 3_000;
4754
4755    /// A history order of `uid` on `tradeable` with its own stamp at `own_ms`, with `fields`
4756    /// standing in for the quantity and order type.
4757    fn history_order(uid: &str, tradeable: &str, own_ms: i64, fields: &str) -> String {
4758        format!(
4759            r#"{{"uid":"{uid}","tradeable":"{tradeable}","direction":"Buy","filled":"0","limitPrice":"70000","clientId":"","reduceOnly":false,"timestamp":{HISTORY_T0},"lastUpdateTimestamp":{own_ms},{fields}}}"#
4760        )
4761    }
4762
4763    /// An element of `kind` at `event_ms` carrying `order` where the kind documents it.
4764    fn history_element(kind: &str, event_ms: i64, order: &str) -> String {
4765        let position = match kind {
4766            "OrderUpdated" => "newOrder",
4767            "OrderEditRejected" => "oldOrder",
4768            _ => "order",
4769        };
4770        format!(
4771            r#"{{"uid":"e-{event_ms}","timestamp":{event_ms},"event":{{"{kind}":{{"{position}":{order}}}}}}}"#
4772        )
4773    }
4774
4775    /// A readable row of `uid` on the test instrument.
4776    fn readable_row(kind: &str, uid: &str, event_ms: i64, own_ms: i64) -> String {
4777        let order = history_order(
4778            uid,
4779            "PF_XBTUSD",
4780            own_ms,
4781            r#""quantity":"3","orderType":"Limit""#,
4782        );
4783        history_element(kind, event_ms, &order)
4784    }
4785
4786    /// A row whose quantity does not decode, so the projection never sees its state.
4787    fn unreadable_row(uid: &str, event_ms: i64) -> String {
4788        let order = history_order(
4789            uid,
4790            "PF_XBTUSD",
4791            event_ms,
4792            r#""quantity":"oops","orderType":"Limit""#,
4793        );
4794        history_element("OrderCancelled", event_ms, &order)
4795    }
4796
4797    /// A row that decodes but fails to parse into a report, its quantity negative.
4798    fn unparsable_row(uid: &str, event_ms: i64) -> String {
4799        let order = history_order(
4800            uid,
4801            "PF_XBTUSD",
4802            event_ms,
4803            r#""quantity":"-1","orderType":"Limit""#,
4804        );
4805        history_element("OrderCancelled", event_ms, &order)
4806    }
4807
4808    /// A row the projection cannot represent, its type reported as `Unknown`.
4809    fn unrepresentable_row(uid: &str, event_ms: i64) -> String {
4810        let order = history_order(
4811            uid,
4812            "PF_XBTUSD",
4813            event_ms,
4814            r#""quantity":"3","orderType":"Unknown""#,
4815        );
4816        history_element("OrderCancelled", event_ms, &order)
4817    }
4818
4819    /// A row that decodes, on a contract the client cannot resolve.
4820    fn unresolved_row(uid: &str, event_ms: i64) -> String {
4821        let order = history_order(
4822            uid,
4823            "PF_NOPE",
4824            event_ms,
4825            r#""quantity":"3","orderType":"Limit""#,
4826        );
4827        history_element("OrderCancelled", event_ms, &order)
4828    }
4829
4830    /// A row of a kind the documentation does not list.
4831    fn undocumented_row(uid: &str, event_ms: i64) -> String {
4832        let order = history_order(
4833            uid,
4834            "PF_XBTUSD",
4835            event_ms,
4836            r#""quantity":"3","orderType":"Limit""#,
4837        );
4838        history_element("OrderSomethingNew", event_ms, &order)
4839    }
4840
4841    /// An undecodable row naming only what it is given.
4842    fn partial_row(uid: Option<&str>, tradeable: Option<&str>, event_ms: i64) -> String {
4843        let uid = uid
4844            .map(|uid| format!(r#""uid":"{uid}","#))
4845            .unwrap_or_default();
4846        let tradeable = tradeable
4847            .map(|tradeable| format!(r#""tradeable":"{tradeable}","#))
4848            .unwrap_or_default();
4849        history_element(
4850            "OrderCancelled",
4851            event_ms,
4852            &format!(r#"{{{uid}{tradeable}"quantity":"oops"}}"#),
4853        )
4854    }
4855
4856    fn history_json(rows: &[String]) -> String {
4857        format!(r#"{{"elements":[{}]}}"#, rows.join(","))
4858    }
4859
4860    fn cache_futures_contract(client: &KrakenFuturesHttpClient, raw_symbol: &str) {
4861        client.cache_instrument(InstrumentAny::CryptoPerpetual(
4862            CryptoPerpetual::builder()
4863                .instrument_id(InstrumentId::from(format!("{raw_symbol}.KRAKEN").as_str()))
4864                .raw_symbol(Symbol::new(raw_symbol))
4865                .base_currency(Currency::BTC())
4866                .quote_currency(Currency::USD())
4867                .settlement_currency(Currency::USD())
4868                .is_inverse(false)
4869                .price_precision(0)
4870                .size_precision(4)
4871                .price_increment(Price::from("1"))
4872                .size_increment(Quantity::from("0.0001"))
4873                .ts_event(0.into())
4874                .ts_init(0.into())
4875                .build()
4876                .unwrap(),
4877        ));
4878    }
4879
4880    /// An open-orders response with one resting buy per `(order_id, symbol)`.
4881    fn open_orders_json(rows: &[(&str, &str)]) -> String {
4882        let orders: Vec<String> = rows
4883            .iter()
4884            .map(|(order_id, symbol)| {
4885                format!(
4886                    r#"{{"order_id":"{order_id}","symbol":"{symbol}","side":"buy","orderType":"lmt","limitPrice":70000,"unfilledSize":3,"receivedTime":"2023-04-07T14:15:30.250Z","status":"untouched","filledSize":0,"reduceOnly":false,"lastUpdateTime":"2023-04-07T14:15:30.250Z"}}"#
4887                )
4888            })
4889            .collect();
4890        format!(
4891            r#"{{"result":"success","openOrders":[{}]}}"#,
4892            orders.join(",")
4893        )
4894    }
4895
4896    /// An order read of `rows` against a venue listing `open_orders`, with `PF_XBTUSD` and
4897    /// `PF_ETHUSD` in the cache.
4898    async fn read_history(
4899        open_orders: &[(&str, &str)],
4900        rows: &[String],
4901        scope: Option<&str>,
4902    ) -> (Vec<OrderStatusReport>, ReportCoverage) {
4903        let client = history_test_client_with_open_orders(
4904            open_orders_json(open_orders),
4905            Arc::new(RwLock::new(history_json(rows))),
4906            None,
4907        )
4908        .await;
4909        cache_futures_contract(&client, "PF_XBTUSD");
4910        cache_futures_contract(&client, "PF_ETHUSD");
4911
4912        client
4913            .request_order_status_reports_checked(
4914                AccountId::from("KRAKEN-001"),
4915                scope.map(|symbol| InstrumentId::from(format!("{symbol}.KRAKEN").as_str())),
4916                None,
4917                None,
4918                false,
4919            )
4920            .await
4921            .unwrap()
4922    }
4923
4924    fn report_status(reports: &[OrderStatusReport], uid: &str) -> Option<OrderStatus> {
4925        reports
4926            .iter()
4927            .find(|report| report.venue_order_id.as_str() == uid)
4928            .map(|report| report.order_status)
4929    }
4930
4931    fn rules_out(coverage: &ReportCoverage, uid: &str) -> bool {
4932        coverage.rules_out(Some(VenueOrderId::from(uid)), None)
4933    }
4934
4935    /// An order is reported only from a state no unread row of the order is as new as, measured
4936    /// against the state the fold chose, and a state other than a cancel or reject stamped before
4937    /// its event counts from that earlier stamp. Withheld or not, the read is incomplete, the order
4938    /// is not ruled out, and a sibling on the page is still reported and another order still ruled
4939    /// out.
4940    #[rstest]
4941    #[case::newer(
4942        vec![unreadable_row("H-O", HISTORY_T2), readable_row("OrderPlaced", "H-O", HISTORY_T1, HISTORY_T1)],
4943        None
4944    )]
4945    #[case::tied(
4946        vec![unreadable_row("H-O", HISTORY_T1), readable_row("OrderPlaced", "H-O", HISTORY_T1, HISTORY_T1)],
4947        None
4948    )]
4949    #[case::no_usable_stamp(
4950        vec![readable_row("OrderPlaced", "H-O", HISTORY_T1, HISTORY_T1), unreadable_row("H-O", -1)],
4951        None
4952    )]
4953    #[case::only_row(vec![unreadable_row("H-O", HISTORY_T1)], None)]
4954    #[case::unparsable_newer(
4955        vec![unparsable_row("H-O", HISTORY_T2), readable_row("OrderPlaced", "H-O", HISTORY_T1, HISTORY_T1)],
4956        None
4957    )]
4958    #[case::unrepresentable_newer(
4959        vec![unrepresentable_row("H-O", HISTORY_T2), readable_row("OrderPlaced", "H-O", HISTORY_T1, HISTORY_T1)],
4960        None
4961    )]
4962    #[case::unresolved_newer(
4963        vec![unresolved_row("H-O", HISTORY_T2), readable_row("OrderPlaced", "H-O", HISTORY_T1, HISTORY_T1)],
4964        None
4965    )]
4966    #[case::closed_older(
4967        vec![unreadable_row("H-O", HISTORY_T2), readable_row("OrderCancelled", "H-O", HISTORY_T1, HISTORY_T0)],
4968        None
4969    )]
4970    #[case::between_closed_and_later_open(
4971        vec![
4972            readable_row("OrderEditRejected", "H-O", HISTORY_T3, HISTORY_T0),
4973            unreadable_row("H-O", HISTORY_T2),
4974            readable_row("OrderCancelled", "H-O", HISTORY_T1, HISTORY_T1),
4975        ],
4976        None
4977    )]
4978    #[case::unreadable_cancel_before_refused_edit(
4979        vec![readable_row("OrderEditRejected", "H-O", HISTORY_T3, HISTORY_T1), unreadable_row("H-O", HISTORY_T2)],
4980        None
4981    )]
4982    #[case::update_stamped_before_the_unread_row(
4983        vec![readable_row("OrderUpdated", "H-O", HISTORY_T3, HISTORY_T1), unreadable_row("H-O", HISTORY_T2)],
4984        None
4985    )]
4986    #[case::older(
4987        vec![readable_row("OrderUpdated", "H-O", HISTORY_T2, HISTORY_T2), unreadable_row("H-O", HISTORY_T1)],
4988        Some(OrderStatus::Accepted)
4989    )]
4990    #[case::older_than_closed(
4991        vec![readable_row("OrderCancelled", "H-O", HISTORY_T2, HISTORY_T0), unreadable_row("H-O", HISTORY_T1)],
4992        Some(OrderStatus::Canceled)
4993    )]
4994    #[case::older_than_rejected(
4995        vec![readable_row("OrderRejected", "H-O", HISTORY_T2, HISTORY_T0), unreadable_row("H-O", HISTORY_T1)],
4996        Some(OrderStatus::Rejected)
4997    )]
4998    #[case::before_closed(
4999        vec![
5000            readable_row("OrderEditRejected", "H-O", HISTORY_T3, HISTORY_T0),
5001            readable_row("OrderCancelled", "H-O", HISTORY_T1, HISTORY_T1),
5002            unreadable_row("H-O", HISTORY_T0),
5003        ],
5004        Some(OrderStatus::Canceled)
5005    )]
5006    #[case::before_refused_edit_state(
5007        vec![readable_row("OrderEditRejected", "H-O", HISTORY_T3, HISTORY_T1), unreadable_row("H-O", HISTORY_T0)],
5008        Some(OrderStatus::Accepted)
5009    )]
5010    #[tokio::test]
5011    async fn test_request_order_status_reports_withhold_an_order_from_an_older_state(
5012        #[case] mut rows: Vec<String>,
5013        #[case] expected: Option<OrderStatus>,
5014    ) {
5015        rows.push(readable_row(
5016            "OrderPlaced",
5017            "H-SIBLING",
5018            HISTORY_T1,
5019            HISTORY_T1,
5020        ));
5021
5022        let (reports, coverage) = read_history(&[], &rows, None).await;
5023
5024        assert_eq!(report_status(&reports, "H-O"), expected, "{reports:?}");
5025        assert_eq!(
5026            report_status(&reports, "H-SIBLING"),
5027            Some(OrderStatus::Accepted)
5028        );
5029        assert!(!coverage.is_complete());
5030        assert!(!rules_out(&coverage, "H-O"));
5031        assert!(rules_out(&coverage, "H-OTHER"));
5032    }
5033
5034    /// A scoped read cannot place a row whose contract does not resolve, so it may be the order's
5035    /// own and withholds the order.
5036    #[rstest]
5037    #[tokio::test]
5038    async fn test_request_order_status_reports_withhold_on_a_scoped_read_for_an_unresolved_row() {
5039        let rows = [
5040            unresolved_row("H-O", HISTORY_T2),
5041            readable_row("OrderPlaced", "H-O", HISTORY_T1, HISTORY_T1),
5042            readable_row("OrderPlaced", "H-SIBLING", HISTORY_T1, HISTORY_T1),
5043        ];
5044
5045        let (reports, coverage) = read_history(&[], &rows, Some("PF_XBTUSD")).await;
5046
5047        assert_eq!(report_status(&reports, "H-O"), None, "{reports:?}");
5048        assert!(report_status(&reports, "H-SIBLING").is_some());
5049        assert!(!coverage.is_complete());
5050        assert!(!rules_out(&coverage, "H-O"));
5051    }
5052
5053    /// An undocumented kind's shape is only a guess, so the order it appears to name is withheld
5054    /// but no other order is ruled out, and a sibling is still reported.
5055    #[rstest]
5056    #[tokio::test]
5057    async fn test_request_order_status_reports_withhold_an_order_an_undocumented_row_names() {
5058        let rows = [
5059            undocumented_row("H-O", HISTORY_T2),
5060            readable_row("OrderPlaced", "H-O", HISTORY_T1, HISTORY_T1),
5061            readable_row("OrderPlaced", "H-SIBLING", HISTORY_T1, HISTORY_T1),
5062        ];
5063
5064        let (reports, coverage) = read_history(&[], &rows, None).await;
5065
5066        assert_eq!(report_status(&reports, "H-O"), None, "{reports:?}");
5067        assert!(report_status(&reports, "H-SIBLING").is_some());
5068        assert!(!coverage.is_complete());
5069        assert!(!rules_out(&coverage, "H-OTHER"));
5070    }
5071
5072    /// A row that names no order may be any order's, so the read rules out none, but it can
5073    /// withhold none either: the page's orders are still reported.
5074    #[rstest]
5075    #[tokio::test]
5076    async fn test_request_order_status_reports_keep_siblings_beside_an_unidentified_row() {
5077        let rows = [
5078            partial_row(None, Some("PF_XBTUSD"), HISTORY_T2),
5079            readable_row("OrderPlaced", "H-SIBLING", HISTORY_T1, HISTORY_T1),
5080        ];
5081
5082        let (reports, coverage) = read_history(&[], &rows, None).await;
5083
5084        assert!(report_status(&reports, "H-SIBLING").is_some());
5085        assert!(!coverage.is_complete());
5086        assert!(!rules_out(&coverage, "H-OTHER"));
5087    }
5088
5089    /// A decoded row whose order ID cannot be an ID names no order: the read survives it, rules
5090    /// out none and keeps the page's other rows, even with the row on another contract than a
5091    /// scoped read's target.
5092    #[rstest]
5093    #[case::empty("", "PF_XBTUSD", None)]
5094    #[case::whitespace(" ", "PF_XBTUSD", None)]
5095    #[case::non_ascii("\u{e9}", "PF_XBTUSD", None)]
5096    #[case::scoped_other_contract("", "PF_ETHUSD", Some("PF_XBTUSD"))]
5097    #[tokio::test]
5098    async fn test_request_order_status_reports_treat_an_invalid_order_id_as_unidentified(
5099        #[case] uid: &str,
5100        #[case] tradeable: &str,
5101        #[case] scope: Option<&str>,
5102    ) {
5103        let order = history_order(
5104            uid,
5105            tradeable,
5106            HISTORY_T2,
5107            r#""quantity":"3","orderType":"Limit""#,
5108        );
5109        let rows = [
5110            history_element("OrderPlaced", HISTORY_T2, &order),
5111            readable_row("OrderPlaced", "H-SIBLING", HISTORY_T1, HISTORY_T1),
5112        ];
5113
5114        let (reports, coverage) = read_history(&[], &rows, scope).await;
5115
5116        assert_eq!(reports.len(), 1, "{reports:?}");
5117        assert!(report_status(&reports, "H-SIBLING").is_some());
5118        assert!(!coverage.is_complete());
5119        assert!(!rules_out(&coverage, "H-OTHER"));
5120    }
5121
5122    /// With no open-order snapshot covering it, a skipped row stays out of the coverage only when
5123    /// it is provably outside the read: it names an order and a contract the cache resolves to
5124    /// another instrument than the read's target. A row that establishes less, or a read with no
5125    /// target, counts it.
5126    #[rstest]
5127    #[case::scoped_target(Some("PF_XBTUSD"), Some("H-O"), Some("PF_XBTUSD"), false, false, true)]
5128    #[case::scoped_target_other_case(
5129        Some("PF_XBTUSD"),
5130        Some("H-O"),
5131        Some("pf_xbtusd"),
5132        false,
5133        false,
5134        true
5135    )]
5136    #[case::scoped_unresolved(Some("PF_XBTUSD"), Some("H-O"), Some("PF_NOPE"), false, false, true)]
5137    #[case::scoped_no_contract(Some("PF_XBTUSD"), Some("H-O"), None, false, false, true)]
5138    #[case::scoped_other_contract(
5139        Some("PF_XBTUSD"),
5140        Some("H-O"),
5141        Some("PF_ETHUSD"),
5142        true,
5143        true,
5144        true
5145    )]
5146    #[case::scoped_other_contract_other_case(
5147        Some("PF_XBTUSD"),
5148        Some("H-O"),
5149        Some("pf_ethusd"),
5150        true,
5151        true,
5152        true
5153    )]
5154    #[case::scoped_other_contract_no_order(
5155        Some("PF_XBTUSD"),
5156        None,
5157        Some("PF_ETHUSD"),
5158        false,
5159        false,
5160        false
5161    )]
5162    #[case::scoped_neither(Some("PF_XBTUSD"), None, None, false, false, false)]
5163    #[case::unscoped_named(None, Some("H-O"), Some("PF_ETHUSD"), false, false, true)]
5164    #[case::unscoped_no_order(None, None, Some("PF_ETHUSD"), false, false, false)]
5165    #[tokio::test]
5166    async fn test_request_order_status_reports_count_a_skipped_row_unless_provably_out_of_scope(
5167        #[case] scope: Option<&str>,
5168        #[case] uid: Option<&str>,
5169        #[case] tradeable: Option<&str>,
5170        #[case] expected_complete: bool,
5171        #[case] expected_rules_out_order: bool,
5172        #[case] expected_rules_out_other: bool,
5173    ) {
5174        let rows = [
5175            partial_row(uid, tradeable, HISTORY_T2),
5176            readable_row("OrderPlaced", "H-SIBLING", HISTORY_T1, HISTORY_T1),
5177        ];
5178
5179        let (reports, coverage) = read_history(&[], &rows, scope).await;
5180
5181        assert!(report_status(&reports, "H-SIBLING").is_some());
5182        assert_eq!(coverage.is_complete(), expected_complete);
5183        assert_eq!(rules_out(&coverage, "H-O"), expected_rules_out_order);
5184        assert_eq!(rules_out(&coverage, "H-OTHER"), expected_rules_out_other);
5185    }
5186
5187    /// A row of an order the open-order snapshot reports does not count, however it failed, since
5188    /// the snapshot is the evidence for that order.
5189    #[rstest]
5190    #[case::unreadable(unreadable_row("H-OPEN", HISTORY_T2))]
5191    #[case::unreadable_no_contract(partial_row(Some("H-OPEN"), None, HISTORY_T2))]
5192    #[case::unparsable(unparsable_row("H-OPEN", HISTORY_T2))]
5193    #[case::unrepresentable(unrepresentable_row("H-OPEN", HISTORY_T2))]
5194    #[case::unresolved(unresolved_row("H-OPEN", HISTORY_T2))]
5195    #[tokio::test]
5196    async fn test_request_order_status_reports_ignore_a_skipped_row_the_snapshot_covers(
5197        #[case] row: String,
5198    ) {
5199        let (reports, coverage) = read_history(&[("H-OPEN", "PF_XBTUSD")], &[row], None).await;
5200
5201        assert_eq!(reports.len(), 1, "{reports:?}");
5202        assert_eq!(reports[0].venue_order_id, VenueOrderId::from("H-OPEN"));
5203        assert!(coverage.is_complete());
5204    }
5205
5206    /// A snapshot row a scoped read passes over reports nothing, so it covers nothing: a row of
5207    /// that order that does not name its contract still counts.
5208    #[rstest]
5209    #[tokio::test]
5210    async fn test_request_order_status_reports_count_a_row_of_an_order_listed_out_of_scope() {
5211        let rows = [partial_row(Some("H-OPEN"), None, HISTORY_T2)];
5212
5213        let (reports, coverage) =
5214            read_history(&[("H-OPEN", "PF_ETHUSD")], &rows, Some("PF_XBTUSD")).await;
5215
5216        assert!(reports.is_empty(), "{reports:?}");
5217        assert!(!coverage.is_complete());
5218        assert!(!rules_out(&coverage, "H-OPEN"));
5219    }
5220
5221    /// An undocumented kind proves nothing about its order, so the snapshot does not excuse it.
5222    #[rstest]
5223    #[tokio::test]
5224    async fn test_request_order_status_reports_count_an_undocumented_row_the_snapshot_lists() {
5225        let rows = [undocumented_row("H-OPEN", HISTORY_T2)];
5226
5227        let (reports, coverage) = read_history(&[("H-OPEN", "PF_XBTUSD")], &rows, None).await;
5228
5229        assert_eq!(reports.len(), 1, "{reports:?}");
5230        assert!(!coverage.is_complete());
5231        assert!(!rules_out(&coverage, "H-OTHER"));
5232    }
5233
5234    /// An undocumented kind proves nothing about its contract either, so a scoped read counts it
5235    /// even when the order it appears to name is on another contract.
5236    #[rstest]
5237    #[tokio::test]
5238    async fn test_request_order_status_reports_count_an_undocumented_row_of_another_contract() {
5239        let order = history_order(
5240            "H-O",
5241            "PF_ETHUSD",
5242            HISTORY_T2,
5243            r#""quantity":"3","orderType":"Limit""#,
5244        );
5245        let rows = [history_element("OrderSomethingNew", HISTORY_T2, &order)];
5246
5247        let (_, coverage) = read_history(&[], &rows, Some("PF_XBTUSD")).await;
5248
5249        assert!(!coverage.is_complete());
5250        assert!(!rules_out(&coverage, "H-OTHER"));
5251    }
5252
5253    /// A continuation token still cuts the read short at the oldest event beside a skipped row.
5254    #[rstest]
5255    #[tokio::test]
5256    async fn test_request_order_status_reports_keep_the_cut_beside_a_skipped_row() {
5257        let page = format!(
5258            r#"{{"elements":[{},{}],"continuationToken":"c2ltYjE3OA=="}}"#,
5259            unreadable_row("H-O", HISTORY_T2),
5260            readable_row("OrderPlaced", "H-SIBLING", HISTORY_T1, HISTORY_T1),
5261        );
5262        let client = history_test_client(Arc::new(RwLock::new(page)), None).await;
5263        cache_test_futures_instrument(&client);
5264
5265        let (reports, coverage) = client
5266            .request_order_status_reports_checked(
5267                AccountId::from("KRAKEN-001"),
5268                None,
5269                None,
5270                None,
5271                false,
5272            )
5273            .await
5274            .unwrap();
5275
5276        assert_eq!(reports.len(), 1, "{reports:?}");
5277        assert!(!coverage.is_complete());
5278        let after_the_cut = UnixNanos::from((HISTORY_T1 as u64 + 120_000) * 1_000_000);
5279        let before_the_cut = UnixNanos::from((HISTORY_T1 as u64 - 120_000) * 1_000_000);
5280        assert!(coverage.rules_out(Some(VenueOrderId::from("H-OTHER")), Some(after_the_cut)));
5281        assert!(!coverage.rules_out(Some(VenueOrderId::from("H-OTHER")), Some(before_the_cut)));
5282    }
5283
5284    const DOCUMENTED_EDIT_RESPONSE: &str =
5285        include_str!("../../../test_data/http_edit_order_futures.json");
5286    const DOCUMENTED_EDIT_ORDER_ID: &str = "022774bc-2c4a-4f26-9317-436c8d85746d";
5287
5288    /// Kraken's documented edit response with its `orderId` replaced or removed, and the send
5289    /// response's `order_id` key added.
5290    fn edit_response(
5291        order_id: Option<serde_json::Value>,
5292        order_id_snake_case: Option<serde_json::Value>,
5293    ) -> String {
5294        let mut response: serde_json::Value =
5295            serde_json::from_str(DOCUMENTED_EDIT_RESPONSE).unwrap();
5296        let edit_status = response["editStatus"].as_object_mut().unwrap();
5297        match order_id {
5298            Some(order_id) => edit_status.insert("orderId".to_string(), order_id),
5299            None => edit_status.remove("orderId"),
5300        };
5301
5302        if let Some(order_id) = order_id_snake_case {
5303            edit_status.insert("order_id".to_string(), order_id);
5304        }
5305        response.to_string()
5306    }
5307
5308    /// Sends an edit naming the order by `venue_order_id`, or by client order ID alone, to a venue
5309    /// that answers with `body`.
5310    async fn modify_order_answered_with(
5311        body: String,
5312        venue_order_id: Option<&str>,
5313    ) -> anyhow::Result<VenueOrderId> {
5314        use axum::{Router, http::header, routing::any};
5315
5316        let app = Router::new().route(
5317            "/derivatives/api/v3/editorder",
5318            any(move || {
5319                let body = body.clone();
5320                async move { ([(header::CONTENT_TYPE, "application/json")], body) }
5321            }),
5322        );
5323        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
5324        let addr = listener.local_addr().unwrap();
5325        tokio::spawn(async move {
5326            axum::serve(listener, app).await.unwrap();
5327        });
5328        let client = KrakenFuturesHttpClient::with_credentials(
5329            "test".to_string(),
5330            "test".to_string(),
5331            KrakenEnvironment::Live,
5332            Some(format!("http://{addr}")),
5333            10,
5334            None,
5335            None,
5336            None,
5337            None,
5338            10,
5339        )
5340        .unwrap();
5341        let instrument_id = cache_test_futures_instrument(&client);
5342        let client_order_id = venue_order_id
5343            .is_none()
5344            .then(|| ClientOrderId::from("O-EDIT"));
5345
5346        client
5347            .modify_order(
5348                instrument_id,
5349                client_order_id,
5350                venue_order_id.map(VenueOrderId::from),
5351                Some(Quantity::from("1")),
5352                None,
5353                None,
5354            )
5355            .await
5356    }
5357
5358    /// Kraken's documented response names the order whichever identifier the request used.
5359    #[rstest]
5360    #[case::by_venue_id(Some(DOCUMENTED_EDIT_ORDER_ID))]
5361    #[case::by_client_id(None)]
5362    #[tokio::test]
5363    async fn test_modify_order_returns_the_documented_order_id(
5364        #[case] request_venue_order_id: Option<&str>,
5365    ) {
5366        let venue_order_id = modify_order_answered_with(
5367            DOCUMENTED_EDIT_RESPONSE.to_string(),
5368            request_venue_order_id,
5369        )
5370        .await
5371        .unwrap();
5372
5373        assert_eq!(venue_order_id, VenueOrderId::from(DOCUMENTED_EDIT_ORDER_ID));
5374    }
5375
5376    /// The send response's key is read after the documented one, and a response naming no order
5377    /// falls back to the request's venue order ID.
5378    #[rstest]
5379    #[case::snake_case_key(None, Some(serde_json::json!("V-SNAKE")), None, "V-SNAKE")]
5380    #[case::both_keys(
5381        Some(serde_json::json!("V-DOC")),
5382        Some(serde_json::json!("V-SNAKE")),
5383        None,
5384        "V-DOC"
5385    )]
5386    #[case::absent(None, None, Some("V-EDIT"), "V-EDIT")]
5387    #[case::null(Some(serde_json::Value::Null), None, Some("V-EDIT"), "V-EDIT")]
5388    #[case::response_over_request(Some(serde_json::json!("V-DOC")), None, Some("V-EDIT"), "V-DOC")]
5389    #[tokio::test]
5390    async fn test_modify_order_resolves_the_order_id_by_key_then_request(
5391        #[case] order_id: Option<serde_json::Value>,
5392        #[case] order_id_snake_case: Option<serde_json::Value>,
5393        #[case] request_venue_order_id: Option<&str>,
5394        #[case] expected: &str,
5395    ) {
5396        let venue_order_id = modify_order_answered_with(
5397            edit_response(order_id, order_id_snake_case),
5398            request_venue_order_id,
5399        )
5400        .await
5401        .unwrap();
5402
5403        assert_eq!(venue_order_id, VenueOrderId::from(expected));
5404    }
5405
5406    /// An edit the venue applied, answered with an order ID the model cannot hold, returns the typed
5407    /// error: an untyped one would read as a command never sent. An invalid ID differs from an
5408    /// absent one, which falls back to the request's venue order ID.
5409    #[rstest]
5410    #[case::by_venue_id(Some(serde_json::json!("")), None, Some("V-EDIT"))]
5411    #[case::by_client_id(Some(serde_json::json!("")), None, None)]
5412    #[case::snake_case_key(None, Some(serde_json::json!("")), Some("V-EDIT"))]
5413    #[tokio::test]
5414    async fn test_modify_order_returns_a_typed_error_for_an_invalid_order_id(
5415        #[case] order_id: Option<serde_json::Value>,
5416        #[case] order_id_snake_case: Option<serde_json::Value>,
5417        #[case] request_venue_order_id: Option<&str>,
5418    ) {
5419        let error = modify_order_answered_with(
5420            edit_response(order_id, order_id_snake_case),
5421            request_venue_order_id,
5422        )
5423        .await
5424        .unwrap_err();
5425
5426        assert!(
5427            matches!(
5428                error.downcast_ref::<KrakenModifyOrderError>(),
5429                Some(KrakenModifyOrderError::InvalidOrderId { detail })
5430                    if detail.starts_with("Invalid order_id '' in Kraken futures edit response")
5431            ),
5432            "{error:#}"
5433        );
5434    }
5435
5436    /// A response naming no order leaves nothing to name it on a request by client order ID alone.
5437    #[rstest]
5438    #[case::absent(None)]
5439    #[case::null(Some(serde_json::Value::Null))]
5440    #[tokio::test]
5441    async fn test_modify_order_by_client_id_fails_without_an_order_id(
5442        #[case] order_id: Option<serde_json::Value>,
5443    ) {
5444        let error = modify_order_answered_with(edit_response(order_id, None), None)
5445            .await
5446            .unwrap_err();
5447
5448        assert!(
5449            matches!(
5450                error.downcast_ref::<KrakenModifyOrderError>(),
5451                Some(KrakenModifyOrderError::MissingOrderId)
5452            ),
5453            "{error:#}"
5454        );
5455    }
5456
5457    /// A contract the listing spells two ways in different cases cannot be told apart by a
5458    /// case-insensitive match, so such a spelling resolves to neither, while an exact spelling
5459    /// and a unique case-insensitive one still resolve.
5460    #[rstest]
5461    #[tokio::test]
5462    async fn test_history_tradeable_leaves_an_ambiguous_spelling_unresolved() {
5463        let client = history_test_client(Arc::new(RwLock::new(String::new())), None).await;
5464        cache_futures_contract(&client, "PF_AAPLxUSD");
5465        cache_futures_contract(&client, "PF_AAPLXUSD");
5466        cache_futures_contract(&client, "PF_XBTUSD");
5467
5468        let resolve = |tradeable: &str| {
5469            client
5470                .get_instrument_by_history_tradeable(tradeable)
5471                .map(|instrument| instrument.raw_symbol().to_string())
5472        };
5473
5474        assert_eq!(resolve("pf_aaplxusd"), None);
5475        assert_eq!(resolve("PF_AAPLxUSD"), Some("PF_AAPLxUSD".to_string()));
5476        assert_eq!(resolve("pf_xbtusd"), Some("PF_XBTUSD".to_string()));
5477    }
5478
5479    /// The post-submit lookup answers from history only when no unread row may hold a newer state
5480    /// of the order: a row of the order, a row naming none or an undocumented row that is as new
5481    /// fails the lookup, while an older row or one naming another order leaves the answer standing.
5482    /// A refused edit's state, stamped before its event, counts from that stamp.
5483    #[rstest]
5484    #[case::order_newer(partial_row(Some("H-O"), None, HISTORY_T2), HISTORY_T1, false)]
5485    #[case::order_tied(partial_row(Some("H-O"), None, HISTORY_T1), HISTORY_T1, false)]
5486    #[case::order_older(partial_row(Some("H-O"), None, HISTORY_T0), HISTORY_T1, true)]
5487    #[case::unnamed_newer(partial_row(None, None, HISTORY_T2), HISTORY_T1, false)]
5488    #[case::unnamed_older(partial_row(None, None, HISTORY_T0), HISTORY_T1, true)]
5489    #[case::sibling_newer(partial_row(Some("H-SIBLING"), None, HISTORY_T2), HISTORY_T1, true)]
5490    #[case::undocumented_sibling_newer(
5491        undocumented_row("H-SIBLING", HISTORY_T2),
5492        HISTORY_T1,
5493        false
5494    )]
5495    #[case::invalid_id_newer(unrepresentable_row("", HISTORY_T2), HISTORY_T1, false)]
5496    #[case::invalid_id_on_a_readable_row_newer(
5497        readable_row("OrderPlaced", "", HISTORY_T2, HISTORY_T2),
5498        HISTORY_T1,
5499        false
5500    )]
5501    #[case::before_the_event_after_the_state(
5502        partial_row(Some("H-O"), None, HISTORY_T2),
5503        HISTORY_T3,
5504        false
5505    )]
5506    #[tokio::test]
5507    async fn test_submit_order_history_fallback_defers_to_an_unread_newer_row(
5508        #[case] row: String,
5509        #[case] found_event_ms: i64,
5510        #[case] expected_ok: bool,
5511    ) {
5512        use axum::{Router, http::header, routing::any};
5513
5514        let page = history_json(&[
5515            row,
5516            readable_row("OrderEditRejected", "H-O", found_event_ms, HISTORY_T1),
5517        ]);
5518        let app = Router::new()
5519            .route(
5520                "/derivatives/api/v3/sendorder",
5521                any(|| async {
5522                    (
5523                        [(header::CONTENT_TYPE, "application/json")],
5524                        r#"{"result":"success","sendStatus":{"status":"placed","order_id":"H-O"}}"#,
5525                    )
5526                }),
5527            )
5528            .route(
5529                "/derivatives/api/v3/openorders",
5530                any(|| async {
5531                    (
5532                        [(header::CONTENT_TYPE, "application/json")],
5533                        r#"{"result":"success","openOrders":[]}"#,
5534                    )
5535                }),
5536            )
5537            .route(
5538                "/api/history/v3/orders",
5539                any(move || {
5540                    let page = page.clone();
5541                    async move { ([(header::CONTENT_TYPE, "application/json")], page) }
5542                }),
5543            );
5544        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
5545        let addr = listener.local_addr().unwrap();
5546        tokio::spawn(async move {
5547            axum::serve(listener, app).await.unwrap();
5548        });
5549        let client = KrakenFuturesHttpClient::with_credentials(
5550            "test".to_string(),
5551            "test".to_string(),
5552            KrakenEnvironment::Live,
5553            Some(format!("http://{addr}")),
5554            10,
5555            None,
5556            None,
5557            None,
5558            None,
5559            10,
5560        )
5561        .unwrap();
5562        cache_test_futures_instrument(&client);
5563
5564        let result = client
5565            .submit_order(
5566                AccountId::from("KRAKEN-001"),
5567                InstrumentId::from("PF_XBTUSD.KRAKEN"),
5568                ClientOrderId::from("cl-fallback"),
5569                OrderSide::Buy,
5570                OrderType::Limit,
5571                Quantity::from("3"),
5572                TimeInForce::Gtc,
5573                Some(Price::from("70000")),
5574                None,
5575                None,
5576                false,
5577                false,
5578            )
5579            .await;
5580
5581        assert_eq!(result.is_ok(), expected_ok, "{result:?}");
5582    }
5583
5584    /// A history row's report carries the time in force and post-only its order type states.
5585    #[rstest]
5586    #[case::ioc("IoC", TimeInForce::Ioc, false)]
5587    #[case::fill_or_kill("FillOrKill", TimeInForce::Fok, false)]
5588    #[case::post("Post", TimeInForce::Gtc, true)]
5589    #[case::limit("Limit", TimeInForce::Gtc, false)]
5590    #[tokio::test]
5591    async fn test_request_order_status_reports_carry_the_time_in_force_of_a_history_row(
5592        #[case] order_type: &str,
5593        #[case] expected_time_in_force: TimeInForce,
5594        #[case] expected_post_only: bool,
5595    ) {
5596        let order = history_order(
5597            "H-O",
5598            "PF_XBTUSD",
5599            HISTORY_T1,
5600            &format!(r#""quantity":"3","orderType":"{order_type}""#),
5601        );
5602        let rows = [history_element("OrderPlaced", HISTORY_T1, &order)];
5603
5604        let (reports, _) = read_history(&[], &rows, None).await;
5605
5606        assert_eq!(reports.len(), 1, "{reports:?}");
5607        assert_eq!(reports[0].time_in_force, expected_time_in_force);
5608        assert_eq!(reports[0].post_only, expected_post_only);
5609    }
5610
5611    /// The venue refuses a client order ID it already holds, or one too long or otherwise invalid,
5612    /// so these statuses reject the submission rather than leave it ambiguous.
5613    #[rstest]
5614    #[case::already_exists("clientOrderIdAlreadyExist")]
5615    #[case::too_big("clientOrderIdTooBig")]
5616    #[case::too_long("clientOrderIdTooLong")]
5617    #[case::invalid("clientOrderIdInvalid")]
5618    fn test_client_order_id_send_statuses_reject_the_submission(#[case] status: &str) {
5619        assert!(is_futures_submit_rejection(status));
5620    }
5621
5622    fn cache_test_futures_instrument(client: &KrakenFuturesHttpClient) -> InstrumentId {
5623        let instrument_id = InstrumentId::from("PF_XBTUSD.KRAKEN");
5624
5625        client.cache_instrument(InstrumentAny::CryptoPerpetual(
5626            CryptoPerpetual::builder()
5627                .instrument_id(instrument_id)
5628                .raw_symbol(Symbol::new("PF_XBTUSD"))
5629                .base_currency(Currency::BTC())
5630                .quote_currency(Currency::USD())
5631                .settlement_currency(Currency::USD())
5632                .is_inverse(false)
5633                .price_precision(0)
5634                .size_precision(4)
5635                .price_increment(Price::from("1"))
5636                .size_increment(Quantity::from("0.0001"))
5637                .ts_event(0.into())
5638                .ts_init(0.into())
5639                .build()
5640                .unwrap(),
5641        ));
5642
5643        instrument_id
5644    }
5645}