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