Skip to main content

nautilus_kraken/http/spot/
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 Spot REST API.
17
18use std::{
19    collections::{HashMap, HashSet},
20    fmt::Debug,
21    num::NonZeroU32,
22    sync::{
23        Arc,
24        atomic::{AtomicBool, Ordering},
25    },
26};
27
28use ahash::AHashMap;
29use anyhow::Context;
30use indexmap::IndexMap;
31use jiff::Timestamp;
32use nautilus_common::cache::InstrumentLookupError;
33use nautilus_core::{
34    AtomicMap, AtomicTime, UUID4, datetime::NANOSECONDS_IN_SECOND, nanos::UnixNanos,
35    time::get_atomic_clock_realtime,
36};
37use nautilus_model::{
38    data::{Bar, BarType, BookOrder, TradeTick},
39    enums::{
40        AccountType, AvgPxReconciliation, BookType, CurrencyType, MarketStatusAction, OrderSide,
41        OrderType, PositionSide, TimeInForce, TriggerType,
42    },
43    events::AccountState,
44    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, VenueOrderId},
45    instruments::{Instrument, InstrumentAny},
46    orderbook::OrderBook,
47    reports::{FillReport, OrderStatusReport, PositionStatusReport},
48    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
49};
50use nautilus_network::{
51    ConnectionUrl,
52    http::{
53        HttpClient, HttpRedirectPolicy, HttpResponse, Method, create_standard_nautilus_headers,
54    },
55    ratelimiter::quota::Quota,
56    retry::{RetryConfig, RetryError, RetryManager},
57};
58use parking_lot::RwLock;
59use rust_decimal::Decimal;
60use serde::{Serialize, de::DeserializeOwned};
61use tokio_util::sync::CancellationToken;
62use ustr::Ustr;
63
64use super::{models::*, query::*};
65use crate::{
66    common::{
67        consts::{
68            KRAKEN_ALTNAME_KEY, KRAKEN_OFLAG_POST_ONLY, KRAKEN_OFLAG_QUOTE_QUANTITY, KRAKEN_VENUE,
69            NAUTILUS_KRAKEN_BROKER_ID,
70        },
71        credential::KrakenCredential,
72        enums::{
73            KrakenAssetClass, KrakenEnvironment, KrakenOrderSide, KrakenOrderType,
74            KrakenProductType, product_type_from_symbol,
75        },
76        parse::{
77            bar_type_to_spot_interval, normalize_currency_code, normalize_spot_symbol, parse_bar,
78            parse_fill_report, parse_order_status_report, parse_spot_instrument,
79            parse_tokenized_instrument, parse_trade_tick_from_array, parse_venue_order_id,
80            truncate_cl_ord_id,
81        },
82        urls::get_kraken_http_base_url,
83    },
84    http::{
85        apply_count_limit,
86        coverage::ReportCoverage,
87        error::{
88            KrakenBatchOrderError, KrakenHttpError, KrakenModifyOrderError, KrakenSubmitOrderError,
89            kraken_http_should_retry,
90        },
91    },
92};
93
94/// Default Kraken Spot REST API rate limit (requests per second).
95pub const KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND: u32 = 5;
96
97/// Caps offset pagination for report reads.
98///
99/// The loops below advance an offset until the venue returns an empty page. A venue that kept
100/// returning a non-empty page would otherwise leave a startup reconciliation read spinning, which
101/// is worse than failing it. Mirrors the cap OKX applies to its own pagination.
102const MAX_REPORT_PAGES: usize = 500;
103
104const KRAKEN_GLOBAL_RATE_KEY: &str = "kraken:spot:global";
105
106/// Maximum orders per batch cancel request for Kraken Spot API.
107const BATCH_CANCEL_LIMIT: usize = 50;
108
109/// Maximum orders per batch submit request for Kraken Spot API.
110const BATCH_SUBMIT_LIMIT: usize = 15;
111
112/// Raw HTTP client for low-level Kraken Spot API operations.
113///
114/// This client handles request/response operations with the Kraken Spot API,
115/// returning venue-specific response types. It does not parse to Nautilus domain types.
116pub struct KrakenSpotRawHttpClient {
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 KrakenSpotRawHttpClient {
128    fn default() -> Self {
129        Self::new(
130            KrakenEnvironment::Live,
131            None,
132            60,
133            None,
134            None,
135            None,
136            None,
137            KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND,
138        )
139        .expect("Failed to create default KrakenSpotRawHttpClient")
140    }
141}
142
143impl Debug for KrakenSpotRawHttpClient {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        f.debug_struct(stringify!(KrakenSpotRawHttpClient))
146            .field("base_url", &self.base_url)
147            .field("has_credentials", &self.credential.is_some())
148            .finish()
149    }
150}
151
152impl KrakenSpotRawHttpClient {
153    /// Creates a new [`KrakenSpotRawHttpClient`].
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::Spot, environment).to_string()
179        });
180
181        Ok(Self {
182            base_url: base_url.into(),
183            client: HttpClient::builder()
184                .headers(Self::default_headers())
185                .keyed_quotas(Self::rate_limiter_quotas(max_requests_per_second)?)
186                .default_quota(Self::default_quota(max_requests_per_second)?)
187                .timeout_secs(timeout_secs)
188                .maybe_proxy_url(proxy_url)
189                .build()
190                .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?,
191            credential: None,
192            retry_manager,
193            cancellation_token: RwLock::new(CancellationToken::new()),
194            clock: get_atomic_clock_realtime(),
195            auth_mutex: tokio::sync::Mutex::new(()),
196        })
197    }
198
199    /// Creates a new [`KrakenSpotRawHttpClient`] with credentials.
200    #[expect(clippy::too_many_arguments)]
201    pub fn with_credentials(
202        api_key: String,
203        api_secret: String,
204        environment: KrakenEnvironment,
205        base_url_override: Option<String>,
206        timeout_secs: u64,
207        max_retries: Option<u32>,
208        retry_delay_ms: Option<u64>,
209        retry_delay_max_ms: Option<u64>,
210        proxy_url: Option<String>,
211        max_requests_per_second: u32,
212    ) -> anyhow::Result<Self> {
213        let retry_config = RetryConfig {
214            max_retries: max_retries.unwrap_or(3),
215            initial_delay_ms: retry_delay_ms.unwrap_or(1000),
216            max_delay_ms: retry_delay_max_ms.unwrap_or(10_000),
217            backoff_factor: 2.0,
218            jitter_ms: 1000,
219            operation_timeout_ms: Some(60_000),
220            immediate_first: false,
221            max_elapsed_ms: Some(180_000),
222        };
223
224        let retry_manager = RetryManager::new(retry_config);
225        let base_url = base_url_override.unwrap_or_else(|| {
226            get_kraken_http_base_url(KrakenProductType::Spot, environment).to_string()
227        });
228
229        Ok(Self {
230            base_url: base_url.into(),
231            client: HttpClient::builder()
232                .redirect_policy(HttpRedirectPolicy::Reject)
233                .headers(Self::default_headers())
234                .keyed_quotas(Self::rate_limiter_quotas(max_requests_per_second)?)
235                .default_quota(Self::default_quota(max_requests_per_second)?)
236                .timeout_secs(timeout_secs)
237                .maybe_proxy_url(proxy_url)
238                .build()
239                .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?,
240            credential: Some(KrakenCredential::new(api_key, api_secret)),
241            retry_manager,
242            cancellation_token: RwLock::new(CancellationToken::new()),
243            clock: get_atomic_clock_realtime(),
244            auth_mutex: tokio::sync::Mutex::new(()),
245        })
246    }
247
248    /// Generates a unique nonce for Kraken Spot API requests.
249    ///
250    /// Uses `AtomicTime` for strict monotonicity. The nanosecond timestamp
251    /// guarantees uniqueness even for rapid consecutive calls.
252    fn generate_nonce(&self) -> u64 {
253        self.clock.get_time_ns().as_u64()
254    }
255
256    /// Returns the base URL for this client.
257    pub fn base_url(&self) -> &str {
258        self.base_url.expose()
259    }
260
261    /// Returns the credential for this client, if set.
262    pub fn credential(&self) -> Option<&KrakenCredential> {
263        self.credential.as_ref()
264    }
265
266    /// Cancels all pending HTTP requests.
267    pub fn cancel_all_requests(&self) {
268        self.cancellation_token.read().cancel();
269    }
270
271    /// Replaces the canceled token so requests can proceed after reconnect.
272    pub fn reset_cancellation_token(&self) {
273        *self.cancellation_token.write() = CancellationToken::new();
274    }
275
276    /// Returns a clone of the current cancellation token.
277    pub fn cancellation_token(&self) -> CancellationToken {
278        self.cancellation_token.read().clone()
279    }
280
281    fn default_headers() -> HashMap<String, String> {
282        create_standard_nautilus_headers().into_iter().collect()
283    }
284
285    fn default_quota(max_requests_per_second: u32) -> anyhow::Result<Quota> {
286        let burst = NonZeroU32::new(max_requests_per_second).unwrap_or(
287            NonZeroU32::new(KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND).expect("non-zero"),
288        );
289        Quota::per_second(burst).ok_or_else(|| {
290            anyhow::anyhow!(
291                "Invalid max_requests_per_second: {max_requests_per_second} exceeds maximum"
292            )
293        })
294    }
295
296    fn rate_limiter_quotas(max_requests_per_second: u32) -> anyhow::Result<Vec<(String, Quota)>> {
297        Ok(vec![(
298            KRAKEN_GLOBAL_RATE_KEY.to_string(),
299            Self::default_quota(max_requests_per_second)?,
300        )])
301    }
302
303    fn rate_limit_keys(endpoint: &str) -> Vec<String> {
304        let normalized = endpoint.split('?').next().unwrap_or(endpoint);
305        let route = format!("kraken:spot:{normalized}");
306        vec![KRAKEN_GLOBAL_RATE_KEY.to_string(), route]
307    }
308
309    fn sign_spot(
310        &self,
311        path: &str,
312        nonce: u64,
313        params: &HashMap<String, String>,
314    ) -> anyhow::Result<(HashMap<String, String>, String)> {
315        let credential = self
316            .credential
317            .as_ref()
318            .ok_or_else(|| anyhow::anyhow!("Missing credentials"))?;
319
320        let (signature, post_data) = credential.sign_spot(path, nonce, params)?;
321
322        let mut headers = HashMap::new();
323        headers.insert("API-Key".to_string(), credential.api_key().to_string());
324        headers.insert("API-Sign".to_string(), signature);
325
326        Ok((headers, post_data))
327    }
328
329    async fn send_request<T: DeserializeOwned>(
330        &self,
331        method: Method,
332        endpoint: &str,
333        body: Option<Vec<u8>>,
334        authenticate: bool,
335    ) -> anyhow::Result<KrakenResponse<T>, KrakenHttpError> {
336        self.send_request_with_body(method, endpoint, RequestBody::Form(body), authenticate)
337            .await
338    }
339
340    #[allow(
341        dead_code,
342        reason = "TradeVolume transport retained for account fee-rate follow-up"
343    )]
344    async fn send_json_request<T: DeserializeOwned, P: Serialize>(
345        &self,
346        method: Method,
347        endpoint: &str,
348        params: &P,
349        authenticate: bool,
350    ) -> anyhow::Result<KrakenResponse<T>, KrakenHttpError> {
351        let body = serde_json::to_value(params).map_err(|e| {
352            KrakenHttpError::RequestNotStarted(format!("Failed to encode request params: {e}"))
353        })?;
354        self.send_request_with_body(method, endpoint, RequestBody::Json(body), authenticate)
355            .await
356    }
357
358    async fn send_request_with_body<T: DeserializeOwned>(
359        &self,
360        method: Method,
361        endpoint: &str,
362        body: RequestBody,
363        authenticate: bool,
364    ) -> anyhow::Result<KrakenResponse<T>, KrakenHttpError> {
365        // Serialize authenticated requests to ensure nonces arrive at Kraken in order.
366        // Without this, concurrent requests can race through the network and arrive
367        // out-of-order, causing "Invalid nonce" errors.
368        let _guard = if authenticate {
369            Some(self.auth_mutex.lock().await)
370        } else {
371            None
372        };
373
374        let endpoint = endpoint.to_string();
375        let method_clone = method.clone();
376        let body_clone = body.clone();
377
378        let operation = || {
379            let method = method_clone.clone();
380            let body = body_clone.clone();
381            let endpoint = endpoint.clone();
382
383            async move {
384                self.send_request_attempt(method, &endpoint, body, authenticate, None)
385                    .await
386            }
387        };
388
389        let should_retry = kraken_http_should_retry;
390        let create_error = |error: RetryError| KrakenHttpError::NetworkError(error.to_string());
391
392        let cancellation_token = self.cancellation_token();
393
394        self.retry_manager
395            .invocation(&endpoint, operation, should_retry, create_error)
396            .cancellation_token(&cancellation_token)
397            .execute()
398            .await
399    }
400
401    async fn send_request_once<T: DeserializeOwned>(
402        &self,
403        method: Method,
404        endpoint: &str,
405        body: Option<Vec<u8>>,
406        authenticate: bool,
407    ) -> anyhow::Result<KrakenResponse<T>, KrakenHttpError> {
408        let cancellation_token = self.cancellation_token();
409        let _guard = if authenticate {
410            Some(self.lock_order_request(&cancellation_token).await?)
411        } else {
412            None
413        };
414
415        self.send_request_attempt(
416            method,
417            endpoint,
418            RequestBody::Form(body),
419            authenticate,
420            Some(&cancellation_token),
421        )
422        .await
423    }
424
425    async fn lock_order_request(
426        &self,
427        cancellation_token: &CancellationToken,
428    ) -> anyhow::Result<tokio::sync::MutexGuard<'_, ()>, KrakenHttpError> {
429        if cancellation_token.is_cancelled() {
430            return Err(KrakenHttpError::RequestNotStarted(
431                "Request canceled before transport invocation".to_string(),
432            ));
433        }
434
435        tokio::select! {
436            biased;
437            () = cancellation_token.cancelled() => Err(KrakenHttpError::RequestNotStarted(
438                "Request canceled before transport invocation".to_string(),
439            )),
440            guard = self.auth_mutex.lock() => Ok(guard),
441        }
442    }
443
444    async fn send_request_attempt<T: DeserializeOwned>(
445        &self,
446        method: Method,
447        endpoint: &str,
448        body: RequestBody,
449        authenticate: bool,
450        cancellation_token: Option<&CancellationToken>,
451    ) -> anyhow::Result<KrakenResponse<T>, KrakenHttpError> {
452        let mut headers = Self::default_headers();
453        let (final_body, content_type) = match (authenticate, body) {
454            (true, RequestBody::Form(body)) => {
455                let nonce = self.generate_nonce();
456                log::debug!("Generated nonce {nonce} for {endpoint}");
457
458                let params: HashMap<String, String> = if let Some(ref body_bytes) = body {
459                    let body_str = std::str::from_utf8(body_bytes).map_err(|e| {
460                        KrakenHttpError::RequestNotStarted(format!(
461                            "Invalid UTF-8 in request body: {e}"
462                        ))
463                    })?;
464                    serde_urlencoded::from_str(body_str).map_err(|e| {
465                        KrakenHttpError::RequestNotStarted(format!(
466                            "Failed to parse request params: {e}"
467                        ))
468                    })?
469                } else {
470                    HashMap::new()
471                };
472
473                let (auth_headers, post_data) =
474                    self.sign_spot(endpoint, nonce, &params).map_err(|e| {
475                        KrakenHttpError::RequestNotStarted(format!("Failed to sign request: {e}"))
476                    })?;
477                headers.extend(auth_headers);
478                (
479                    Some(post_data.into_bytes()),
480                    "application/x-www-form-urlencoded",
481                )
482            }
483            (true, RequestBody::Json(mut body)) => {
484                let nonce = self.generate_nonce();
485                log::debug!("Generated nonce {nonce} for {endpoint}");
486
487                let body = body.as_object_mut().ok_or_else(|| {
488                    KrakenHttpError::RequestNotStarted(
489                        "Authenticated JSON request body must be an object".to_string(),
490                    )
491                })?;
492                body.insert("nonce".to_string(), serde_json::json!(nonce.to_string()));
493                let body = serde_json::to_string(body).map_err(|e| {
494                    KrakenHttpError::RequestNotStarted(format!(
495                        "Failed to serialize request body: {e}"
496                    ))
497                })?;
498                let credential = self.credential.as_ref().ok_or_else(|| {
499                    KrakenHttpError::RequestNotStarted("Missing credentials".to_string())
500                })?;
501                let signature = credential
502                    .sign_spot_json(endpoint, nonce, &body)
503                    .map_err(|e| {
504                        KrakenHttpError::RequestNotStarted(format!("Failed to sign request: {e}"))
505                    })?;
506                headers.insert("API-Key".to_string(), credential.api_key().to_string());
507                headers.insert("API-Sign".to_string(), signature);
508                (Some(body.into_bytes()), "application/json")
509            }
510            (false, RequestBody::Form(body)) => (body, "application/x-www-form-urlencoded"),
511            (false, RequestBody::Json(body)) => {
512                let body = serde_json::to_vec(&body).map_err(|e| {
513                    KrakenHttpError::RequestNotStarted(format!(
514                        "Failed to serialize request body: {e}"
515                    ))
516                })?;
517                (Some(body), "application/json")
518            }
519        };
520
521        if method == Method::POST {
522            headers.insert("Content-Type".to_string(), content_type.to_string());
523        }
524
525        let response = if let Some(cancellation_token) = cancellation_token {
526            self.send_order_request(method, endpoint, headers, final_body, cancellation_token)
527                .await?
528        } else {
529            let url = format!("{}{endpoint}", self.base_url.expose());
530            let rate_limit_keys = Self::rate_limit_keys(endpoint);
531            self.client
532                .request(
533                    method,
534                    url,
535                    None,
536                    Some(headers),
537                    final_body,
538                    None,
539                    Some(rate_limit_keys),
540                )
541                .await
542                .map_err(|e| {
543                    KrakenHttpError::NetworkError(format!(
544                        "Request to {} failed: {e}",
545                        self.base_url.origin()
546                    ))
547                })?
548        };
549
550        let status = response.status.as_u16();
551        if status >= 400 {
552            let body = String::from_utf8_lossy(&response.body).to_string();
553            let http_error = if status == 401 || status == 403 {
554                KrakenHttpError::AuthenticationError(format!("HTTP error {status}: {body}"))
555            } else {
556                KrakenHttpError::NetworkError(format!("HTTP error {status}: {body}"))
557            };
558            return Err(http_error);
559        }
560
561        let response_text = String::from_utf8(response.body.to_vec()).map_err(|e| {
562            KrakenHttpError::ParseError(format!("Failed to parse response as UTF-8: {e}"))
563        })?;
564        let kraken_response: KrakenResponse<T> =
565            serde_json::from_str(&response_text).map_err(|e| {
566                KrakenHttpError::ParseError(format!("Failed to deserialize response: {e}"))
567            })?;
568
569        if !kraken_response.error.is_empty() {
570            return Err(KrakenHttpError::ApiError(kraken_response.error));
571        }
572
573        Ok(kraken_response)
574    }
575
576    async fn send_order_request(
577        &self,
578        method: Method,
579        endpoint: &str,
580        headers: HashMap<String, String>,
581        body: Option<Vec<u8>>,
582        cancellation_token: &CancellationToken,
583    ) -> anyhow::Result<HttpResponse, KrakenHttpError> {
584        if cancellation_token.is_cancelled() {
585            return Err(KrakenHttpError::RequestNotStarted(
586                "Request canceled before transport invocation".to_string(),
587            ));
588        }
589
590        let request_started = AtomicBool::new(false);
591        let url = format!("{}{endpoint}", self.base_url.expose());
592        let rate_limit_keys = Self::rate_limit_keys(endpoint);
593        let request = async {
594            request_started.store(true, Ordering::Relaxed);
595            self.client
596                .request(
597                    method,
598                    url,
599                    None,
600                    Some(headers),
601                    body,
602                    None,
603                    Some(rate_limit_keys),
604                )
605                .await
606        };
607        tokio::pin!(request);
608
609        tokio::select! {
610            biased;
611            () = cancellation_token.cancelled() => {
612                if request_started.load(Ordering::Relaxed) {
613                    Err(KrakenHttpError::NetworkError(
614                        "Request canceled after transport invocation".to_string(),
615                    ))
616                } else {
617                    Err(KrakenHttpError::RequestNotStarted(
618                        "Request canceled before transport invocation".to_string(),
619                    ))
620                }
621            }
622            response = &mut request => response
623                .map_err(|e| KrakenHttpError::NetworkError(format!("Request to {} failed: {e}", self.base_url.origin()))),
624        }
625    }
626
627    /// Requests the server time from Kraken.
628    pub async fn get_server_time(&self) -> anyhow::Result<ServerTime, KrakenHttpError> {
629        let response: KrakenResponse<ServerTime> = self
630            .send_request(Method::GET, "/0/public/Time", None, false)
631            .await?;
632
633        response.result.ok_or_else(|| {
634            KrakenHttpError::ParseError("Missing result in server time response".to_string())
635        })
636    }
637
638    /// Requests the system status from Kraken.
639    pub async fn get_system_status(&self) -> anyhow::Result<SystemStatus, KrakenHttpError> {
640        let response: KrakenResponse<SystemStatus> = self
641            .send_request(Method::GET, "/0/public/SystemStatus", None, false)
642            .await?;
643
644        response.result.ok_or_else(|| {
645            KrakenHttpError::ParseError("Missing result in system status response".to_string())
646        })
647    }
648
649    /// Requests tradable asset pairs from Kraken.
650    ///
651    /// When `aclass_base` is `None`, the Kraken API defaults to `"currency"` (crypto pairs).
652    /// Pass `"tokenized_asset"` to fetch tokenized equities (xStocks).
653    pub async fn get_asset_pairs(
654        &self,
655        pairs: Option<Vec<String>>,
656        aclass_base: Option<&str>,
657    ) -> anyhow::Result<AssetPairsResponse, KrakenHttpError> {
658        let mut params = Vec::new();
659
660        if let Some(pairs) = pairs {
661            params.push(format!("pair={}", pairs.join(",")));
662        }
663
664        if let Some(aclass) = aclass_base {
665            params.push(format!("aclass_base={aclass}"));
666        }
667
668        let endpoint = if params.is_empty() {
669            "/0/public/AssetPairs".to_string()
670        } else {
671            format!("/0/public/AssetPairs?{}", params.join("&"))
672        };
673
674        let response: KrakenResponse<AssetPairsResponse> = self
675            .send_request(Method::GET, &endpoint, None, false)
676            .await?;
677
678        response.result.ok_or_else(|| {
679            KrakenHttpError::ParseError("Missing result in asset pairs response".to_string())
680        })
681    }
682
683    /// Requests ticker information for asset pairs.
684    pub async fn get_ticker(
685        &self,
686        pairs: Vec<String>,
687        asset_class: Option<KrakenAssetClass>,
688    ) -> anyhow::Result<TickerResponse, KrakenHttpError> {
689        let mut endpoint = format!("/0/public/Ticker?pair={}", pairs.join(","));
690
691        if let Some(aclass) = asset_class {
692            endpoint.push_str(&format!("&asset_class={aclass}"));
693        }
694
695        let response: KrakenResponse<TickerResponse> = self
696            .send_request(Method::GET, &endpoint, None, false)
697            .await?;
698
699        response.result.ok_or_else(|| {
700            KrakenHttpError::ParseError("Missing result in ticker response".to_string())
701        })
702    }
703
704    /// Requests OHLC candlestick data for an asset pair.
705    pub async fn get_ohlc(
706        &self,
707        pair: &str,
708        interval: Option<u32>,
709        since: Option<i64>,
710        asset_class: Option<KrakenAssetClass>,
711    ) -> anyhow::Result<OhlcResponse, KrakenHttpError> {
712        let mut endpoint = format!("/0/public/OHLC?pair={pair}");
713
714        if let Some(aclass) = asset_class {
715            endpoint.push_str(&format!("&asset_class={aclass}"));
716        }
717
718        if let Some(interval) = interval {
719            endpoint.push_str(&format!("&interval={interval}"));
720        }
721
722        if let Some(since) = since {
723            endpoint.push_str(&format!("&since={since}"));
724        }
725
726        let response: KrakenResponse<OhlcResponse> = self
727            .send_request(Method::GET, &endpoint, None, false)
728            .await?;
729
730        response.result.ok_or_else(|| {
731            KrakenHttpError::ParseError("Missing result in OHLC response".to_string())
732        })
733    }
734
735    /// Requests order book depth for an asset pair.
736    pub async fn get_book_depth(
737        &self,
738        pair: &str,
739        count: Option<u32>,
740        asset_class: Option<KrakenAssetClass>,
741    ) -> anyhow::Result<OrderBookResponse, KrakenHttpError> {
742        let mut endpoint = format!("/0/public/Depth?pair={pair}");
743
744        if let Some(aclass) = asset_class {
745            endpoint.push_str(&format!("&asset_class={aclass}"));
746        }
747
748        if let Some(count) = count {
749            endpoint.push_str(&format!("&count={count}"));
750        }
751
752        let response: KrakenResponse<OrderBookResponse> = self
753            .send_request(Method::GET, &endpoint, None, false)
754            .await?;
755
756        response.result.ok_or_else(|| {
757            KrakenHttpError::ParseError("Missing result in book depth response".to_string())
758        })
759    }
760
761    /// Requests recent trades for an asset pair.
762    pub async fn get_trades(
763        &self,
764        pair: &str,
765        since: Option<String>,
766        asset_class: Option<KrakenAssetClass>,
767    ) -> anyhow::Result<TradesResponse, KrakenHttpError> {
768        let mut endpoint = format!("/0/public/Trades?pair={pair}");
769
770        if let Some(aclass) = asset_class {
771            endpoint.push_str(&format!("&asset_class={aclass}"));
772        }
773
774        if let Some(since) = since {
775            endpoint.push_str(&format!("&since={since}"));
776        }
777
778        let response: KrakenResponse<TradesResponse> = self
779            .send_request(Method::GET, &endpoint, None, false)
780            .await?;
781
782        response.result.ok_or_else(|| {
783            KrakenHttpError::ParseError("Missing result in trades response".to_string())
784        })
785    }
786
787    /// Requests an authentication token for WebSocket connections.
788    pub async fn get_websockets_token(&self) -> anyhow::Result<WebSocketToken, KrakenHttpError> {
789        if self.credential.is_none() {
790            return Err(KrakenHttpError::AuthenticationError(
791                "API credentials required for GetWebSocketsToken".to_string(),
792            ));
793        }
794
795        let response: KrakenResponse<WebSocketToken> = self
796            .send_request(Method::POST, "/0/private/GetWebSocketsToken", None, true)
797            .await?;
798
799        response.result.ok_or_else(|| {
800            KrakenHttpError::ParseError("Missing result in websockets token response".to_string())
801        })
802    }
803
804    /// Requests all open orders (requires authentication).
805    pub async fn get_open_orders(
806        &self,
807        trades: Option<bool>,
808        userref: Option<i64>,
809    ) -> anyhow::Result<IndexMap<String, SpotOrder>, KrakenHttpError> {
810        if self.credential.is_none() {
811            return Err(KrakenHttpError::AuthenticationError(
812                "API credentials required for OpenOrders".to_string(),
813            ));
814        }
815
816        let mut params = vec![];
817
818        if let Some(trades_flag) = trades {
819            params.push(format!("trades={trades_flag}"));
820        }
821
822        if let Some(userref_val) = userref {
823            params.push(format!("userref={userref_val}"));
824        }
825
826        let body = if params.is_empty() {
827            None
828        } else {
829            Some(params.join("&").into_bytes())
830        };
831
832        let response: KrakenResponse<SpotOpenOrdersResult> = self
833            .send_request(Method::POST, "/0/private/OpenOrders", body, true)
834            .await?;
835
836        let result = response.result.ok_or_else(|| {
837            KrakenHttpError::ParseError("Missing result in open orders response".to_string())
838        })?;
839
840        Ok(result.open)
841    }
842
843    /// Requests closed orders history (requires authentication).
844    pub async fn get_closed_orders(
845        &self,
846        trades: Option<bool>,
847        userref: Option<i64>,
848        start: Option<i64>,
849        end: Option<i64>,
850        ofs: Option<i32>,
851        closetime: Option<String>,
852    ) -> anyhow::Result<IndexMap<String, SpotOrder>, KrakenHttpError> {
853        if self.credential.is_none() {
854            return Err(KrakenHttpError::AuthenticationError(
855                "API credentials required for ClosedOrders".to_string(),
856            ));
857        }
858
859        let mut params = vec![];
860
861        if let Some(trades_flag) = trades {
862            params.push(format!("trades={trades_flag}"));
863        }
864
865        if let Some(userref_val) = userref {
866            params.push(format!("userref={userref_val}"));
867        }
868
869        if let Some(start_val) = start {
870            params.push(format!("start={start_val}"));
871        }
872
873        if let Some(end_val) = end {
874            params.push(format!("end={end_val}"));
875        }
876
877        if let Some(ofs_val) = ofs {
878            params.push(format!("ofs={ofs_val}"));
879        }
880
881        if let Some(closetime_val) = closetime {
882            params.push(format!("closetime={closetime_val}"));
883        }
884
885        let body = if params.is_empty() {
886            None
887        } else {
888            Some(params.join("&").into_bytes())
889        };
890
891        let response: KrakenResponse<SpotClosedOrdersResult> = self
892            .send_request(Method::POST, "/0/private/ClosedOrders", body, true)
893            .await?;
894
895        let result = response.result.ok_or_else(|| {
896            KrakenHttpError::ParseError("Missing result in closed orders response".to_string())
897        })?;
898
899        Ok(result.closed)
900    }
901
902    /// Requests trades history (requires authentication).
903    pub async fn get_trades_history(
904        &self,
905        trade_type: Option<String>,
906        trades: Option<bool>,
907        start: Option<i64>,
908        end: Option<i64>,
909        ofs: Option<i32>,
910    ) -> anyhow::Result<IndexMap<String, SpotTrade>, KrakenHttpError> {
911        if self.credential.is_none() {
912            return Err(KrakenHttpError::AuthenticationError(
913                "API credentials required for TradesHistory".to_string(),
914            ));
915        }
916
917        let mut params = vec![];
918
919        if let Some(type_val) = trade_type {
920            params.push(format!("type={type_val}"));
921        }
922
923        if let Some(trades_flag) = trades {
924            params.push(format!("trades={trades_flag}"));
925        }
926
927        if let Some(start_val) = start {
928            params.push(format!("start={start_val}"));
929        }
930
931        if let Some(end_val) = end {
932            params.push(format!("end={end_val}"));
933        }
934
935        if let Some(ofs_val) = ofs {
936            params.push(format!("ofs={ofs_val}"));
937        }
938
939        let body = if params.is_empty() {
940            None
941        } else {
942            Some(params.join("&").into_bytes())
943        };
944
945        let response: KrakenResponse<SpotTradesHistoryResult> = self
946            .send_request(Method::POST, "/0/private/TradesHistory", body, true)
947            .await?;
948
949        let result = response.result.ok_or_else(|| {
950            KrakenHttpError::ParseError("Missing result in trades history response".to_string())
951        })?;
952
953        Ok(result.trades)
954    }
955
956    /// Submits a new order (requires authentication).
957    pub async fn add_order(
958        &self,
959        params: &KrakenSpotAddOrderParams,
960    ) -> anyhow::Result<SpotAddOrderResponse, KrakenHttpError> {
961        if self.credential.is_none() {
962            return Err(KrakenHttpError::MissingCredentials);
963        }
964
965        let param_string = serde_urlencoded::to_string(params).map_err(|e| {
966            KrakenHttpError::RequestNotStarted(format!("Failed to encode params: {e}"))
967        })?;
968        let body = Some(param_string.into_bytes());
969
970        let response: KrakenResponse<SpotAddOrderResponse> = self
971            .send_request_once(Method::POST, "/0/private/AddOrder", body, true)
972            .await?;
973
974        response
975            .result
976            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
977    }
978
979    /// Submits multiple orders in a single batch request (requires authentication).
980    pub async fn add_order_batch(
981        &self,
982        params: &KrakenSpotAddOrderBatchParams,
983    ) -> anyhow::Result<SpotAddOrderBatchResponse, KrakenHttpError> {
984        let credential = self
985            .credential
986            .as_ref()
987            .ok_or(KrakenHttpError::MissingCredentials)?;
988
989        let cancellation_token = self.cancellation_token();
990        let _guard = self.lock_order_request(&cancellation_token).await?;
991
992        let endpoint = "/0/private/AddOrderBatch";
993        let nonce = self.generate_nonce();
994
995        let mut json_body = serde_json::json!({
996            "nonce": nonce.to_string(),
997            "pair": params.pair,
998            "orders": params.orders,
999        });
1000
1001        if let Some(aclass) = &params.asset_class {
1002            json_body["asset_class"] = serde_json::json!(aclass);
1003        }
1004        let json_str = serde_json::to_string(&json_body)
1005            .map_err(|e| KrakenHttpError::RequestNotStarted(format!("Failed to serialize: {e}")))?;
1006
1007        let signature = credential
1008            .sign_spot_json(endpoint, nonce, &json_str)
1009            .map_err(|e| KrakenHttpError::RequestNotStarted(format!("Failed to sign: {e}")))?;
1010
1011        let mut headers = Self::default_headers();
1012        headers.insert("API-Key".to_string(), credential.api_key().to_string());
1013        headers.insert("API-Sign".to_string(), signature);
1014        headers.insert("Content-Type".to_string(), "application/json".to_string());
1015
1016        let response = self
1017            .send_order_request(
1018                Method::POST,
1019                endpoint,
1020                headers,
1021                Some(json_str.into_bytes()),
1022                &cancellation_token,
1023            )
1024            .await?;
1025
1026        if !response.status.is_success() {
1027            return Err(KrakenHttpError::NetworkError(format!(
1028                "HTTP {:?} for {}",
1029                response.status, endpoint
1030            )));
1031        }
1032
1033        let parsed: KrakenResponse<SpotAddOrderBatchResponse> =
1034            serde_json::from_slice(&response.body).map_err(|e| {
1035                KrakenHttpError::ParseError(format!("Failed to parse JSON response: {e}"))
1036            })?;
1037
1038        if !parsed.error.is_empty() {
1039            return Err(KrakenHttpError::ApiError(parsed.error));
1040        }
1041
1042        parsed
1043            .result
1044            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
1045    }
1046
1047    /// Cancels an open order (requires authentication).
1048    pub async fn cancel_order(
1049        &self,
1050        params: &KrakenSpotCancelOrderParams,
1051    ) -> anyhow::Result<SpotCancelOrderResponse, KrakenHttpError> {
1052        if self.credential.is_none() {
1053            return Err(KrakenHttpError::MissingCredentials);
1054        }
1055
1056        let param_string = serde_urlencoded::to_string(params)
1057            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to encode params: {e}")))?;
1058
1059        let body = Some(param_string.into_bytes());
1060
1061        let response: KrakenResponse<SpotCancelOrderResponse> = self
1062            .send_request_once(Method::POST, "/0/private/CancelOrder", body, true)
1063            .await?;
1064
1065        response
1066            .result
1067            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
1068    }
1069
1070    /// Cancels multiple orders in a single batch request (max 50 orders).
1071    pub async fn cancel_order_batch(
1072        &self,
1073        params: &KrakenSpotCancelOrderBatchParams,
1074    ) -> anyhow::Result<SpotCancelOrderBatchResponse, KrakenHttpError> {
1075        let credential = self
1076            .credential
1077            .as_ref()
1078            .ok_or(KrakenHttpError::MissingCredentials)?;
1079
1080        // Serialize authenticated requests to ensure nonces arrive at Kraken in order
1081        let _guard = self.auth_mutex.lock().await;
1082
1083        let endpoint = "/0/private/CancelOrderBatch";
1084        let nonce = self.generate_nonce();
1085
1086        // CancelOrderBatch uses JSON body with nonce included
1087        let mut json_body = serde_json::json!({ "nonce": nonce.to_string() });
1088
1089        // Kraken keys transaction IDs and client order IDs separately, and rejects empty arrays.
1090        if !params.orders.is_empty() {
1091            json_body["orders"] = serde_json::json!(params.orders);
1092        }
1093
1094        if !params.cl_ord_ids.is_empty() {
1095            json_body["cl_ord_ids"] = serde_json::json!(params.cl_ord_ids);
1096        }
1097        let json_str = serde_json::to_string(&json_body)
1098            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to serialize: {e}")))?;
1099
1100        let signature = credential
1101            .sign_spot_json(endpoint, nonce, &json_str)
1102            .map_err(|e| KrakenHttpError::RequestNotStarted(format!("Failed to sign: {e}")))?;
1103
1104        let mut headers = Self::default_headers();
1105        headers.insert("API-Key".to_string(), credential.api_key().to_string());
1106        headers.insert("API-Sign".to_string(), signature);
1107        headers.insert("Content-Type".to_string(), "application/json".to_string());
1108
1109        let url = format!("{}{endpoint}", self.base_url.expose());
1110        let rate_limit_keys = Self::rate_limit_keys(endpoint);
1111
1112        let response = self
1113            .client
1114            .request(
1115                Method::POST,
1116                url,
1117                None,
1118                Some(headers),
1119                Some(json_str.into_bytes()),
1120                None,
1121                Some(rate_limit_keys),
1122            )
1123            .await
1124            .map_err(|e| {
1125                KrakenHttpError::NetworkError(format!(
1126                    "Request to {} failed: {e}",
1127                    self.base_url.origin()
1128                ))
1129            })?;
1130
1131        if response.status.as_u16() >= 400 {
1132            let status = response.status.as_u16();
1133            let body = String::from_utf8_lossy(&response.body).to_string();
1134
1135            if status == 401 || status == 403 {
1136                return Err(KrakenHttpError::AuthenticationError(format!(
1137                    "HTTP error {status}: {body}"
1138                )));
1139            }
1140            return Err(KrakenHttpError::NetworkError(format!(
1141                "HTTP error {status}: {body}"
1142            )));
1143        }
1144
1145        let response_text = String::from_utf8(response.body.to_vec())
1146            .map_err(|e| KrakenHttpError::ParseError(format!("Invalid UTF-8: {e}")))?;
1147
1148        let kraken_response: KrakenResponse<SpotCancelOrderBatchResponse> =
1149            serde_json::from_str(&response_text).map_err(|e| {
1150                KrakenHttpError::ParseError(format!("Failed to parse response: {e}"))
1151            })?;
1152
1153        if !kraken_response.error.is_empty() {
1154            return Err(KrakenHttpError::ApiError(kraken_response.error));
1155        }
1156
1157        kraken_response
1158            .result
1159            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
1160    }
1161
1162    /// Cancels all open orders (requires authentication).
1163    pub async fn cancel_all_orders(
1164        &self,
1165    ) -> anyhow::Result<SpotCancelOrderResponse, KrakenHttpError> {
1166        if self.credential.is_none() {
1167            return Err(KrakenHttpError::MissingCredentials);
1168        }
1169
1170        let response: KrakenResponse<SpotCancelOrderResponse> = self
1171            .send_request_once(Method::POST, "/0/private/CancelAll", None, true)
1172            .await?;
1173
1174        response
1175            .result
1176            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
1177    }
1178
1179    /// Edits an existing order (cancel and replace).
1180    pub async fn edit_order(
1181        &self,
1182        params: &KrakenSpotEditOrderParams,
1183    ) -> anyhow::Result<SpotEditOrderResponse, KrakenHttpError> {
1184        if self.credential.is_none() {
1185            return Err(KrakenHttpError::AuthenticationError(
1186                "API credentials required for editing orders".to_string(),
1187            ));
1188        }
1189
1190        let param_string = serde_urlencoded::to_string(params)
1191            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to encode params: {e}")))?;
1192
1193        let body = Some(param_string.into_bytes());
1194
1195        let response: KrakenResponse<SpotEditOrderResponse> = self
1196            .send_request_once(Method::POST, "/0/private/EditOrder", body, true)
1197            .await?;
1198
1199        response
1200            .result
1201            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
1202    }
1203
1204    /// Amends an existing order in-place (no cancel/replace).
1205    pub async fn amend_order(
1206        &self,
1207        params: &KrakenSpotAmendOrderParams,
1208    ) -> anyhow::Result<SpotAmendOrderResponse, KrakenHttpError> {
1209        if self.credential.is_none() {
1210            return Err(KrakenHttpError::MissingCredentials);
1211        }
1212
1213        let param_string = serde_urlencoded::to_string(params).map_err(|e| {
1214            KrakenHttpError::RequestNotStarted(format!("Failed to encode params: {e}"))
1215        })?;
1216
1217        let body = Some(param_string.into_bytes());
1218
1219        let response: KrakenResponse<SpotAmendOrderResponse> = self
1220            .send_request_once(Method::POST, "/0/private/AmendOrder", body, true)
1221            .await?;
1222
1223        response
1224            .result
1225            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
1226    }
1227
1228    /// Requests account balances (requires authentication).
1229    pub async fn get_balance(&self) -> anyhow::Result<BalanceResponse, KrakenHttpError> {
1230        if self.credential.is_none() {
1231            return Err(KrakenHttpError::AuthenticationError(
1232                "API credentials required for Balance".to_string(),
1233            ));
1234        }
1235
1236        let response: KrakenResponse<BalanceResponse> = self
1237            .send_request(Method::POST, "/0/private/Balance", None, true)
1238            .await?;
1239
1240        response.result.ok_or_else(|| {
1241            KrakenHttpError::ParseError("Missing result in balance response".to_string())
1242        })
1243    }
1244
1245    /// Requests account balances including held amounts (requires authentication).
1246    ///
1247    /// Unlike [`Self::get_balance`], which reports only total wallet amounts, this additionally
1248    /// reports `hold_trade`: the portion of each balance Kraken has reserved against resting
1249    /// orders. Required to populate `locked` on cash balances.
1250    pub async fn get_balance_ex(&self) -> anyhow::Result<BalanceExResponse, KrakenHttpError> {
1251        if self.credential.is_none() {
1252            return Err(KrakenHttpError::AuthenticationError(
1253                "API credentials required for BalanceEx".to_string(),
1254            ));
1255        }
1256
1257        let response: KrakenResponse<BalanceExResponse> = self
1258            .send_request(Method::POST, "/0/private/BalanceEx", None, true)
1259            .await?;
1260
1261        response.result.ok_or_else(|| {
1262            KrakenHttpError::ParseError("Missing result in extended balance response".to_string())
1263        })
1264    }
1265
1266    /// Requests margin account summary (requires authentication).
1267    ///
1268    /// Unlike `get_balance` which returns per-currency wallet amounts, this returns margin
1269    /// accounting metrics: used margin, free margin, equity, all denominated in `asset`
1270    /// (defaults to `"ZUSD"` when `None`). Only meaningful for spot margin accounts.
1271    pub async fn get_trade_balance(
1272        &self,
1273        asset: Option<&str>,
1274    ) -> anyhow::Result<TradeBalanceResponse, KrakenHttpError> {
1275        if self.credential.is_none() {
1276            return Err(KrakenHttpError::AuthenticationError(
1277                "API credentials required for TradeBalance".to_string(),
1278            ));
1279        }
1280
1281        let params = asset.map(|a| SpotTradeBalanceParams {
1282            asset: Some(a.to_string()),
1283        });
1284
1285        let body = params
1286            .as_ref()
1287            .and_then(|p| serde_urlencoded::to_string(p).ok())
1288            .map(|s| s.into_bytes());
1289
1290        let response: KrakenResponse<TradeBalanceResponse> = self
1291            .send_request(Method::POST, "/0/private/TradeBalance", body, true)
1292            .await?;
1293
1294        response.result.ok_or_else(|| {
1295            KrakenHttpError::ParseError("Missing result in TradeBalance response".to_string())
1296        })
1297    }
1298
1299    #[allow(
1300        dead_code,
1301        reason = "TradeVolume endpoint retained for account fee-rate follow-up"
1302    )]
1303    async fn get_trade_volume(
1304        &self,
1305        params: &SpotTradeVolumeParams,
1306    ) -> anyhow::Result<SpotTradeVolumeResponse, KrakenHttpError> {
1307        if self.credential.is_none() {
1308            return Err(KrakenHttpError::MissingCredentials);
1309        }
1310
1311        let response: KrakenResponse<SpotTradeVolumeResponse> = self
1312            .send_json_request(Method::POST, "/0/private/TradeVolume", params, true)
1313            .await?;
1314
1315        response.result.ok_or_else(|| {
1316            KrakenHttpError::ParseError("Missing result in TradeVolume response".to_string())
1317        })
1318    }
1319
1320    /// Requests open spot margin positions (requires authentication).
1321    pub async fn get_open_positions(
1322        &self,
1323        params: &SpotOpenPositionsParams,
1324    ) -> anyhow::Result<SpotOpenPositionsResponse, KrakenHttpError> {
1325        if self.credential.is_none() {
1326            return Err(KrakenHttpError::AuthenticationError(
1327                "API credentials required for OpenPositions".to_string(),
1328            ));
1329        }
1330
1331        let body = serde_urlencoded::to_string(params)
1332            .ok()
1333            .filter(|s| !s.is_empty())
1334            .map(|s| s.into_bytes());
1335
1336        let response: KrakenResponse<SpotOpenPositionsResponse> = self
1337            .send_request(Method::POST, "/0/private/OpenPositions", body, true)
1338            .await?;
1339
1340        response.result.ok_or_else(|| {
1341            KrakenHttpError::ParseError("Missing result in OpenPositions response".to_string())
1342        })
1343    }
1344}
1345
1346#[derive(Clone)]
1347enum RequestBody {
1348    Form(Option<Vec<u8>>),
1349    Json(serde_json::Value),
1350}
1351
1352#[allow(
1353    dead_code,
1354    reason = "TradeVolume request types retained for account fee-rate follow-up"
1355)]
1356#[derive(Clone, Serialize)]
1357struct SpotTradeVolumeParams {
1358    pair: SpotTradeVolumePairs,
1359}
1360
1361#[allow(
1362    dead_code,
1363    reason = "TradeVolume request types retained for account fee-rate follow-up"
1364)]
1365#[derive(Clone, Serialize)]
1366#[serde(untagged)]
1367enum SpotTradeVolumePairs {
1368    Names(String),
1369    Classified(Vec<SpotTradeVolumePair>),
1370}
1371
1372#[allow(
1373    dead_code,
1374    reason = "TradeVolume request types retained for account fee-rate follow-up"
1375)]
1376#[derive(Clone, Serialize)]
1377struct SpotTradeVolumePair {
1378    asset: String,
1379    aclass: SpotTradeVolumeAssetClass,
1380}
1381
1382#[allow(
1383    dead_code,
1384    reason = "TradeVolume request types retained for account fee-rate follow-up"
1385)]
1386#[derive(Clone, Copy, Serialize)]
1387#[serde(rename_all = "snake_case")]
1388enum SpotTradeVolumeAssetClass {
1389    EquityPair,
1390}
1391
1392pub(crate) type SpotBatchOrder = (
1393    InstrumentId,
1394    ClientOrderId,
1395    OrderSide,
1396    OrderType,
1397    Quantity,
1398    TimeInForce,
1399    Option<UnixNanos>,
1400    Option<Price>,
1401    Option<Price>,
1402    Option<TriggerType>,
1403    Option<Decimal>,
1404    Option<Decimal>,
1405    bool,
1406    bool,
1407    bool,
1408    Option<Quantity>,
1409    Option<u16>,
1410);
1411
1412/// High-level HTTP client for the Kraken Spot REST API.
1413///
1414/// This client wraps the raw client and provides Nautilus domain types.
1415/// It maintains an instrument cache and uses it to parse venue responses
1416/// into Nautilus domain objects.
1417#[cfg_attr(
1418    feature = "python",
1419    pyo3::pyclass(module = "nautilus_trader.adapters.kraken", from_py_object)
1420)]
1421#[cfg_attr(
1422    feature = "python",
1423    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.kraken")
1424)]
1425pub struct KrakenSpotHttpClient {
1426    pub(crate) inner: Arc<KrakenSpotRawHttpClient>,
1427    pub(crate) instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
1428    /// Maps a Kraken `altname` to the `AssetPairs` key used as the instrument `raw_symbol`.
1429    ///
1430    /// Kraken spells the same pair two ways: `OpenPositions` returns the key (`XXBTZUSD`) while
1431    /// `OpenOrders` and `TradesHistory` return the altname (`XBTUSD`). The altname is not derivable
1432    /// from a cached instrument, because `normalize_spot_symbol` rewrites Kraken's currency codes,
1433    /// so it is captured from `AssetPairs` while the definitions are in hand.
1434    pair_aliases: Arc<AtomicMap<Ustr, Ustr>>,
1435    leverage_tiers_cache: LeverageTiersCache,
1436    clock: &'static AtomicTime,
1437    cache_initialized: Arc<AtomicBool>,
1438}
1439
1440impl Clone for KrakenSpotHttpClient {
1441    fn clone(&self) -> Self {
1442        Self {
1443            inner: self.inner.clone(),
1444            instruments_cache: self.instruments_cache.clone(),
1445            pair_aliases: self.pair_aliases.clone(),
1446            leverage_tiers_cache: self.leverage_tiers_cache.clone(),
1447            cache_initialized: self.cache_initialized.clone(),
1448            clock: self.clock,
1449        }
1450    }
1451}
1452
1453impl Default for KrakenSpotHttpClient {
1454    fn default() -> Self {
1455        Self::new(
1456            KrakenEnvironment::Live,
1457            None,
1458            60,
1459            None,
1460            None,
1461            None,
1462            None,
1463            KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND,
1464        )
1465        .expect("Failed to create default KrakenSpotHttpClient")
1466    }
1467}
1468
1469impl Debug for KrakenSpotHttpClient {
1470    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1471        f.debug_struct(stringify!(KrakenSpotHttpClient))
1472            .field("inner", &self.inner)
1473            .finish()
1474    }
1475}
1476
1477impl KrakenSpotHttpClient {
1478    /// Creates a new [`KrakenSpotHttpClient`].
1479    #[expect(clippy::too_many_arguments)]
1480    pub fn new(
1481        environment: KrakenEnvironment,
1482        base_url_override: Option<String>,
1483        timeout_secs: u64,
1484        max_retries: Option<u32>,
1485        retry_delay_ms: Option<u64>,
1486        retry_delay_max_ms: Option<u64>,
1487        proxy_url: Option<String>,
1488        max_requests_per_second: u32,
1489    ) -> anyhow::Result<Self> {
1490        Ok(Self {
1491            inner: Arc::new(KrakenSpotRawHttpClient::new(
1492                environment,
1493                base_url_override,
1494                timeout_secs,
1495                max_retries,
1496                retry_delay_ms,
1497                retry_delay_max_ms,
1498                proxy_url,
1499                max_requests_per_second,
1500            )?),
1501            instruments_cache: Arc::new(AtomicMap::new()),
1502            pair_aliases: Arc::new(AtomicMap::new()),
1503            leverage_tiers_cache: Arc::new(AtomicMap::new()),
1504            cache_initialized: Arc::new(AtomicBool::new(false)),
1505            clock: get_atomic_clock_realtime(),
1506        })
1507    }
1508
1509    /// Creates a new [`KrakenSpotHttpClient`] with credentials.
1510    #[expect(clippy::too_many_arguments)]
1511    pub fn with_credentials(
1512        api_key: String,
1513        api_secret: String,
1514        environment: KrakenEnvironment,
1515        base_url_override: Option<String>,
1516        timeout_secs: u64,
1517        max_retries: Option<u32>,
1518        retry_delay_ms: Option<u64>,
1519        retry_delay_max_ms: Option<u64>,
1520        proxy_url: Option<String>,
1521        max_requests_per_second: u32,
1522    ) -> anyhow::Result<Self> {
1523        Ok(Self {
1524            inner: Arc::new(KrakenSpotRawHttpClient::with_credentials(
1525                api_key,
1526                api_secret,
1527                environment,
1528                base_url_override,
1529                timeout_secs,
1530                max_retries,
1531                retry_delay_ms,
1532                retry_delay_max_ms,
1533                proxy_url,
1534                max_requests_per_second,
1535            )?),
1536            instruments_cache: Arc::new(AtomicMap::new()),
1537            pair_aliases: Arc::new(AtomicMap::new()),
1538            leverage_tiers_cache: Arc::new(AtomicMap::new()),
1539            cache_initialized: Arc::new(AtomicBool::new(false)),
1540            clock: get_atomic_clock_realtime(),
1541        })
1542    }
1543
1544    /// Creates a new [`KrakenSpotHttpClient`] loading credentials from environment variables.
1545    ///
1546    /// Looks for `KRAKEN_SPOT_API_KEY` and `KRAKEN_SPOT_API_SECRET`.
1547    ///
1548    /// Note: Kraken Spot does not have a testnet/demo environment.
1549    ///
1550    /// Falls back to unauthenticated client if credentials are not set.
1551    #[expect(clippy::too_many_arguments)]
1552    pub fn from_env(
1553        environment: KrakenEnvironment,
1554        base_url_override: Option<String>,
1555        timeout_secs: u64,
1556        max_retries: Option<u32>,
1557        retry_delay_ms: Option<u64>,
1558        retry_delay_max_ms: Option<u64>,
1559        proxy_url: Option<String>,
1560        max_requests_per_second: u32,
1561    ) -> anyhow::Result<Self> {
1562        if let Some(credential) = KrakenCredential::from_env_spot() {
1563            let (api_key, api_secret) = credential.into_parts();
1564            Self::with_credentials(
1565                api_key,
1566                api_secret,
1567                environment,
1568                base_url_override,
1569                timeout_secs,
1570                max_retries,
1571                retry_delay_ms,
1572                retry_delay_max_ms,
1573                proxy_url,
1574                max_requests_per_second,
1575            )
1576        } else {
1577            Self::new(
1578                environment,
1579                base_url_override,
1580                timeout_secs,
1581                max_retries,
1582                retry_delay_ms,
1583                retry_delay_max_ms,
1584                proxy_url,
1585                max_requests_per_second,
1586            )
1587        }
1588    }
1589
1590    /// Cancels all pending HTTP requests.
1591    pub fn cancel_all_requests(&self) {
1592        self.inner.cancel_all_requests();
1593    }
1594
1595    /// Replaces the canceled token so requests can proceed after reconnect.
1596    pub fn reset_cancellation_token(&self) {
1597        self.inner.reset_cancellation_token();
1598    }
1599
1600    /// Returns a clone of the current cancellation token.
1601    pub fn cancellation_token(&self) -> CancellationToken {
1602        self.inner.cancellation_token()
1603    }
1604
1605    /// Caches an instrument for symbol lookup.
1606    pub fn cache_instrument(&self, instrument: InstrumentAny) {
1607        self.record_instrument_aliases(std::slice::from_ref(&instrument));
1608        self.instruments_cache
1609            .insert(instrument.symbol().inner(), instrument);
1610        self.cache_initialized.store(true, Ordering::Release);
1611    }
1612
1613    /// Caches multiple instruments for symbol lookup.
1614    pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
1615        self.record_instrument_aliases(instruments);
1616        self.instruments_cache.rcu(|m| {
1617            for instrument in instruments {
1618                m.insert(instrument.symbol().inner(), instrument.clone());
1619            }
1620        });
1621        self.cache_initialized.store(true, Ordering::Release);
1622    }
1623
1624    /// Records the altname each instrument carries, so a client fed through the cache APIs can
1625    /// resolve altname-spelled rows without the `AssetPairs` response.
1626    fn record_instrument_aliases(&self, instruments: &[InstrumentAny]) {
1627        let aliases: Vec<(Ustr, Ustr)> = instruments
1628            .iter()
1629            .filter_map(|instrument| {
1630                let altname = instrument.info()?.get_str(KRAKEN_ALTNAME_KEY)?;
1631                Some((Ustr::from(altname), instrument.raw_symbol().inner()))
1632            })
1633            .collect();
1634
1635        if aliases.is_empty() {
1636            return;
1637        }
1638
1639        self.pair_aliases.rcu(|m| {
1640            for (altname, pair_name) in &aliases {
1641                m.insert(*altname, *pair_name);
1642            }
1643        });
1644    }
1645
1646    /// Gets an instrument from the cache by symbol.
1647    pub fn get_cached_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
1648        self.instruments_cache.get_cloned(symbol)
1649    }
1650
1651    /// Records the `altname` of each pair against the `AssetPairs` key.
1652    ///
1653    /// Only differing spellings are stored, so a key is never shadowed by another pair's altname.
1654    fn record_pair_aliases(&self, pairs: &AssetPairsResponse) {
1655        let aliases: Vec<(Ustr, Ustr)> = pairs
1656            .iter()
1657            .filter(|(pair_name, definition)| definition.altname.as_str() != pair_name.as_str())
1658            .map(|(pair_name, definition)| (definition.altname, Ustr::from(pair_name)))
1659            .collect();
1660
1661        if aliases.is_empty() {
1662            return;
1663        }
1664
1665        self.pair_aliases.rcu(|m| {
1666            for (altname, pair_name) in &aliases {
1667                m.insert(*altname, *pair_name);
1668            }
1669        });
1670    }
1671
1672    /// Resolves a cached instrument from whichever spelling Kraken used for the pair.
1673    ///
1674    /// Matches the `AssetPairs` key first so a key always wins, then falls back to the altname
1675    /// recorded by [`Self::record_pair_aliases`].
1676    fn get_instrument_by_raw_symbol(&self, raw_symbol: &str) -> Option<InstrumentAny> {
1677        let instruments = self.instruments_cache.load();
1678
1679        if let Some(instrument) = instruments
1680            .values()
1681            .find(|inst| inst.raw_symbol().as_str() == raw_symbol)
1682        {
1683            return Some(instrument.clone());
1684        }
1685
1686        let pair_name = self.pair_aliases.get_cloned(&Ustr::from(raw_symbol))?;
1687
1688        instruments
1689            .values()
1690            .find(|inst| inst.raw_symbol().inner() == pair_name)
1691            .cloned()
1692    }
1693
1694    fn generate_ts_init(&self) -> UnixNanos {
1695        self.clock.get_time_ns()
1696    }
1697
1698    // Kraken requires `asset_class=tokenized_asset` on every request that references a tokenized pair.
1699    fn asset_class_for(instrument: &InstrumentAny) -> Option<KrakenAssetClass> {
1700        if matches!(instrument, InstrumentAny::TokenizedAsset(_)) {
1701            Some(KrakenAssetClass::TokenizedAsset)
1702        } else {
1703            None
1704        }
1705    }
1706
1707    /// Requests an authentication token for WebSocket connections.
1708    pub async fn get_websockets_token(&self) -> anyhow::Result<WebSocketToken, KrakenHttpError> {
1709        self.inner.get_websockets_token().await
1710    }
1711
1712    /// Requests tradable instruments from Kraken.
1713    ///
1714    /// When `pairs` is `None` (loading all), also fetches tokenized asset pairs
1715    /// (xStocks) and merges them with the default currency pairs.
1716    pub async fn request_instruments(
1717        &self,
1718        pairs: Option<Vec<String>>,
1719    ) -> anyhow::Result<Vec<InstrumentAny>, KrakenHttpError> {
1720        let ts_init = self.generate_ts_init();
1721        let asset_pairs = self.inner.get_asset_pairs(pairs.clone(), None).await?;
1722        self.record_pair_aliases(&asset_pairs);
1723        let mut leverage_tiers = AHashMap::new();
1724
1725        let mut instruments: Vec<InstrumentAny> = asset_pairs
1726            .iter()
1727            .filter_map(|(pair_name, definition)| {
1728                match parse_spot_instrument(pair_name, definition, ts_init, ts_init) {
1729                    Ok(instrument) => Some((instrument, definition)),
1730                    Err(e) => {
1731                        log::warn!("Failed to parse instrument {pair_name}: {e}");
1732                        None
1733                    }
1734                }
1735            })
1736            .map(|(instrument, definition)| {
1737                let key = Ustr::from(instrument.raw_symbol().as_str());
1738                let tiers = (
1739                    definition.leverage_buy.clone(),
1740                    definition.leverage_sell.clone(),
1741                );
1742                leverage_tiers.insert(key, tiers);
1743                instrument
1744            })
1745            .collect();
1746
1747        if !leverage_tiers.is_empty() {
1748            self.leverage_tiers_cache.rcu(|cache| {
1749                cache.extend(
1750                    leverage_tiers
1751                        .iter()
1752                        .map(|(key, tiers)| (*key, tiers.clone())),
1753                );
1754            });
1755        }
1756
1757        // Also fetch tokenized asset pairs (xStocks). When loading all pairs this
1758        // picks up tokenized equities; when loading specific pairs it covers the
1759        // case where the requested symbols are tokenized assets.
1760        {
1761            match self
1762                .inner
1763                .get_asset_pairs(pairs, Some("tokenized_asset"))
1764                .await
1765            {
1766                Ok(tokenized_pairs) => {
1767                    if !tokenized_pairs.is_empty() {
1768                        log::debug!("Fetched {} tokenized asset pairs", tokenized_pairs.len());
1769                    }
1770                    self.record_pair_aliases(&tokenized_pairs);
1771                    let tokenized_instruments: Vec<InstrumentAny> =
1772                        tokenized_pairs
1773                            .iter()
1774                            .filter_map(|(pair_name, definition)| match parse_tokenized_instrument(
1775                                pair_name, definition, ts_init, ts_init,
1776                            ) {
1777                                Ok(instrument) => Some(instrument),
1778                                Err(e) => {
1779                                    log::warn!(
1780                                        "Failed to parse tokenized instrument {pair_name}: {e}"
1781                                    );
1782                                    None
1783                                }
1784                            })
1785                            .collect();
1786                    instruments.extend(tokenized_instruments);
1787                }
1788                Err(e) => {
1789                    log::warn!("Failed to fetch tokenized asset pairs: {e}");
1790                }
1791            }
1792        }
1793
1794        Ok(instruments)
1795    }
1796
1797    /// Requests the current market status for Kraken Spot instruments.
1798    ///
1799    /// Fetches both regular and tokenized asset pairs. The call returns an error if
1800    /// either fetch fails so callers can avoid emitting partial snapshots that would
1801    /// otherwise cause the missing tokenized symbols to be diffed as removed.
1802    pub async fn request_instrument_statuses(
1803        &self,
1804        pairs: Option<Vec<String>>,
1805    ) -> anyhow::Result<AHashMap<InstrumentId, MarketStatusAction>, KrakenHttpError> {
1806        let asset_pairs = self.inner.get_asset_pairs(pairs.clone(), None).await?;
1807        let mut statuses = collect_spot_statuses(&asset_pairs);
1808
1809        let tokenized_pairs = self
1810            .inner
1811            .get_asset_pairs(pairs, Some("tokenized_asset"))
1812            .await?;
1813        statuses.extend(collect_spot_statuses(&tokenized_pairs));
1814
1815        Ok(statuses)
1816    }
1817
1818    /// Requests historical trades for an instrument.
1819    pub async fn request_trades(
1820        &self,
1821        instrument_id: InstrumentId,
1822        start: Option<Timestamp>,
1823        end: Option<Timestamp>,
1824        limit: Option<u64>,
1825    ) -> anyhow::Result<Vec<TradeTick>, KrakenHttpError> {
1826        let instrument = self
1827            .get_cached_instrument(&instrument_id.symbol.inner())
1828            .ok_or_else(|| {
1829                KrakenHttpError::ParseError(
1830                    InstrumentLookupError::not_found(instrument_id).to_string(),
1831                )
1832            })?;
1833
1834        let raw_symbol = instrument.raw_symbol().to_string();
1835        let asset_class = Self::asset_class_for(&instrument);
1836        let ts_init = self.generate_ts_init();
1837
1838        // Kraken trades API expects nanoseconds since epoch as string
1839        let since = start.map(|dt| u64::try_from(dt.as_nanosecond()).unwrap_or(0).to_string());
1840        let response = self
1841            .inner
1842            .get_trades(&raw_symbol, since, asset_class)
1843            .await?;
1844
1845        let end_ns = end.map(|dt| u64::try_from(dt.as_nanosecond()).unwrap_or(0));
1846        let mut trades = Vec::new();
1847
1848        for (_pair_name, trade_arrays) in &response.data {
1849            for trade_array in trade_arrays {
1850                match parse_trade_tick_from_array(trade_array, &instrument, ts_init) {
1851                    Ok(trade_tick) => {
1852                        if let Some(end_nanos) = end_ns
1853                            && trade_tick.ts_event.as_u64() > end_nanos
1854                        {
1855                            continue;
1856                        }
1857                        trades.push(trade_tick);
1858                    }
1859                    Err(e) => {
1860                        log::warn!("Failed to parse trade tick: {e}");
1861                    }
1862                }
1863            }
1864        }
1865
1866        // Count-only keeps the most recent `limit` trades, not the oldest
1867        apply_count_limit(&mut trades, start, limit);
1868
1869        Ok(trades)
1870    }
1871
1872    /// Requests historical bars/OHLC data for an instrument.
1873    pub async fn request_bars(
1874        &self,
1875        bar_type: BarType,
1876        start: Option<Timestamp>,
1877        end: Option<Timestamp>,
1878        limit: Option<u64>,
1879    ) -> anyhow::Result<Vec<Bar>, KrakenHttpError> {
1880        let instrument_id = bar_type.instrument_id();
1881        let instrument = self
1882            .get_cached_instrument(&instrument_id.symbol.inner())
1883            .ok_or_else(|| {
1884                KrakenHttpError::ParseError(
1885                    InstrumentLookupError::not_found(instrument_id).to_string(),
1886                )
1887            })?;
1888
1889        let raw_symbol = instrument.raw_symbol().to_string();
1890        let asset_class = Self::asset_class_for(&instrument);
1891        let ts_init = self.generate_ts_init();
1892
1893        let interval = Some(
1894            bar_type_to_spot_interval(bar_type)
1895                .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?,
1896        );
1897
1898        // Kraken OHLC API expects Unix timestamp in seconds
1899        let since = start.map(|dt| dt.as_second());
1900        let end_ns = end.map(|dt| u64::try_from(dt.as_nanosecond()).unwrap_or(0));
1901        let response = self
1902            .inner
1903            .get_ohlc(&raw_symbol, interval, since, asset_class)
1904            .await?;
1905
1906        let mut bars = Vec::new();
1907
1908        for (_pair_name, ohlc_arrays) in &response.data {
1909            for ohlc_array in ohlc_arrays {
1910                if ohlc_array.len() < 8 {
1911                    let len = ohlc_array.len();
1912                    log::warn!("OHLC array too short: {len}");
1913                    continue;
1914                }
1915
1916                let ohlc = OhlcData {
1917                    time: ohlc_array[0].as_i64().unwrap_or(0),
1918                    open: ohlc_array[1].as_str().unwrap_or("0").to_string(),
1919                    high: ohlc_array[2].as_str().unwrap_or("0").to_string(),
1920                    low: ohlc_array[3].as_str().unwrap_or("0").to_string(),
1921                    close: ohlc_array[4].as_str().unwrap_or("0").to_string(),
1922                    vwap: ohlc_array[5].as_str().unwrap_or("0").to_string(),
1923                    volume: ohlc_array[6].as_str().unwrap_or("0").to_string(),
1924                    count: ohlc_array[7].as_i64().unwrap_or(0),
1925                };
1926
1927                match parse_bar(&ohlc, &instrument, bar_type, ts_init) {
1928                    Ok(bar) => {
1929                        if let Some(end_nanos) = end_ns
1930                            && bar.ts_event.as_u64() > end_nanos
1931                        {
1932                            continue;
1933                        }
1934                        bars.push(bar);
1935                    }
1936                    Err(e) => {
1937                        log::warn!("Failed to parse bar: {e}");
1938                    }
1939                }
1940            }
1941        }
1942
1943        // Kraken returns the page oldest-first; keep the most recent `limit`
1944        // bars for count-only requests rather than the oldest (issue #4254).
1945        apply_count_limit(&mut bars, start, limit);
1946
1947        Ok(bars)
1948    }
1949
1950    /// Requests an order book snapshot for an instrument.
1951    pub async fn request_book_snapshot(
1952        &self,
1953        instrument_id: InstrumentId,
1954        depth: Option<u32>,
1955    ) -> anyhow::Result<OrderBook, KrakenHttpError> {
1956        let instrument = self
1957            .get_cached_instrument(&instrument_id.symbol.inner())
1958            .ok_or_else(|| {
1959                KrakenHttpError::ParseError(
1960                    InstrumentLookupError::not_found(instrument_id).to_string(),
1961                )
1962            })?;
1963
1964        let raw_symbol = instrument.raw_symbol().to_string();
1965        let asset_class = Self::asset_class_for(&instrument);
1966        let price_precision = instrument.price_precision();
1967        let size_precision = instrument.size_precision();
1968        let ts_event = self.generate_ts_init();
1969
1970        let response = self
1971            .inner
1972            .get_book_depth(&raw_symbol, depth, asset_class)
1973            .await?;
1974
1975        let book_data = response.values().next().ok_or_else(|| {
1976            KrakenHttpError::ParseError(format!("No book data returned for {instrument_id}"))
1977        })?;
1978
1979        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
1980
1981        // Pass sequence=0 so the snapshot does not advance the book's high-water sequence,
1982        // the WS subscription owns sequencing once it starts streaming deltas.
1983        for (i, level) in book_data.bids.iter().enumerate() {
1984            let price_str = level.first().and_then(|v| v.as_str()).unwrap_or("0");
1985            let size_str = level.get(1).and_then(|v| v.as_str()).unwrap_or("0");
1986            let price = Price::from_decimal_dp(
1987                Decimal::from_str_exact(price_str).unwrap_or(Decimal::ZERO),
1988                price_precision,
1989            )
1990            .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
1991            let size = Quantity::from_decimal_dp(
1992                Decimal::from_str_exact(size_str).unwrap_or(Decimal::ZERO),
1993                size_precision,
1994            )
1995            .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
1996            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
1997            book.add(order, 0, 0, ts_event);
1998        }
1999
2000        let bids_len = book_data.bids.len();
2001
2002        for (i, level) in book_data.asks.iter().enumerate() {
2003            let price_str = level.first().and_then(|v| v.as_str()).unwrap_or("0");
2004            let size_str = level.get(1).and_then(|v| v.as_str()).unwrap_or("0");
2005            let price = Price::from_decimal_dp(
2006                Decimal::from_str_exact(price_str).unwrap_or(Decimal::ZERO),
2007                price_precision,
2008            )
2009            .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
2010            let size = Quantity::from_decimal_dp(
2011                Decimal::from_str_exact(size_str).unwrap_or(Decimal::ZERO),
2012                size_precision,
2013            )
2014            .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?;
2015            let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
2016            book.add(order, 0, 0, ts_event);
2017        }
2018
2019        Ok(book)
2020    }
2021
2022    /// Requests account state (balances) from Kraken.
2023    ///
2024    /// In cash mode returns wallet balances only.
2025    /// In margin mode additionally calls `TradeBalance` to build [`MarginBalance`] entries.
2026    /// `margin_balance_asset` selects the summary-display denomination for `TradeBalance`
2027    /// (e.g. `"ZUSD"`, `"ZGBP"`); `None` lets Kraken default to `ZUSD`.
2028    ///
2029    /// Callers that also need the `TradeBalance` metrics dictionary should use
2030    /// [`Self::request_account_state_with_metrics`] to avoid issuing two `TradeBalance`
2031    /// HTTP requests per account update.
2032    pub async fn request_account_state(
2033        &self,
2034        account_id: AccountId,
2035        account_type: AccountType,
2036        margin_balance_asset: Option<&str>,
2037    ) -> anyhow::Result<AccountState> {
2038        self.request_account_state_with_metrics(account_id, account_type, margin_balance_asset)
2039            .await
2040            .map(|(state, _)| state)
2041    }
2042
2043    /// Requests the full margin account snapshot in a single round-trip.
2044    ///
2045    /// Returns the [`AccountState`] (including `MarginBalance` entries when
2046    /// `account_type` is `Margin`) and the `TradeBalance` metrics dictionary that
2047    /// callers attach to `AccountState.info`. In cash mode the metrics map is empty
2048    /// and `TradeBalance` is not called.
2049    ///
2050    /// In margin mode, replaces the raw `margin_balance_asset` wallet with a
2051    /// synthetic [`AccountBalance`] using `total = e` and `free = mf` from
2052    /// `TradeBalance`. Kraken reports these values across all collateral, which
2053    /// avoids clamping free margin to one wallet bucket in multi-asset accounts.
2054    ///
2055    /// Wallet balances come from `BalanceEx`, whose per-asset `hold_trade` gives the amount
2056    /// Kraken has reserved against resting orders and populates `locked`. Net credit
2057    /// (`credit - credit_used`, returned only for credit-line accounts) is included in `total`,
2058    /// so `free` derives to Kraken's available balance of
2059    /// `balance + credit - credit_used - hold_trade`.
2060    ///
2061    /// The single shared fetch keeps Kraken rate-limit usage symmetric with `BalanceEx`
2062    /// (one request per account update), instead of two as if `request_account_state`
2063    /// and `request_margin_metrics` were called in sequence.
2064    pub async fn request_account_state_with_metrics(
2065        &self,
2066        account_id: AccountId,
2067        account_type: AccountType,
2068        margin_balance_asset: Option<&str>,
2069    ) -> anyhow::Result<(AccountState, IndexMap<String, String>)> {
2070        let balances_raw = self.inner.get_balance_ex().await?;
2071        let ts_init = self.generate_ts_init();
2072
2073        let (margins, metrics, margin_entry, target_code) = if account_type == AccountType::Margin {
2074            let snapshot = self
2075                .fetch_trade_balance_snapshot(margin_balance_asset)
2076                .await?;
2077            let target_code = normalize_currency_code(margin_balance_asset.unwrap_or("ZUSD"));
2078            let currency = Currency::new(target_code, 8, 0, "0", CurrencyType::Crypto);
2079            let margin_entry = AccountBalance::from_total_and_free(
2080                snapshot.equity,
2081                snapshot.free_margin,
2082                currency,
2083            )
2084            .context("Failed to build synthetic margin AccountBalance from TradeBalance")?;
2085
2086            (
2087                snapshot.margins,
2088                snapshot.metrics,
2089                Some(margin_entry),
2090                target_code,
2091            )
2092        } else {
2093            (Vec::new(), IndexMap::new(), None, "")
2094        };
2095
2096        let skip_margin_wallet = margin_entry.is_some();
2097
2098        let balances: Vec<AccountBalance> = balances_raw
2099            .iter()
2100            .filter_map(|(currency_code, entry)| {
2101                let balance = Decimal::from_str_exact(&entry.balance).ok()?;
2102                let credit = optional_credit_amount(entry.credit.as_deref())?;
2103                let credit_used = optional_credit_amount(entry.credit_used.as_deref())?;
2104
2105                // Kraken defines available funds as `balance + credit - credit_used -
2106                // hold_trade`, so net credit belongs in `total` for `free` to derive to it.
2107                let total = balance + credit - credit_used;
2108
2109                let normalized_code = normalize_currency_code(currency_code);
2110
2111                if skip_margin_wallet && normalized_code == target_code {
2112                    return None;
2113                }
2114
2115                let locked = Decimal::from_str_exact(&entry.hold_trade).ok()?;
2116                let currency =
2117                    Currency::new(normalized_code, 8, 0, normalized_code, CurrencyType::Crypto);
2118                AccountBalance::from_total_and_locked(total, locked, currency).ok()
2119            })
2120            .chain(margin_entry)
2121            .collect();
2122
2123        let state = AccountState::new(
2124            account_id,
2125            account_type,
2126            balances,
2127            margins,
2128            true,
2129            UUID4::new(),
2130            ts_init,
2131            ts_init,
2132            None,
2133        );
2134
2135        Ok((state, metrics))
2136    }
2137
2138    /// Fetches `TradeBalance` once and returns both the parsed [`MarginBalance`] entries
2139    /// and the metrics dictionary surfaced through `AccountState.info`.
2140    ///
2141    /// # Margin mapping rationale
2142    ///
2143    /// Kraken's `TradeBalance` returns a single used-margin value `m` ("margin amount
2144    /// of open positions") and does not split into separate initial- and maintenance-
2145    /// margin figures. Kraken's "maintenance margin" is a liquidation-level percentage
2146    /// threshold (around 80% margin level), not a collateral money figure.
2147    ///
2148    /// [`nautilus_model::accounts::MarginAccount::recalculate_balance`] sums
2149    /// `initial + maintenance` to compute `locked`, so duplicating `m` into both fields
2150    /// would double-lock equity and diverge from Kraken's reported `mf = e - m`.
2151    /// `m` is therefore mapped to `initial`, with `maintenance = Money::zero(currency)`.
2152    async fn fetch_trade_balance_snapshot(
2153        &self,
2154        asset: Option<&str>,
2155    ) -> anyhow::Result<TradeBalanceSnapshot> {
2156        let tb = self.inner.get_trade_balance(asset).await?;
2157
2158        let used_margin = Decimal::from_str_exact(&tb.m)
2159            .with_context(|| format!("Failed to parse TradeBalance 'm' field {:?}", tb.m))?;
2160        let free_margin = Decimal::from_str_exact(&tb.mf)
2161            .with_context(|| format!("Failed to parse TradeBalance 'mf' field {:?}", tb.mf))?;
2162        let equity = Decimal::from_str_exact(&tb.e)
2163            .with_context(|| format!("Failed to parse TradeBalance 'e' field {:?}", tb.e))?;
2164
2165        let margins = if used_margin.is_zero() {
2166            Vec::new()
2167        } else {
2168            let currency = trade_balance_currency(asset);
2169            let initial = Money::from_decimal(used_margin, currency)
2170                .context("Failed to build initial margin from TradeBalance 'm'")?;
2171            let maintenance = Money::zero(currency);
2172            vec![MarginBalance::new(initial, maintenance, None)]
2173        };
2174
2175        let mut metrics = IndexMap::new();
2176        metrics.insert("equivalent_balance".to_string(), tb.eb);
2177        metrics.insert("trade_balance".to_string(), tb.tb);
2178        metrics.insert("used_margin".to_string(), tb.m);
2179        metrics.insert("unexecuted_value".to_string(), tb.uv);
2180        metrics.insert("unrealized_pnl".to_string(), tb.n);
2181        metrics.insert("cost_basis".to_string(), tb.c);
2182        metrics.insert("valuation".to_string(), tb.v);
2183        metrics.insert("equity".to_string(), tb.e);
2184        metrics.insert("free_margin".to_string(), tb.mf);
2185        if let Some(ml) = tb.ml {
2186            metrics.insert("margin_level".to_string(), ml);
2187        }
2188        metrics.insert(
2189            "asset".to_string(),
2190            normalize_currency_code(asset.unwrap_or("ZUSD")).to_string(),
2191        );
2192
2193        Ok(TradeBalanceSnapshot {
2194            margins,
2195            metrics,
2196            free_margin,
2197            equity,
2198        })
2199    }
2200
2201    /// Returns a flattened snapshot of Kraken's `TradeBalance` margin metrics.
2202    ///
2203    /// Caller is expected to invoke this only when operating in margin mode; consumers
2204    /// surface the values via `AccountState.info` (Python-side) for strategy access.
2205    /// Strings preserve venue precision exactly. Keys: `equivalent_balance`,
2206    /// `trade_balance`, `used_margin`, `unexecuted_value`, `unrealized_pnl`,
2207    /// `cost_basis`, `valuation`, `equity`, `free_margin`, `margin_level` (omitted
2208    /// when Kraken returns no value, i.e. no open positions), `asset`.
2209    ///
2210    /// When the metrics are needed alongside the [`AccountState`], prefer
2211    /// [`Self::request_account_state_with_metrics`] to share a single `TradeBalance`
2212    /// HTTP request between both.
2213    pub async fn request_margin_metrics(
2214        &self,
2215        asset: Option<&str>,
2216    ) -> anyhow::Result<IndexMap<String, String>> {
2217        self.fetch_trade_balance_snapshot(asset)
2218            .await
2219            .map(|snapshot| snapshot.metrics)
2220    }
2221
2222    /// Requests order status reports from Kraken.
2223    pub async fn request_order_status_reports(
2224        &self,
2225        account_id: AccountId,
2226        instrument_id: Option<InstrumentId>,
2227        start: Option<Timestamp>,
2228        end: Option<Timestamp>,
2229        open_only: bool,
2230    ) -> anyhow::Result<Vec<OrderStatusReport>> {
2231        self.request_order_status_reports_checked(account_id, instrument_id, start, end, open_only)
2232            .await
2233            .map(|(reports, _)| reports)
2234    }
2235
2236    /// Requests order status reports, also reporting what the read covered.
2237    ///
2238    /// An in-scope open order whose pair cannot be resolved, or that cannot be parsed, fails the
2239    /// read, except that a read scoped to one instrument skips an order whose pair it cannot
2240    /// resolve, since that order may be on another instrument. The coverage records each such
2241    /// skip, each closed order that cannot be resolved, each in-scope one that cannot be parsed,
2242    /// and a closed-order read that stops at its page cap, which it cannot place in time. A read
2243    /// scoped to an unheld spot instrument reads nothing and rules out no order.
2244    /// `ExecutionMassStatus::set_report_window` records whether it is complete for bounded history,
2245    /// and the single-order lookup whether it rules out an order it did not return.
2246    pub(crate) async fn request_order_status_reports_checked(
2247        &self,
2248        account_id: AccountId,
2249        instrument_id: Option<InstrumentId>,
2250        start: Option<Timestamp>,
2251        end: Option<Timestamp>,
2252        open_only: bool,
2253    ) -> anyhow::Result<(Vec<OrderStatusReport>, ReportCoverage)> {
2254        const PAGE_SIZE: i32 = 50;
2255
2256        let ts_init = self.generate_ts_init();
2257        let mut all_reports = Vec::new();
2258        let mut coverage = ReportCoverage::default();
2259
2260        // A scoped read for an instrument this client does not hold can match nothing, so return
2261        // before the request rather than falling through and reporting every instrument's rows.
2262        // A futures instrument names none of this client's orders, so that read is complete; a
2263        // spot one the listing lacks read nothing, so it rules out none of its orders.
2264        if let Some(ref target_id) = instrument_id
2265            && self
2266                .get_cached_instrument(&target_id.symbol.inner())
2267                .is_none()
2268        {
2269            if product_type_from_symbol(target_id.symbol.as_str()) == KrakenProductType::Spot {
2270                coverage.truncate(None);
2271            }
2272            return Ok((all_reports, coverage));
2273        }
2274
2275        let open_orders = self.inner.get_open_orders(Some(true), None).await?;
2276
2277        for (order_id, order) in &open_orders {
2278            // Kraken spells a pair two ways, so resolve the row and compare instrument ids rather
2279            // than the row's spelling against the cached `raw_symbol`.
2280            let resolved = self.get_instrument_by_raw_symbol(order.descr.pair.as_str());
2281            if let Some(ref target_id) = instrument_id {
2282                match &resolved {
2283                    Some(inst) if inst.id() != *target_id => continue,
2284                    // Unresolved, the row may be the scoped instrument's own
2285                    None => {
2286                        coverage.skip(order_id);
2287                        continue;
2288                    }
2289                    Some(_) => {}
2290                }
2291            }
2292
2293            let instrument = resolved.ok_or_else(|| {
2294                anyhow::anyhow!(
2295                    "OpenOrders: instrument not in cache for pair {}",
2296                    order.descr.pair
2297                )
2298            })?;
2299
2300            // An in-scope open order the client cannot parse fails the read: dropped, it reads to
2301            // reconciliation as an order the venue does not have.
2302            let report =
2303                parse_order_status_report(order_id, order, &instrument, account_id, ts_init)
2304                    .map_err(|e| {
2305                        anyhow::anyhow!("OpenOrders: failed to parse order {order_id}: {e}")
2306                    })?;
2307            all_reports.push(report);
2308        }
2309
2310        if open_only {
2311            return Ok((all_reports, coverage));
2312        }
2313
2314        // Kraken API expects Unix timestamps in seconds
2315        let start_ts = start.map(|dt| dt.as_second());
2316        let end_ts = end.map(|dt| dt.as_second());
2317
2318        let mut offset = 0;
2319        let mut pages = 0;
2320
2321        loop {
2322            if pages >= MAX_REPORT_PAGES {
2323                log::warn!(
2324                    "ClosedOrders pagination hit the cap of {MAX_REPORT_PAGES} pages; returning a truncated set and marking it incomplete"
2325                );
2326                coverage.truncate(None);
2327                break;
2328            }
2329
2330            let closed_orders = self
2331                .inner
2332                .get_closed_orders(Some(true), None, start_ts, end_ts, Some(offset), None)
2333                .await?;
2334
2335            if closed_orders.is_empty() {
2336                break;
2337            }
2338
2339            pages += 1;
2340
2341            for (order_id, order) in &closed_orders {
2342                let resolved = self.get_instrument_by_raw_symbol(order.descr.pair.as_str());
2343                if let Some(ref target_id) = instrument_id {
2344                    match &resolved {
2345                        Some(inst) if inst.id() != *target_id => continue,
2346                        // Unresolved, the row may be the scoped instrument's own
2347                        None => {
2348                            coverage.skip(order_id);
2349                            continue;
2350                        }
2351                        Some(_) => {}
2352                    }
2353                }
2354
2355                // A historical record can reference an instrument absent from the current
2356                // listing, so warn and keep the rest rather than withholding the whole read.
2357                let Some(instrument) = resolved else {
2358                    log::warn!(
2359                        "ClosedOrders: instrument not in cache for pair {}, skipping order {order_id}",
2360                        order.descr.pair
2361                    );
2362                    coverage.skip(order_id);
2363                    continue;
2364                };
2365
2366                match parse_order_status_report(order_id, order, &instrument, account_id, ts_init) {
2367                    Ok(report) => all_reports.push(report),
2368                    Err(e) => {
2369                        log::warn!("Failed to parse order {order_id}: {e}");
2370                        coverage.skip(order_id);
2371                    }
2372                }
2373            }
2374
2375            offset += PAGE_SIZE;
2376        }
2377
2378        Ok((all_reports, coverage))
2379    }
2380
2381    /// Requests fill/trade reports from Kraken.
2382    pub async fn request_fill_reports(
2383        &self,
2384        account_id: AccountId,
2385        instrument_id: Option<InstrumentId>,
2386        start: Option<Timestamp>,
2387        end: Option<Timestamp>,
2388    ) -> anyhow::Result<Vec<FillReport>> {
2389        self.request_fill_reports_checked(account_id, instrument_id, start, end)
2390            .await
2391            .map(|(reports, _)| reports)
2392    }
2393
2394    /// Requests fill reports, also reporting whether the set is complete.
2395    ///
2396    /// The flag is `false` when an in-scope trade cannot be resolved or parsed, or the read stops
2397    /// at its page cap, which `ExecutionMassStatus::set_report_window` records for bounded history.
2398    pub(crate) async fn request_fill_reports_checked(
2399        &self,
2400        account_id: AccountId,
2401        instrument_id: Option<InstrumentId>,
2402        start: Option<Timestamp>,
2403        end: Option<Timestamp>,
2404    ) -> anyhow::Result<(Vec<FillReport>, bool)> {
2405        const PAGE_SIZE: i32 = 50;
2406
2407        let ts_init = self.generate_ts_init();
2408        let mut all_reports = Vec::new();
2409        let mut complete = true;
2410
2411        // As above: a scoped read for an instrument this client does not hold matches nothing.
2412        if let Some(ref target_id) = instrument_id
2413            && self
2414                .get_cached_instrument(&target_id.symbol.inner())
2415                .is_none()
2416        {
2417            return Ok((all_reports, complete));
2418        }
2419
2420        // Kraken API expects Unix timestamps in seconds
2421        let start_ts = start.map(|dt| dt.as_second());
2422        let end_ts = end.map(|dt| dt.as_second());
2423
2424        let mut offset = 0;
2425        let mut pages = 0;
2426
2427        loop {
2428            if pages >= MAX_REPORT_PAGES {
2429                log::warn!(
2430                    "TradesHistory pagination hit the cap of {MAX_REPORT_PAGES} pages; returning a truncated set and marking it incomplete, which only mass status surfaces"
2431                );
2432                complete = false;
2433                break;
2434            }
2435
2436            let trades = self
2437                .inner
2438                .get_trades_history(None, Some(true), start_ts, end_ts, Some(offset))
2439                .await?;
2440
2441            if trades.is_empty() {
2442                break;
2443            }
2444
2445            pages += 1;
2446
2447            for (trade_id, trade) in &trades {
2448                let resolved = self.get_instrument_by_raw_symbol(trade.pair.as_str());
2449                if let Some(ref target_id) = instrument_id
2450                    && resolved.as_ref().is_none_or(|inst| inst.id() != *target_id)
2451                {
2452                    continue;
2453                }
2454
2455                // As above: historical fills outlive the listing, so preserve the usable rows.
2456                let Some(instrument) = resolved else {
2457                    log::warn!(
2458                        "TradesHistory: instrument not in cache for pair {}, skipping trade {trade_id}",
2459                        trade.pair
2460                    );
2461                    complete = false;
2462                    continue;
2463                };
2464
2465                match parse_fill_report(trade_id, trade, &instrument, account_id, ts_init) {
2466                    Ok(report) => all_reports.push(report),
2467                    Err(e) => {
2468                        log::warn!("Failed to parse trade {trade_id}: {e}");
2469                        complete = false;
2470                    }
2471                }
2472            }
2473
2474            offset += PAGE_SIZE;
2475        }
2476
2477        Ok((all_reports, complete))
2478    }
2479
2480    /// Requests position status reports for SPOT instruments.
2481    ///
2482    /// In margin mode: calls `OpenPositions` and returns reports for each open leveraged position.
2483    /// When `use_spot_position_reports` is enabled (cash mode): derives reports from wallet balances.
2484    /// Otherwise returns an empty vector.
2485    pub async fn request_position_status_reports(
2486        &self,
2487        account_id: AccountId,
2488        instrument_id: Option<InstrumentId>,
2489        account_type: AccountType,
2490        use_spot_position_reports: bool,
2491        quote_currency: Ustr,
2492    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2493        if account_type == AccountType::Margin {
2494            self.generate_margin_position_reports(account_id, instrument_id)
2495                .await
2496        } else if use_spot_position_reports {
2497            self.generate_spot_position_reports_from_wallet(
2498                account_id,
2499                instrument_id,
2500                quote_currency,
2501            )
2502            .await
2503        } else {
2504            Ok(Vec::new())
2505        }
2506    }
2507
2508    /// Requests wallet position reports for the startup mass status, adding a FLAT report for
2509    /// each of `flat_candidates` whose base asset the `Balance` read establishes as flat.
2510    ///
2511    /// Every row that counts toward a candidate's base, suffixed and staked rows included, must
2512    /// parse and be non-negative. A candidate is flat when the sum of its base's rows rounds to
2513    /// zero at the instrument's size precision, so an absent, zero or dust balance qualifies. A
2514    /// nonzero sum with no LONG report withholds the FLAT with a warning. Tokenized assets never
2515    /// get a FLAT, since their `Balance` key and units are undocumented.
2516    ///
2517    /// # Errors
2518    ///
2519    /// Returns an error if the request fails, or if a row that counts toward a candidate's base
2520    /// cannot be parsed or is negative.
2521    pub(crate) async fn request_wallet_position_reports_with_flats(
2522        &self,
2523        account_id: AccountId,
2524        quote_currency: Ustr,
2525        flat_candidates: &[InstrumentId],
2526    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2527        let balances_raw = self.inner.get_balance().await?;
2528        let ts_init = self.generate_ts_init();
2529
2530        let mut candidates: Vec<(InstrumentId, Ustr, u8)> = Vec::new();
2531
2532        for instrument_id in flat_candidates {
2533            let Some((instrument, base_currency)) = self
2534                .get_cached_instrument(&instrument_id.symbol.inner())
2535                .and_then(|instrument| {
2536                    wallet_report_base_currency(&instrument, quote_currency)
2537                        .map(|base_currency| (instrument, base_currency))
2538                })
2539            else {
2540                log::warn!(
2541                    "Withholding flat position report for {instrument_id}: not covered by the wallet read"
2542                );
2543                continue;
2544            };
2545
2546            if matches!(instrument, InstrumentAny::TokenizedAsset(_)) {
2547                log::warn!(
2548                    "Withholding flat position report for {instrument_id}: tokenized asset balances are not read"
2549                );
2550                continue;
2551            }
2552
2553            candidates.push((
2554                *instrument_id,
2555                base_currency.code,
2556                instrument.size_precision(),
2557            ));
2558        }
2559
2560        let candidate_bases: HashSet<Ustr> = candidates.iter().map(|(_, base, _)| *base).collect();
2561        let mut rows_by_base: HashMap<Ustr, Vec<(&str, Decimal)>> = HashMap::new();
2562
2563        for (key, amount) in &balances_raw {
2564            let Some(base) = covered_balance_base(key, &candidate_bases) else {
2565                continue;
2566            };
2567            let amount = Decimal::from_str_exact(amount)
2568                .with_context(|| format!("Balance: failed to parse '{amount}' for {key}"))?;
2569            anyhow::ensure!(
2570                amount >= Decimal::ZERO,
2571                "Balance: negative balance '{amount}' for {key}"
2572            );
2573            rows_by_base
2574                .entry(base)
2575                .or_default()
2576                .push((key.as_str(), amount));
2577        }
2578
2579        let mut reports = self.spot_position_reports_from_balances(
2580            &balances_raw,
2581            account_id,
2582            None,
2583            quote_currency,
2584            ts_init,
2585        )?;
2586
2587        for (instrument_id, base, size_precision) in candidates {
2588            let rows = rows_by_base
2589                .get(&base)
2590                .map(Vec::as_slice)
2591                .unwrap_or_default();
2592            let total: Decimal = rows.iter().map(|(_, amount)| *amount).sum();
2593            let held = Quantity::from_decimal_dp(total, size_precision)?;
2594
2595            if !held.is_zero() {
2596                if !reports
2597                    .iter()
2598                    .any(|report| report.instrument_id == instrument_id)
2599                {
2600                    let keys: Vec<&str> = rows
2601                        .iter()
2602                        .filter(|(_, amount)| !amount.is_zero())
2603                        .map(|(key, _)| *key)
2604                        .collect();
2605                    log::warn!(
2606                        "Withholding flat position report for {instrument_id}: {base} balance {held} held in {}",
2607                        keys.join(", "),
2608                    );
2609                }
2610                continue;
2611            }
2612
2613            reports.push(PositionStatusReport::new(
2614                account_id,
2615                instrument_id,
2616                PositionSide::Flat,
2617                Quantity::zero(size_precision),
2618                ts_init,
2619                ts_init,
2620                None,
2621                None,
2622                None,
2623            ));
2624        }
2625
2626        Ok(reports)
2627    }
2628
2629    /// Returns whether a bulk position read covers `instrument_id`, so that an absent report is
2630    /// evidence the position is flat.
2631    ///
2632    /// This mirrors [`Self::request_position_status_reports`] with `instrument_id` left unset.
2633    /// Margin mode reads `OpenPositions`, which reports leveraged positions only, and cash mode
2634    /// without `use_spot_position_reports` reads nothing, so neither covers a spot holding. The
2635    /// wallet read covers an instrument only when it would enumerate it, which one shared
2636    /// predicate decides for the read and for this answer alike.
2637    pub fn covers_bulk_position_reports(
2638        &self,
2639        instrument_id: InstrumentId,
2640        account_type: AccountType,
2641        use_spot_position_reports: bool,
2642        quote_currency: Ustr,
2643    ) -> bool {
2644        if account_type == AccountType::Margin || !use_spot_position_reports {
2645            return false;
2646        }
2647
2648        self.get_cached_instrument(&instrument_id.symbol.inner())
2649            .is_some_and(|instrument| {
2650                wallet_report_base_currency(&instrument, quote_currency).is_some()
2651            })
2652    }
2653
2654    /// Generates position reports from Kraken `OpenPositions` (margin mode).
2655    async fn generate_margin_position_reports(
2656        &self,
2657        account_id: AccountId,
2658        instrument_id: Option<InstrumentId>,
2659    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2660        let open_positions = self
2661            .inner
2662            .get_open_positions(&SpotOpenPositionsParams::default())
2663            .await?;
2664
2665        let ts_init = self.generate_ts_init();
2666
2667        // Aggregate individual lot entries by pair into a signed net quantity.
2668        // Kraken returns one entry per order lot (keyed by ordertxid); buy lots add to net
2669        // quantity and sell lots subtract. A single signed value per pair is correct for a
2670        // NETTING account and avoids emitting conflicting long+short reports for the same
2671        // instrument when opposing lots exist on the same pair. Aggregation uses `Decimal`
2672        // so opposing lots cancel exactly and partial-close noise does not leave residual
2673        // float dust in the reported quantity.
2674        let mut agg: IndexMap<String, OpenPositionAggregate> = IndexMap::new();
2675
2676        let target_pair: Option<Ustr> = match &instrument_id {
2677            Some(target_id) => match self.get_cached_instrument(&target_id.symbol.inner()) {
2678                Some(inst) => Some(Ustr::from(inst.raw_symbol().as_str())),
2679                None => return Ok(Vec::new()),
2680            },
2681            None => None,
2682        };
2683
2684        for (_pos_id, pos) in open_positions.iter() {
2685            if let Some(pair) = target_pair
2686                && pair.as_str() != pos.pair
2687            {
2688                continue;
2689            }
2690
2691            if let Some(status) = pos.posstatus.as_deref()
2692                && status != "open"
2693            {
2694                log::debug!(
2695                    "Skipping non-open OpenPositions entry for {}: posstatus={status}",
2696                    pos.pair,
2697                );
2698                continue;
2699            }
2700
2701            let instrument = self
2702                .get_instrument_by_raw_symbol(pos.pair.as_str())
2703                .ok_or_else(|| {
2704                    anyhow::anyhow!(
2705                        "OpenPositions: instrument not in cache for pair {}",
2706                        pos.pair
2707                    )
2708                })?;
2709
2710            let vol = Decimal::from_str_exact(&pos.vol)
2711                .with_context(|| format!("OpenPositions: failed to parse vol for {}", pos.pair))?;
2712            let vol_closed = Decimal::from_str_exact(&pos.vol_closed).with_context(|| {
2713                format!("OpenPositions: failed to parse vol_closed for {}", pos.pair)
2714            })?;
2715
2716            let lot_net = (vol - vol_closed).max(Decimal::ZERO);
2717            let signed_lot = match pos.side {
2718                KrakenOrderSide::Buy => lot_net,
2719                KrakenOrderSide::Sell => -lot_net,
2720            };
2721
2722            // `cost` is the quote volume for the whole `vol`, so the lot's entry price is their
2723            // ratio. Accumulate each side separately: a blended average across opposing lots
2724            // would not describe the surviving exposure.
2725            let cost = Decimal::from_str_exact(&pos.cost)
2726                .with_context(|| format!("OpenPositions: failed to parse cost for {}", pos.pair))?;
2727
2728            let entry = agg
2729                .entry(pos.pair.clone())
2730                .or_insert_with(|| OpenPositionAggregate::new(instrument.id()));
2731            entry.signed_qty += signed_lot;
2732
2733            if !vol.is_zero() {
2734                let entry_px = cost / vol;
2735
2736                match pos.side {
2737                    KrakenOrderSide::Buy => {
2738                        entry.long_qty += lot_net;
2739                        entry.long_notional += lot_net * entry_px;
2740                    }
2741                    KrakenOrderSide::Sell => {
2742                        entry.short_qty += lot_net;
2743                        entry.short_notional += lot_net * entry_px;
2744                    }
2745                }
2746            }
2747        }
2748
2749        let mut reports = Vec::new();
2750
2751        for (_, aggregate) in agg {
2752            let signed_qty = aggregate.signed_qty;
2753            let inst_id = aggregate.instrument_id;
2754            let instrument = self
2755                .get_cached_instrument(&inst_id.symbol.inner())
2756                .ok_or_else(|| InstrumentLookupError::not_found(inst_id))?;
2757
2758            let side = if signed_qty.is_sign_positive() && !signed_qty.is_zero() {
2759                PositionSide::Long
2760            } else if signed_qty.is_sign_negative() && !signed_qty.is_zero() {
2761                PositionSide::Short
2762            } else {
2763                PositionSide::Flat
2764            };
2765            let quantity = Quantity::from_decimal_dp(signed_qty.abs(), instrument.size_precision())
2766                .map_err(|e| {
2767                    anyhow::anyhow!("OpenPositions: failed to build Quantity for {inst_id}: {e:?}")
2768                })?;
2769            let avg_px_open = aggregate.avg_px_open(side);
2770            let report = PositionStatusReport::new(
2771                account_id,
2772                inst_id,
2773                side,
2774                quantity,
2775                ts_init,
2776                ts_init,
2777                None,
2778                None,
2779                avg_px_open,
2780            )
2781            // Kraken averages the lots that remain open under FIFO, so after a partial close it
2782            // describes the surviving lots rather than the opening fills. It can open a position
2783            // from flat, but must not be compared with a netting average.
2784            .with_avg_px_open_reconciliation(AvgPxReconciliation::OpeningOnly);
2785            reports.push(report);
2786        }
2787
2788        // If a specific instrument was requested but no open position exists for it, emit
2789        // a FLAT report so the engine can reconcile a previously-open position to closed.
2790        // (Kraken omits fully-closed positions from OpenPositions entirely.)
2791        // Only emit for instruments known to this spot client; a missing cache entry means
2792        // the target belongs to a different product type (e.g. futures) and must not receive
2793        // a spurious FLAT from the spot reconciliation path.
2794        if let Some(target_id) = instrument_id {
2795            let already_reported = reports.iter().any(|r| r.instrument_id == target_id);
2796
2797            if !already_reported
2798                && let Some(instrument) = self.get_cached_instrument(&target_id.symbol.inner())
2799            {
2800                let precision = instrument.size_precision();
2801                reports.push(PositionStatusReport::new(
2802                    account_id,
2803                    target_id,
2804                    PositionSide::Flat,
2805                    Quantity::zero(precision),
2806                    ts_init,
2807                    ts_init,
2808                    None,
2809                    None,
2810                    None,
2811                ));
2812            }
2813        }
2814
2815        Ok(reports)
2816    }
2817
2818    /// Generates SPOT position reports from wallet balances.
2819    ///
2820    /// Kraken spot balances are simple totals (no borrowing concept). A requested instrument is
2821    /// reported LONG for a positive balance and FLAT otherwise. The bulk read reports LONG for each
2822    /// covered instrument whose balance is nonzero at its size precision and omits every other
2823    /// instrument.
2824    async fn generate_spot_position_reports_from_wallet(
2825        &self,
2826        account_id: AccountId,
2827        instrument_id: Option<InstrumentId>,
2828        quote_currency: Ustr,
2829    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2830        let balances_raw = self.inner.get_balance().await?;
2831        let ts_init = self.generate_ts_init();
2832        self.spot_position_reports_from_balances(
2833            &balances_raw,
2834            account_id,
2835            instrument_id,
2836            quote_currency,
2837            ts_init,
2838        )
2839    }
2840
2841    fn spot_position_reports_from_balances(
2842        &self,
2843        balances_raw: &BalanceResponse,
2844        account_id: AccountId,
2845        instrument_id: Option<InstrumentId>,
2846        quote_currency: Ustr,
2847        ts_init: UnixNanos,
2848    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2849        let mut wallet_by_coin: HashMap<Ustr, Decimal> = HashMap::new();
2850
2851        for (currency_code, amount_str) in balances_raw {
2852            let balance = match Decimal::from_str_exact(amount_str) {
2853                Ok(b) => b,
2854                Err(_) => continue,
2855            };
2856
2857            if balance.is_zero() {
2858                continue;
2859            }
2860
2861            wallet_by_coin.insert(Ustr::from(normalize_currency_code(currency_code)), balance);
2862        }
2863
2864        let mut reports = Vec::new();
2865
2866        if let Some(instrument_id) = instrument_id {
2867            if let Some(instrument) = self.get_cached_instrument(&instrument_id.symbol.inner()) {
2868                let base_currency = match instrument.base_currency() {
2869                    Some(currency) => currency,
2870                    None => return Ok(reports),
2871                };
2872
2873                let coin = Ustr::from(base_currency.code.as_str());
2874                let wallet_balance = wallet_by_coin.get(&coin).copied().unwrap_or(Decimal::ZERO);
2875
2876                let side = if wallet_balance > Decimal::ZERO {
2877                    PositionSide::Long
2878                } else {
2879                    PositionSide::Flat
2880                };
2881
2882                let abs_balance = wallet_balance.abs();
2883                let quantity = Quantity::from_decimal_dp(abs_balance, instrument.size_precision())?;
2884
2885                let report = PositionStatusReport::new(
2886                    account_id,
2887                    instrument_id,
2888                    side,
2889                    quantity,
2890                    ts_init,
2891                    ts_init,
2892                    None,
2893                    None,
2894                    None,
2895                );
2896
2897                reports.push(report);
2898            }
2899        } else {
2900            let instruments_guard = self.instruments_cache.load();
2901            for instrument in instruments_guard.values() {
2902                let Some(base_currency) = wallet_report_base_currency(instrument, quote_currency)
2903                else {
2904                    continue;
2905                };
2906
2907                let coin = Ustr::from(base_currency.code.as_str());
2908                let wallet_balance = wallet_by_coin.get(&coin).copied().unwrap_or(Decimal::ZERO);
2909
2910                if wallet_balance.is_zero() {
2911                    continue;
2912                }
2913
2914                let side = PositionSide::Long;
2915                let quantity =
2916                    Quantity::from_decimal_dp(wallet_balance, instrument.size_precision())?;
2917
2918                if quantity.is_zero() {
2919                    continue;
2920                }
2921
2922                log::debug!(
2923                    "Spot position: {} {} (quote: {})",
2924                    quantity,
2925                    base_currency.code,
2926                    instrument.quote_currency().code
2927                );
2928
2929                let report = PositionStatusReport::new(
2930                    account_id,
2931                    instrument.id(),
2932                    side,
2933                    quantity,
2934                    ts_init,
2935                    ts_init,
2936                    None,
2937                    None,
2938                    None,
2939                );
2940
2941                reports.push(report);
2942            }
2943        }
2944
2945        Ok(reports)
2946    }
2947
2948    /// Submits a new order to the Kraken Spot exchange.
2949    ///
2950    /// Returns the venue order ID on success. WebSocket handles all execution events.
2951    ///
2952    /// # Errors
2953    ///
2954    /// Returns an error if:
2955    /// - Credentials are missing.
2956    /// - The instrument is not found in cache.
2957    /// - The order type or time in force is not supported.
2958    /// - The request fails.
2959    /// - The order is rejected.
2960    /// - The response carries an invalid order ID.
2961    #[expect(clippy::too_many_arguments)]
2962    pub async fn submit_order(
2963        &self,
2964        _account_id: AccountId,
2965        instrument_id: InstrumentId,
2966        client_order_id: ClientOrderId,
2967        order_side: OrderSide,
2968        order_type: OrderType,
2969        quantity: Quantity,
2970        time_in_force: TimeInForce,
2971        expire_time: Option<UnixNanos>,
2972        price: Option<Price>,
2973        trigger_price: Option<Price>,
2974        trigger_type: Option<TriggerType>,
2975        trailing_offset: Option<Decimal>,
2976        limit_offset: Option<Decimal>,
2977        reduce_only: bool,
2978        post_only: bool,
2979        quote_quantity: bool,
2980        display_qty: Option<Quantity>,
2981        leverage: Option<u16>,
2982        account_type: AccountType,
2983    ) -> anyhow::Result<VenueOrderId> {
2984        let params = self.build_add_order_params(
2985            instrument_id,
2986            client_order_id,
2987            order_side,
2988            order_type,
2989            quantity,
2990            time_in_force,
2991            expire_time,
2992            price,
2993            trigger_price,
2994            trigger_type,
2995            trailing_offset,
2996            limit_offset,
2997            reduce_only,
2998            post_only,
2999            quote_quantity,
3000            display_qty,
3001            leverage,
3002            account_type,
3003        )?;
3004        let response = self.inner.add_order(&params).await?;
3005
3006        let venue_order_id =
3007            response
3008                .txid
3009                .first()
3010                .ok_or_else(|| KrakenSubmitOrderError::MissingOrderId {
3011                    detail: "transaction ID was absent".to_string(),
3012                })?;
3013
3014        parse_venue_order_id(venue_order_id, "spot submit response").map_err(|e| {
3015            KrakenSubmitOrderError::InvalidOrderId {
3016                detail: format!("{e:#}"),
3017            }
3018            .into()
3019        })
3020    }
3021
3022    /// Submits multiple orders to the Kraken Spot exchange.
3023    ///
3024    /// Automatically groups orders by pair and chunks batch requests at the venue
3025    /// limit. Single-order groups fall back to `AddOrder`.
3026    #[expect(clippy::type_complexity)]
3027    pub async fn submit_orders_batch(
3028        &self,
3029        orders: Vec<(
3030            InstrumentId,
3031            ClientOrderId,
3032            OrderSide,
3033            OrderType,
3034            Quantity,
3035            TimeInForce,
3036            Option<UnixNanos>,
3037            Option<Price>,
3038            Option<Price>,
3039            Option<TriggerType>,
3040            Option<Decimal>,
3041            Option<Decimal>,
3042            bool,
3043            bool,
3044            bool,
3045            Option<Quantity>,
3046            Option<u16>,
3047        )>,
3048        account_type: AccountType,
3049    ) -> anyhow::Result<Vec<String>> {
3050        Ok(self
3051            .send_order_batches(orders, account_type)
3052            .await
3053            .into_iter()
3054            .map(|result| match result {
3055                Ok(order) if order.txid.is_some() => "placed".to_string(),
3056                Ok(order) => order.error.unwrap_or_else(|| "Unknown error".to_string()),
3057                Err(e)
3058                    if matches!(
3059                        e.downcast_ref::<KrakenBatchOrderError>(),
3060                        Some(KrakenBatchOrderError::Validation { .. })
3061                    ) =>
3062                {
3063                    format!("validation_error: {e}")
3064                }
3065                Err(e) => format!("batch_error: {e}"),
3066            })
3067            .collect())
3068    }
3069
3070    pub(crate) async fn send_order_batches(
3071        &self,
3072        orders: Vec<SpotBatchOrder>,
3073        account_type: AccountType,
3074    ) -> Vec<anyhow::Result<SpotBatchOrderResponse>> {
3075        let count = orders.len();
3076        if count == 0 {
3077            return Vec::new();
3078        }
3079
3080        let mut results: Vec<Option<anyhow::Result<SpotBatchOrderResponse>>> =
3081            (0..count).map(|_| None).collect();
3082        let mut grouped: AHashMap<Ustr, Vec<(usize, KrakenSpotAddOrderParams)>> = AHashMap::new();
3083
3084        for (
3085            idx,
3086            (
3087                instrument_id,
3088                client_order_id,
3089                order_side,
3090                order_type,
3091                quantity,
3092                time_in_force,
3093                expire_time,
3094                price,
3095                trigger_price,
3096                trigger_type,
3097                trailing_offset,
3098                limit_offset,
3099                reduce_only,
3100                post_only,
3101                quote_quantity,
3102                display_qty,
3103                leverage,
3104            ),
3105        ) in orders.into_iter().enumerate()
3106        {
3107            match self.build_add_order_params(
3108                instrument_id,
3109                client_order_id,
3110                order_side,
3111                order_type,
3112                quantity,
3113                time_in_force,
3114                expire_time,
3115                price,
3116                trigger_price,
3117                trigger_type,
3118                trailing_offset,
3119                limit_offset,
3120                reduce_only,
3121                post_only,
3122                quote_quantity,
3123                display_qty,
3124                leverage,
3125                account_type,
3126            ) {
3127                Ok(params) => {
3128                    grouped.entry(params.pair).or_default().push((idx, params));
3129                }
3130                Err(e) => {
3131                    results[idx] = Some(Err(KrakenBatchOrderError::Validation {
3132                        reason: e.to_string(),
3133                    }
3134                    .into()));
3135                }
3136            }
3137        }
3138
3139        let mut batches = Vec::new();
3140        let mut grouped_orders: Vec<_> = grouped.into_values().collect();
3141        grouped_orders.sort_by_key(|group| group.first().map_or(usize::MAX, |(idx, _)| *idx));
3142        for group in grouped_orders {
3143            batches.extend(group.chunks(BATCH_SUBMIT_LIMIT).map(|chunk| chunk.to_vec()));
3144        }
3145
3146        for (batch_index, batch) in batches.iter().enumerate() {
3147            let response = if batch.len() == 1 {
3148                self.inner
3149                    .add_order(&batch[0].1)
3150                    .await
3151                    .map(|response| SpotAddOrderBatchResponse {
3152                        orders: vec![SpotBatchOrderResponse {
3153                            descr: response.descr,
3154                            error: None,
3155                            txid: response.txid.into_iter().next(),
3156                        }],
3157                    })
3158            } else {
3159                let params = KrakenSpotAddOrderBatchParams {
3160                    pair: batch[0].1.pair,
3161                    orders: batch
3162                        .iter()
3163                        .map(|(_, params)| params.clone().into())
3164                        .collect(),
3165                    asset_class: batch[0].1.asset_class,
3166                };
3167                self.inner.add_order_batch(&params).await
3168            };
3169
3170            match response {
3171                // AddOrderBatch returns result items in request order, so exact cardinality makes
3172                // positional correlation unambiguous.
3173                Ok(response) if response.orders.len() == batch.len() => {
3174                    for ((idx, _), order) in batch.iter().zip(response.orders) {
3175                        results[*idx] = Some(Ok(order));
3176                    }
3177                }
3178                Ok(response) => {
3179                    for (idx, _) in batch {
3180                        results[*idx] = Some(Err(KrakenBatchOrderError::ResponseCount {
3181                            expected: batch.len(),
3182                            actual: response.orders.len(),
3183                        }
3184                        .into()));
3185                    }
3186                }
3187                Err(e) => {
3188                    for (idx, _) in batch {
3189                        results[*idx] = Some(Err(anyhow::Error::new(e.clone())));
3190                    }
3191
3192                    for later_batch in &batches[batch_index + 1..] {
3193                        for (idx, _) in later_batch {
3194                            results[*idx] = Some(Err(KrakenBatchOrderError::NotAttempted.into()));
3195                        }
3196                    }
3197                    break;
3198                }
3199            }
3200        }
3201
3202        results
3203            .into_iter()
3204            .map(|result| result.unwrap_or_else(|| Err(KrakenBatchOrderError::NotAttempted.into())))
3205            .collect()
3206    }
3207
3208    /// Modifies an existing order on the Kraken Spot exchange using atomic amend.
3209    ///
3210    /// Uses the AmendOrder endpoint which modifies the order in-place,
3211    /// keeping the same order ID and queue position.
3212    ///
3213    /// # Errors
3214    ///
3215    /// Returns an error if:
3216    /// - Neither `client_order_id` nor `venue_order_id` is provided.
3217    /// - The instrument is not found in cache.
3218    /// - The request fails.
3219    pub async fn modify_order(
3220        &self,
3221        instrument_id: InstrumentId,
3222        client_order_id: Option<ClientOrderId>,
3223        venue_order_id: Option<VenueOrderId>,
3224        quantity: Option<Quantity>,
3225        price: Option<Price>,
3226        trigger_price: Option<Price>,
3227    ) -> anyhow::Result<VenueOrderId> {
3228        let _ = self
3229            .get_cached_instrument(&instrument_id.symbol.inner())
3230            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
3231
3232        let txid = venue_order_id.as_ref().map(|id| id.to_string());
3233        let cl_ord_id = client_order_id.as_ref().map(truncate_cl_ord_id);
3234
3235        if txid.is_none() && cl_ord_id.is_none() {
3236            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
3237        }
3238
3239        let mut builder = KrakenSpotAmendOrderParamsBuilder::default();
3240        if let Some(ref id) = txid {
3241            builder.txid(id.clone());
3242        } else if let Some(ref id) = cl_ord_id {
3243            builder.cl_ord_id(id.clone());
3244        }
3245
3246        if let Some(qty) = quantity {
3247            builder.order_qty(qty.to_string());
3248        }
3249
3250        if let Some(p) = price {
3251            builder.limit_price(p.to_string());
3252        }
3253
3254        if let Some(tp) = trigger_price {
3255            builder.trigger_price(tp.to_string());
3256        }
3257
3258        let params = builder
3259            .build()
3260            .map_err(|e| anyhow::anyhow!("Failed to build amend order params: {e}"))?;
3261
3262        let _response = self.inner.amend_order(&params).await?;
3263
3264        // AmendOrder modifies in-place, so the order keeps its original ID
3265        let order_id = venue_order_id.ok_or(KrakenModifyOrderError::MissingOrderId)?;
3266
3267        Ok(order_id)
3268    }
3269
3270    /// Cancels an order on the Kraken Spot exchange.
3271    ///
3272    /// # Errors
3273    ///
3274    /// Returns an error if:
3275    /// - Credentials are missing.
3276    /// - Neither client_order_id nor venue_order_id is provided.
3277    /// - The request fails.
3278    /// - The order cancellation is rejected.
3279    pub async fn cancel_order(
3280        &self,
3281        _account_id: AccountId,
3282        instrument_id: InstrumentId,
3283        client_order_id: Option<ClientOrderId>,
3284        venue_order_id: Option<VenueOrderId>,
3285    ) -> anyhow::Result<()> {
3286        let _ = self
3287            .get_cached_instrument(&instrument_id.symbol.inner())
3288            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
3289
3290        let txid = venue_order_id.as_ref().map(|id| id.to_string());
3291        let cl_ord_id = client_order_id.as_ref().map(truncate_cl_ord_id);
3292
3293        if txid.is_none() && cl_ord_id.is_none() {
3294            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
3295        }
3296
3297        // Prefer txid (venue identifier) since Kraken always knows it.
3298        // cl_ord_id may not be known to Kraken for reconciled orders.
3299        let mut builder = KrakenSpotCancelOrderParamsBuilder::default();
3300
3301        if let Some(ref id) = txid {
3302            builder.txid(id.clone());
3303        } else if let Some(ref id) = cl_ord_id {
3304            builder.cl_ord_id(id.clone());
3305        }
3306        let params = builder
3307            .build()
3308            .map_err(|e| anyhow::anyhow!("Failed to build cancel params: {e}"))?;
3309
3310        self.inner.cancel_order(&params).await?;
3311
3312        Ok(())
3313    }
3314
3315    /// Cancels multiple orders on the Kraken Spot exchange (batched, max 50 per request).
3316    pub async fn cancel_orders_batch(
3317        &self,
3318        venue_order_ids: Vec<VenueOrderId>,
3319    ) -> anyhow::Result<i32> {
3320        if venue_order_ids.is_empty() {
3321            return Ok(0);
3322        }
3323
3324        let mut total_cancelled = 0;
3325
3326        for chunk in venue_order_ids.chunks(BATCH_CANCEL_LIMIT) {
3327            let orders: Vec<String> = chunk.iter().map(|id| id.to_string()).collect();
3328            let params = KrakenSpotCancelOrderBatchParams {
3329                orders,
3330                cl_ord_ids: Vec::new(),
3331            };
3332
3333            let response = self.inner.cancel_order_batch(&params).await?;
3334            total_cancelled += response.count;
3335        }
3336
3337        Ok(total_cancelled)
3338    }
3339
3340    #[expect(clippy::too_many_arguments)]
3341    fn build_add_order_params(
3342        &self,
3343        instrument_id: InstrumentId,
3344        client_order_id: ClientOrderId,
3345        order_side: OrderSide,
3346        order_type: OrderType,
3347        quantity: Quantity,
3348        time_in_force: TimeInForce,
3349        expire_time: Option<UnixNanos>,
3350        price: Option<Price>,
3351        trigger_price: Option<Price>,
3352        trigger_type: Option<TriggerType>,
3353        trailing_offset: Option<Decimal>,
3354        limit_offset: Option<Decimal>,
3355        reduce_only: bool,
3356        post_only: bool,
3357        quote_quantity: bool,
3358        display_qty: Option<Quantity>,
3359        leverage: Option<u16>,
3360        account_type: AccountType,
3361    ) -> anyhow::Result<KrakenSpotAddOrderParams> {
3362        let instrument = self
3363            .get_cached_instrument(&instrument_id.symbol.inner())
3364            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
3365
3366        let raw_symbol = instrument.raw_symbol().inner();
3367        let asset_class = Self::asset_class_for(&instrument);
3368
3369        let kraken_side = match order_side {
3370            OrderSide::Buy => KrakenOrderSide::Buy,
3371            OrderSide::Sell => KrakenOrderSide::Sell,
3372        };
3373
3374        let kraken_order_type = match order_type {
3375            OrderType::Market => KrakenOrderType::Market,
3376            OrderType::Limit => KrakenOrderType::Limit,
3377            OrderType::StopMarket => KrakenOrderType::StopLoss,
3378            OrderType::StopLimit => KrakenOrderType::StopLossLimit,
3379            OrderType::MarketIfTouched => KrakenOrderType::TakeProfit,
3380            OrderType::LimitIfTouched => KrakenOrderType::TakeProfitLimit,
3381            OrderType::TrailingStopMarket => KrakenOrderType::TrailingStop,
3382            OrderType::TrailingStopLimit => KrakenOrderType::TrailingStopLimit,
3383            _ => anyhow::bail!("Unsupported order type: {order_type:?}"),
3384        };
3385
3386        let mut oflags = Vec::new();
3387        let is_limit_order = matches!(
3388            order_type,
3389            OrderType::Limit
3390                | OrderType::StopLimit
3391                | OrderType::LimitIfTouched
3392                | OrderType::TrailingStopLimit
3393        );
3394
3395        if time_in_force == TimeInForce::Fok && order_type != OrderType::Limit {
3396            anyhow::bail!("FOK time in force only supported for LIMIT orders on Kraken Spot");
3397        }
3398
3399        let (timeinforce, expiretm) =
3400            compute_time_in_force(is_limit_order, time_in_force, expire_time)?;
3401
3402        if post_only {
3403            oflags.push(KRAKEN_OFLAG_POST_ONLY);
3404        }
3405
3406        if quote_quantity {
3407            oflags.push(KRAKEN_OFLAG_QUOTE_QUANTITY);
3408        }
3409
3410        let mut builder = KrakenSpotAddOrderParamsBuilder::default();
3411        builder
3412            .cl_ord_id(truncate_cl_ord_id(&client_order_id))
3413            .broker(NAUTILUS_KRAKEN_BROKER_ID)
3414            .pair(raw_symbol)
3415            .side(kraken_side)
3416            .volume(quantity.to_string())
3417            .order_type(kraken_order_type);
3418
3419        let is_conditional = matches!(
3420            order_type,
3421            OrderType::StopMarket
3422                | OrderType::StopLimit
3423                | OrderType::MarketIfTouched
3424                | OrderType::LimitIfTouched
3425                | OrderType::TrailingStopMarket
3426                | OrderType::TrailingStopLimit
3427        );
3428
3429        let is_trailing = matches!(
3430            order_type,
3431            OrderType::TrailingStopMarket | OrderType::TrailingStopLimit
3432        );
3433
3434        if is_trailing {
3435            if trigger_price.is_some() {
3436                anyhow::bail!(
3437                    "Kraken Spot trailing stops do not support activation trigger prices"
3438                );
3439            }
3440
3441            if let Some(offset) = trailing_offset {
3442                builder.price(offset.to_string());
3443            }
3444
3445            if let Some(offset) = limit_offset {
3446                builder.price2(offset.to_string());
3447            }
3448        } else if is_conditional {
3449            if let Some(trigger) = trigger_price {
3450                builder.price(trigger.to_string());
3451            }
3452
3453            if let Some(limit) = price {
3454                builder.price2(limit.to_string());
3455            }
3456        } else if let Some(limit) = price {
3457            builder.price(limit.to_string());
3458        }
3459
3460        if is_conditional {
3461            match trigger_type {
3462                Some(TriggerType::IndexPrice) => {
3463                    builder.trigger("index".to_string());
3464                }
3465                Some(TriggerType::LastPrice | TriggerType::Default) | None => {}
3466                Some(other) => {
3467                    anyhow::bail!(
3468                        "Unsupported trigger type for Kraken Spot: {other:?} (only LastPrice and IndexPrice supported)"
3469                    );
3470                }
3471            }
3472        }
3473
3474        if !oflags.is_empty() {
3475            builder.oflags(oflags.join(","));
3476        }
3477
3478        if let Some(tif) = timeinforce {
3479            builder.timeinforce(tif);
3480        }
3481
3482        if let Some(expire) = expiretm {
3483            builder.expiretm(expire);
3484        }
3485
3486        if let Some(dq) = display_qty {
3487            builder.displayvol(dq.to_string());
3488        }
3489
3490        if let Some(ac) = asset_class {
3491            builder.asset_class(ac);
3492        }
3493
3494        if leverage.is_some() && account_type != AccountType::Margin {
3495            anyhow::bail!("leverage requires spot_account_type=Margin (current: Cash)");
3496        }
3497
3498        if let Some(n) = leverage {
3499            let tiers = self.leverage_tiers_cache.get_cloned(&raw_symbol);
3500            let (buy_tiers, sell_tiers) = tiers.ok_or_else(|| {
3501                anyhow::anyhow!(
3502                    "Leverage tiers not loaded for {raw_symbol}; cannot validate leverage {n}:1 (instruments must be initialized before submitting margin orders)"
3503                )
3504            })?;
3505            let valid_tiers = match order_side {
3506                OrderSide::Buy => buy_tiers,
3507                _ => sell_tiers,
3508            };
3509            let side_label = match order_side {
3510                OrderSide::Buy => "buy",
3511                _ => "sell",
3512            };
3513
3514            if valid_tiers.is_empty() {
3515                anyhow::bail!("Leverage not supported for {raw_symbol} on {side_label} side");
3516            }
3517
3518            if !valid_tiers.contains(&(n as i32)) {
3519                anyhow::bail!(
3520                    "Leverage {n}:1 not supported for {raw_symbol} on {side_label} side (valid: {valid_tiers:?})"
3521                );
3522            }
3523            builder.leverage(format!("{n}:1"));
3524        }
3525
3526        if reduce_only {
3527            if account_type != AccountType::Margin {
3528                anyhow::bail!("reduce_only requires spot_account_type=Margin (current: Cash)");
3529            }
3530            builder.reduce_only(true);
3531        }
3532
3533        builder
3534            .build()
3535            .map_err(|e| anyhow::anyhow!("Failed to build order params: {e}"))
3536    }
3537}
3538
3539fn collect_spot_statuses(
3540    asset_pairs: &AssetPairsResponse,
3541) -> AHashMap<InstrumentId, MarketStatusAction> {
3542    asset_pairs
3543        .iter()
3544        .map(|(_, definition)| {
3545            let symbol_str = definition.wsname.as_ref().unwrap_or(&definition.altname);
3546            let normalized_symbol = normalize_spot_symbol(symbol_str.as_str());
3547            let instrument_id = InstrumentId::new(Symbol::new(&normalized_symbol), *KRAKEN_VENUE);
3548            let action = definition
3549                .status
3550                .map_or(MarketStatusAction::Trading, MarketStatusAction::from);
3551
3552            (instrument_id, action)
3553        })
3554        .collect()
3555}
3556
3557/// Maps raw symbol (altname, e.g. "XBTUSD") to leverage tiers.
3558type LeverageTiersCache = Arc<AtomicMap<Ustr, (Vec<i32>, Vec<i32>)>>;
3559
3560/// Accumulates `OpenPositions` lots for one pair.
3561///
3562/// Each side is tracked separately, so the entry average describes the side that survives netting
3563/// rather than blending opposing lots.
3564struct OpenPositionAggregate {
3565    instrument_id: InstrumentId,
3566    signed_qty: Decimal,
3567    long_qty: Decimal,
3568    long_notional: Decimal,
3569    short_qty: Decimal,
3570    short_notional: Decimal,
3571}
3572
3573impl OpenPositionAggregate {
3574    fn new(instrument_id: InstrumentId) -> Self {
3575        Self {
3576            instrument_id,
3577            signed_qty: Decimal::ZERO,
3578            long_qty: Decimal::ZERO,
3579            long_notional: Decimal::ZERO,
3580            short_qty: Decimal::ZERO,
3581            short_notional: Decimal::ZERO,
3582        }
3583    }
3584
3585    /// Returns the entry average for the netted side, or `None` when it cannot be derived.
3586    fn avg_px_open(&self, side: PositionSide) -> Option<Decimal> {
3587        match side {
3588            PositionSide::Long if !self.long_qty.is_zero() => {
3589                Some(self.long_notional / self.long_qty)
3590            }
3591            PositionSide::Short if !self.short_qty.is_zero() => {
3592                Some(self.short_notional / self.short_qty)
3593            }
3594            _ => None,
3595        }
3596    }
3597}
3598
3599struct TradeBalanceSnapshot {
3600    margins: Vec<MarginBalance>,
3601    metrics: IndexMap<String, String>,
3602    free_margin: Decimal,
3603    equity: Decimal,
3604}
3605
3606/// Returns the base currency whose wallet balance the bulk position read reports for `instrument`,
3607/// or `None` when the read skips it.
3608///
3609/// The read only covers pairs quoted in the configured `spot_positions_quote_currency`, and it
3610/// needs a base currency to name the holding. A configured code matches in either spelling, so an
3611/// existing `ZEUR` setting still selects euro-quoted instruments now that they carry `EUR`. Both
3612/// decisions live here so that the coverage declared through
3613/// [`KrakenSpotHttpClient::covers_bulk_position_reports`] cannot drift from what the read actually
3614/// enumerates.
3615fn wallet_report_base_currency(
3616    instrument: &InstrumentAny,
3617    quote_currency: Ustr,
3618) -> Option<Currency> {
3619    let quote_filter = Ustr::from(normalize_currency_code(quote_currency.as_str()));
3620    if instrument.quote_currency().code != quote_filter {
3621        return None;
3622    }
3623
3624    instrument.base_currency()
3625}
3626
3627/// Returns the covered base currency that a `Balance` row counts toward, or `None`.
3628///
3629/// The whole key matches first, so a dotted code such as `BRK.Bx` stays whole. Otherwise a dotted
3630/// key counts toward the code before its last dot, as is or with trailing digits stripped, so
3631/// `XBT.F`, `L3.F`, `DOT28.S` and `EUR.HOLD` count toward `BTC`, `L3`, `DOT` and `EUR`.
3632fn covered_balance_base(key: &str, covered_bases: &HashSet<Ustr>) -> Option<Ustr> {
3633    let whole = Ustr::from(normalize_currency_code(key));
3634    if covered_bases.contains(&whole) {
3635        return Some(whole);
3636    }
3637
3638    let (code, _) = key.rsplit_once('.')?;
3639    let base = Ustr::from(normalize_currency_code(code));
3640    if covered_bases.contains(&base) {
3641        return Some(base);
3642    }
3643
3644    let stripped = code.trim_end_matches(|c: char| c.is_ascii_digit());
3645    let base = Ustr::from(normalize_currency_code(stripped));
3646    covered_bases.contains(&base).then_some(base)
3647}
3648
3649/// Parses an optional `BalanceEx` credit amount, treating an absent field as zero.
3650///
3651/// Kraken only includes `credit` and `credit_used` for accounts holding a credit line, so their
3652/// absence means no credit rather than an unknown amount. Returns `None` when the field is present
3653/// but unparsable, so the caller can skip the balance rather than understate it.
3654fn optional_credit_amount(value: Option<&str>) -> Option<Decimal> {
3655    match value {
3656        Some(amount) => Decimal::from_str_exact(amount).ok(),
3657        None => Some(Decimal::ZERO),
3658    }
3659}
3660
3661/// Resolves the Nautilus [`Currency`] used to denominate `TradeBalance` margin metrics.
3662///
3663/// Kraken's `TradeBalance` defaults to `ZUSD` when no asset is supplied. This maps Kraken's
3664/// legacy asset codes to their standard equivalents and falls back to a 2dp fiat currency for
3665/// unknown codes so unusual collateral assets still produce a tagged `MarginBalance`.
3666fn trade_balance_currency(asset: Option<&str>) -> Currency {
3667    let raw = asset.unwrap_or("ZUSD");
3668    let normalized = normalize_currency_code(raw);
3669    Currency::try_from_str(normalized)
3670        .unwrap_or_else(|| Currency::new(normalized, 2, 0, normalized, CurrencyType::Fiat))
3671}
3672
3673fn compute_time_in_force(
3674    is_limit_order: bool,
3675    time_in_force: TimeInForce,
3676    expire_time: Option<UnixNanos>,
3677) -> anyhow::Result<(Option<String>, Option<String>)> {
3678    if !is_limit_order {
3679        return Ok((None, None));
3680    }
3681
3682    match time_in_force {
3683        TimeInForce::Gtc => Ok((None, None)),
3684        TimeInForce::Ioc => Ok((Some("IOC".to_string()), None)),
3685        TimeInForce::Fok => Ok((Some("FOK".to_string()), None)),
3686        TimeInForce::Gtd => {
3687            let expire = expire_time.ok_or_else(|| {
3688                anyhow::anyhow!("GTD time in force requires expire_time parameter")
3689            })?;
3690            let expire_secs = expire.as_u64() / NANOSECONDS_IN_SECOND;
3691            Ok((Some("GTD".to_string()), Some(expire_secs.to_string())))
3692        }
3693        _ => anyhow::bail!("Unsupported time in force: {time_in_force:?}"),
3694    }
3695}
3696
3697#[cfg(test)]
3698mod tests {
3699    use std::{
3700        sync::{
3701            Arc,
3702            atomic::{AtomicUsize, Ordering},
3703        },
3704        time::Duration,
3705    };
3706
3707    use nautilus_model::instruments::CurrencyPair;
3708    use nautilus_testkit::http::assert_http_redirect_rejected;
3709    use rstest::rstest;
3710
3711    use super::*;
3712
3713    #[tokio::test]
3714    async fn test_authenticated_client_rejects_redirects() {
3715        let client = KrakenSpotRawHttpClient::with_credentials(
3716            "key".into(),
3717            "secret".into(),
3718            KrakenEnvironment::Live,
3719            None,
3720            3,
3721            Some(0),
3722            None,
3723            None,
3724            None,
3725            10,
3726        )
3727        .unwrap()
3728        .client;
3729        assert_http_redirect_rejected(|url| async move {
3730            client
3731                .get(url, None, None, Some(3), None)
3732                .await
3733                .unwrap()
3734                .status
3735                .as_u16()
3736        })
3737        .await;
3738    }
3739
3740    #[rstest]
3741    fn test_raw_client_creation() {
3742        let client = KrakenSpotRawHttpClient::default();
3743        assert!(client.credential.is_none());
3744    }
3745
3746    #[rstest]
3747    fn test_raw_client_with_credentials() {
3748        let client = KrakenSpotRawHttpClient::with_credentials(
3749            "test_key".to_string(),
3750            "test_secret".to_string(),
3751            KrakenEnvironment::Live,
3752            None,
3753            60,
3754            None,
3755            None,
3756            None,
3757            None,
3758            KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND,
3759        )
3760        .unwrap();
3761        assert!(client.credential.is_some());
3762    }
3763
3764    #[rstest]
3765    #[tokio::test]
3766    async fn test_order_request_cancellation_before_transport() {
3767        let client = Arc::new(KrakenSpotRawHttpClient::default());
3768        let guard = client.auth_mutex.lock().await;
3769        let cancellation_token = client.cancellation_token();
3770        let waiting_token = cancellation_token.clone();
3771        let waiting_client = Arc::clone(&client);
3772        let waiting = tokio::spawn(async move {
3773            waiting_client
3774                .lock_order_request(&waiting_token)
3775                .await
3776                .map(drop)
3777        });
3778
3779        tokio::task::yield_now().await;
3780        client.cancel_all_requests();
3781        let waiting_result = tokio::time::timeout(Duration::from_secs(1), waiting)
3782            .await
3783            .expect("auth lock wait should stop on cancellation")
3784            .expect("auth lock task should complete");
3785        let request_result = client
3786            .send_order_request(
3787                Method::POST,
3788                "/0/private/AddOrder",
3789                KrakenSpotRawHttpClient::default_headers(),
3790                None,
3791                &cancellation_token,
3792            )
3793            .await;
3794        drop(guard);
3795        client.reset_cancellation_token();
3796        let reset_token = client.cancellation_token();
3797
3798        assert!(matches!(
3799            waiting_result,
3800            Err(KrakenHttpError::RequestNotStarted(ref message))
3801                if message == "Request canceled before transport invocation"
3802        ));
3803        assert!(matches!(
3804            request_result,
3805            Err(KrakenHttpError::RequestNotStarted(ref message))
3806                if message == "Request canceled before transport invocation"
3807        ));
3808        assert!(!reset_token.is_cancelled());
3809    }
3810
3811    #[rstest]
3812    #[tokio::test]
3813    async fn test_trade_volume_request_cancellation_before_transport() {
3814        let client = KrakenSpotRawHttpClient::with_credentials(
3815            "test_key".to_string(),
3816            "dGVzdF9hcGlfc2VjcmV0X2Jhc2U2NA==".to_string(),
3817            KrakenEnvironment::Live,
3818            Some("http://127.0.0.1:1".to_string()),
3819            1,
3820            None,
3821            None,
3822            None,
3823            None,
3824            KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND,
3825        )
3826        .unwrap();
3827        let params = SpotTradeVolumeParams {
3828            pair: SpotTradeVolumePairs::Names("XBTUSDT".to_string()),
3829        };
3830        client.cancel_all_requests();
3831
3832        let result = client.get_trade_volume(&params).await;
3833
3834        assert!(matches!(
3835            result,
3836            Err(KrakenHttpError::NetworkError(ref message))
3837                if message.contains("canceled") || message.contains("cancelled")
3838        ));
3839    }
3840
3841    #[rstest]
3842    fn test_client_creation() {
3843        let client = KrakenSpotHttpClient::default();
3844        assert!(client.instruments_cache.is_empty());
3845    }
3846
3847    #[rstest]
3848    fn test_client_with_credentials() {
3849        let client = KrakenSpotHttpClient::with_credentials(
3850            "test_key".to_string(),
3851            "test_secret".to_string(),
3852            KrakenEnvironment::Live,
3853            None,
3854            60,
3855            None,
3856            None,
3857            None,
3858            None,
3859            KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND,
3860        )
3861        .unwrap();
3862        assert!(client.instruments_cache.is_empty());
3863    }
3864
3865    #[rstest]
3866    fn test_nonce_generation_strictly_increasing() {
3867        let client = KrakenSpotRawHttpClient::default();
3868
3869        let nonce1 = client.generate_nonce();
3870        let nonce2 = client.generate_nonce();
3871        let nonce3 = client.generate_nonce();
3872
3873        assert!(
3874            nonce2 > nonce1,
3875            "nonce2 ({nonce2}) should be > nonce1 ({nonce1})"
3876        );
3877        assert!(
3878            nonce3 > nonce2,
3879            "nonce3 ({nonce3}) should be > nonce2 ({nonce2})"
3880        );
3881    }
3882
3883    #[rstest]
3884    fn test_nonce_is_nanosecond_timestamp() {
3885        let client = KrakenSpotRawHttpClient::default();
3886
3887        let nonce = client.generate_nonce();
3888
3889        // Nonce should be a nanosecond timestamp (roughly 1.7e18 for Dec 2025)
3890        // Verify it's in a reasonable range (> 1.5e18, which is ~2017)
3891        assert!(
3892            nonce > 1_500_000_000_000_000_000,
3893            "Nonce should be nanosecond timestamp"
3894        );
3895    }
3896
3897    #[rstest]
3898    #[case::gtc_limit(true, TimeInForce::Gtc, None, None, None)]
3899    #[case::ioc_limit(true, TimeInForce::Ioc, None, Some("IOC"), None)]
3900    #[case::fok_limit(true, TimeInForce::Fok, None, Some("FOK"), None)]
3901    #[case::gtd_limit_with_expire(
3902        true,
3903        TimeInForce::Gtd,
3904        Some(1_704_067_200_000_000_000u64),
3905        Some("GTD"),
3906        Some("1704067200")
3907    )]
3908    #[case::gtc_market(false, TimeInForce::Gtc, None, None, None)]
3909    #[case::ioc_market(false, TimeInForce::Ioc, None, None, None)]
3910    fn test_compute_time_in_force_success(
3911        #[case] is_limit: bool,
3912        #[case] tif: TimeInForce,
3913        #[case] expire_nanos: Option<u64>,
3914        #[case] expected_tif: Option<&str>,
3915        #[case] expected_expire: Option<&str>,
3916    ) {
3917        let expire_time = expire_nanos.map(UnixNanos::from);
3918        let result = compute_time_in_force(is_limit, tif, expire_time).unwrap();
3919        assert_eq!(result.0, expected_tif.map(String::from));
3920        assert_eq!(result.1, expected_expire.map(String::from));
3921    }
3922
3923    #[rstest]
3924    #[case::gtd_missing_expire(TimeInForce::Gtd, None, "expire_time")]
3925    fn test_compute_time_in_force_errors(
3926        #[case] tif: TimeInForce,
3927        #[case] expire_nanos: Option<u64>,
3928        #[case] expected_error: &str,
3929    ) {
3930        let expire_time = expire_nanos.map(UnixNanos::from);
3931        let result = compute_time_in_force(true, tif, expire_time);
3932        assert!(result.is_err());
3933        assert!(result.unwrap_err().to_string().contains(expected_error));
3934    }
3935
3936    #[rstest]
3937    fn test_build_add_order_params_sets_index_trigger_for_conditional_orders() {
3938        let client = KrakenSpotHttpClient::default();
3939        let instrument_id = cache_test_spot_instrument(&client);
3940
3941        let params = client
3942            .build_add_order_params(
3943                instrument_id,
3944                ClientOrderId::new("spot-trigger-index"),
3945                OrderSide::Buy,
3946                OrderType::StopMarket,
3947                Quantity::from("0.01"),
3948                TimeInForce::Gtc,
3949                None,
3950                None,
3951                Some(Price::from("50000")),
3952                Some(TriggerType::IndexPrice),
3953                None,
3954                None,
3955                false,
3956                false,
3957                false,
3958                None,
3959                None,
3960                AccountType::Cash,
3961            )
3962            .unwrap();
3963
3964        assert_eq!(params.trigger, Some("index".to_string()));
3965        assert_eq!(params.price, Some("50000".to_string()));
3966    }
3967
3968    #[rstest]
3969    fn test_build_add_order_params_sets_trailing_offsets() {
3970        let client = KrakenSpotHttpClient::default();
3971        let instrument_id = cache_test_spot_instrument(&client);
3972
3973        let params = client
3974            .build_add_order_params(
3975                instrument_id,
3976                ClientOrderId::new("spot-trailing"),
3977                OrderSide::Sell,
3978                OrderType::TrailingStopLimit,
3979                Quantity::from("0.01"),
3980                TimeInForce::Gtc,
3981                None,
3982                Some(Price::from("49900")),
3983                None,
3984                Some(TriggerType::LastPrice),
3985                Some(Decimal::from(50)),
3986                Some(Decimal::from(25)),
3987                false,
3988                false,
3989                false,
3990                Some(Quantity::from("0.005")),
3991                None,
3992                AccountType::Cash,
3993            )
3994            .unwrap();
3995
3996        assert_eq!(params.price, Some("50".to_string()));
3997        assert_eq!(params.price2, Some("25".to_string()));
3998        assert_eq!(params.trigger, None);
3999        assert_eq!(params.displayvol, Some("0.005".to_string()));
4000    }
4001
4002    #[rstest]
4003    fn test_build_add_order_params_rejects_unsupported_trigger_type() {
4004        let client = KrakenSpotHttpClient::default();
4005        let instrument_id = cache_test_spot_instrument(&client);
4006
4007        let error = client
4008            .build_add_order_params(
4009                instrument_id,
4010                ClientOrderId::new("spot-trigger-invalid"),
4011                OrderSide::Buy,
4012                OrderType::StopMarket,
4013                Quantity::from("0.01"),
4014                TimeInForce::Gtc,
4015                None,
4016                None,
4017                Some(Price::from("50000")),
4018                Some(TriggerType::MarkPrice),
4019                None,
4020                None,
4021                false,
4022                false,
4023                false,
4024                None,
4025                None,
4026                AccountType::Cash,
4027            )
4028            .unwrap_err();
4029
4030        assert!(
4031            error
4032                .to_string()
4033                .contains("Unsupported trigger type for Kraken Spot")
4034        );
4035    }
4036
4037    fn cache_spot_pair(
4038        client: &KrakenSpotHttpClient,
4039        symbol: &str,
4040        quote: Currency,
4041    ) -> InstrumentId {
4042        let instrument_id = InstrumentId::from(symbol);
4043
4044        client.cache_instrument(InstrumentAny::CurrencyPair(
4045            CurrencyPair::builder()
4046                .instrument_id(instrument_id)
4047                .raw_symbol(Symbol::new(instrument_id.symbol.as_str()))
4048                .base_currency(Currency::BTC())
4049                .quote_currency(quote)
4050                .price_precision(1)
4051                .size_precision(8)
4052                .price_increment(Price::from("0.1"))
4053                .size_increment(Quantity::from("0.00000001"))
4054                .ts_event(0.into())
4055                .ts_init(0.into())
4056                .build()
4057                .unwrap(),
4058        ));
4059
4060        instrument_id
4061    }
4062
4063    /// Bulk position coverage must answer for exactly the instruments the bulk read enumerates.
4064    ///
4065    /// The wallet read only reports pairs quoted in `spot_positions_quote_currency`, so claiming
4066    /// coverage for every instrument would let an absent report force-close a holding the read
4067    /// could never have reported.
4068    #[rstest]
4069    #[case(AccountType::Margin, true, "XBT/USDT.KRAKEN", false)]
4070    #[case(AccountType::Margin, false, "XBT/USDT.KRAKEN", false)]
4071    #[case(AccountType::Cash, false, "XBT/USDT.KRAKEN", false)]
4072    #[case(AccountType::Cash, true, "XBT/USDT.KRAKEN", true)]
4073    #[case(AccountType::Cash, true, "XBT/USD.KRAKEN", false)]
4074    #[case(AccountType::Cash, true, "XBT/EUR.KRAKEN", false)]
4075    fn test_covers_bulk_position_reports(
4076        #[case] account_type: AccountType,
4077        #[case] use_spot_position_reports: bool,
4078        #[case] instrument: &str,
4079        #[case] expected: bool,
4080    ) {
4081        let client = KrakenSpotHttpClient::default();
4082        cache_spot_pair(&client, "XBT/USDT.KRAKEN", Currency::USDT());
4083        cache_spot_pair(&client, "XBT/USD.KRAKEN", Currency::USD());
4084
4085        // `XBT/EUR` is never cached, standing for an instrument the read cannot enumerate.
4086        let covered = client.covers_bulk_position_reports(
4087            InstrumentId::from(instrument),
4088            account_type,
4089            use_spot_position_reports,
4090            Ustr::from("USDT"),
4091        );
4092
4093        assert_eq!(covered, expected);
4094    }
4095
4096    /// A legacy quote code must select the same instruments as its standard spelling.
4097    ///
4098    /// Instruments now carry standard codes, so `ZEUR` has to normalize to `EUR` or an existing
4099    /// setting would stop matching and an absent report could close a holding the read still sees.
4100    #[rstest]
4101    fn test_covers_bulk_position_reports_accepts_legacy_quote_code() {
4102        let client = KrakenSpotHttpClient::default();
4103        let eur = cache_spot_pair(&client, "XBT/EUR.KRAKEN", Currency::EUR());
4104        cache_spot_pair(&client, "XBT/USDT.KRAKEN", Currency::USDT());
4105
4106        let legacy =
4107            client.covers_bulk_position_reports(eur, AccountType::Cash, true, Ustr::from("ZEUR"));
4108        let standard =
4109            client.covers_bulk_position_reports(eur, AccountType::Cash, true, Ustr::from("EUR"));
4110        let other = client.covers_bulk_position_reports(
4111            InstrumentId::from("XBT/USDT.KRAKEN"),
4112            AccountType::Cash,
4113            true,
4114            Ustr::from("ZEUR"),
4115        );
4116
4117        assert!(legacy);
4118        assert!(standard);
4119        assert!(!other);
4120    }
4121
4122    /// A `Balance` row counts toward the covered base it names, in any spelling or suffix, and a
4123    /// dotted base code stays whole when it is itself covered.
4124    #[rstest]
4125    #[case::legacy("XXBT", &["BTC"], Some("BTC"))]
4126    #[case::standard("XBT", &["BTC"], Some("BTC"))]
4127    #[case::suffixed("XBT.F", &["BTC"], Some("BTC"))]
4128    #[case::legacy_suffixed("XXBT.F", &["BTC"], Some("BTC"))]
4129    #[case::margin_suffix("XBT.M", &["BTC"], Some("BTC"))]
4130    #[case::staked("DOT.S", &["DOT"], Some("DOT"))]
4131    #[case::staked_term("DOT28.S", &["DOT"], Some("DOT"))]
4132    #[case::staked_digit_code("ETH2.S", &["ETH"], Some("ETH"))]
4133    #[case::staked_term_atom("ATOM21.S", &["ATOM"], Some("ATOM"))]
4134    #[case::hold("EUR.HOLD", &["EUR"], Some("EUR"))]
4135    #[case::hold_uncovered("EUR.HOLD", &["BTC"], None)]
4136    #[case::bare_digit_code("ETH2", &["ETH"], None)]
4137    #[case::bare_digit_code_luna("LUNA2", &["LUNA"], None)]
4138    #[case::fee_credit("KFEE", &["BTC"], None)]
4139    #[case::uncovered("XXBT", &["ETH"], None)]
4140    #[case::digit_base_suffixed("L3.F", &["L3"], Some("L3"))]
4141    #[case::digit_base_before_stripped("LUNA2.S", &["LUNA2", "LUNA"], Some("LUNA2"))]
4142    #[case::digit_base_stripped("LUNA2.S", &["LUNA"], Some("LUNA"))]
4143    #[case::dotted_base_whole("BRK.Bx", &["BRK.Bx", "BRK"], Some("BRK.Bx"))]
4144    #[case::dotted_base_prefix("BRK.Bx", &["BRK"], Some("BRK"))]
4145    fn test_covered_balance_base(
4146        #[case] key: &str,
4147        #[case] covered: &[&str],
4148        #[case] expected: Option<&str>,
4149    ) {
4150        let covered_bases: HashSet<Ustr> = covered.iter().map(|code| Ustr::from(code)).collect();
4151
4152        assert_eq!(
4153            covered_balance_base(key, &covered_bases),
4154            expected.map(Ustr::from)
4155        );
4156    }
4157
4158    /// An order the venue placed, answered with a transaction ID the model cannot hold, returns the
4159    /// typed error: an untyped one would read as a command never sent and reject a live order.
4160    #[rstest]
4161    #[tokio::test]
4162    async fn test_submit_order_returns_a_typed_error_for_an_invalid_order_id() {
4163        use axum::{Router, http::header, routing::any};
4164
4165        let body = include_str!("../../../test_data/http_add_order_spot.json")
4166            .replace("OUF4EM-FRGI2-MQMWZD", "");
4167        let app = Router::new().route(
4168            "/0/private/AddOrder",
4169            any(move || {
4170                let body = body.clone();
4171                async move { ([(header::CONTENT_TYPE, "application/json")], body) }
4172            }),
4173        );
4174        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4175        let addr = listener.local_addr().unwrap();
4176        tokio::spawn(async move {
4177            axum::serve(listener, app).await.unwrap();
4178        });
4179        let client = KrakenSpotHttpClient::with_credentials(
4180            "test".to_string(),
4181            "c2VjcmV0".to_string(),
4182            KrakenEnvironment::Live,
4183            Some(format!("http://{addr}")),
4184            10,
4185            None,
4186            None,
4187            None,
4188            None,
4189            10,
4190        )
4191        .unwrap();
4192        let instrument_id = cache_test_spot_instrument(&client);
4193
4194        let error = client
4195            .submit_order(
4196                AccountId::from("KRAKEN-001"),
4197                instrument_id,
4198                ClientOrderId::from("O-SUBMIT"),
4199                OrderSide::Buy,
4200                OrderType::Limit,
4201                Quantity::from("0.00100000"),
4202                TimeInForce::Gtc,
4203                None,
4204                Some(Price::from("50000.0")),
4205                None,
4206                None,
4207                None,
4208                None,
4209                false,
4210                false,
4211                false,
4212                None,
4213                None,
4214                AccountType::Cash,
4215            )
4216            .await
4217            .unwrap_err();
4218
4219        assert!(
4220            matches!(
4221                error.downcast_ref::<KrakenSubmitOrderError>(),
4222                Some(KrakenSubmitOrderError::InvalidOrderId { detail })
4223                    if detail.starts_with("Invalid order_id '' in Kraken spot submit response")
4224            ),
4225            "{error:#}"
4226        );
4227    }
4228
4229    /// A spot command that can change venue state, with the endpoint it writes to.
4230    #[derive(Clone, Copy, Debug)]
4231    enum StateChangingSpotCommand {
4232        CancelOrder,
4233        CancelAll,
4234        EditOrder,
4235    }
4236
4237    impl StateChangingSpotCommand {
4238        fn endpoint(self) -> &'static str {
4239            match self {
4240                Self::CancelOrder => "/0/private/CancelOrder",
4241                Self::CancelAll => "/0/private/CancelAll",
4242                Self::EditOrder => "/0/private/EditOrder",
4243            }
4244        }
4245
4246        async fn send(
4247            self,
4248            client: &KrakenSpotRawHttpClient,
4249        ) -> anyhow::Result<(), KrakenHttpError> {
4250            match self {
4251                Self::CancelOrder => {
4252                    let params = KrakenSpotCancelOrderParamsBuilder::default()
4253                        .txid("V-001".to_string())
4254                        .build()
4255                        .expect("cancel params should build");
4256                    client.cancel_order(&params).await.map(|_| ())
4257                }
4258                Self::CancelAll => client.cancel_all_orders().await.map(|_| ()),
4259                Self::EditOrder => {
4260                    let params = KrakenSpotEditOrderParamsBuilder::default()
4261                        .pair(Ustr::from("XXBTZUSD"))
4262                        .txid("V-001".to_string())
4263                        .volume("0.00100000".to_string())
4264                        .build()
4265                        .expect("edit params should build");
4266                    client.edit_order(&params).await.map(|_| ())
4267                }
4268            }
4269        }
4270    }
4271
4272    /// A retryable transport failure as the mock venue presents it.
4273    #[derive(Clone, Copy, Debug)]
4274    enum RetryableTransportFailure {
4275        /// Accepted connections are dropped before any response, failing at the transport layer.
4276        DroppedConnection,
4277        /// HTTP 429, which the client classifies as a retryable network error.
4278        Http429,
4279        /// HTTP 500, which the client classifies as a retryable network error.
4280        Http500,
4281        /// HTTP 200 carrying a rate-limit error array, Kraken's other retryable class.
4282        ApiRateLimit,
4283    }
4284
4285    /// Serves `endpoint` with the given failure and counts the requests that reach it.
4286    async fn spawn_failing_spot_mock(
4287        endpoint: &'static str,
4288        failure: RetryableTransportFailure,
4289    ) -> (String, Arc<AtomicUsize>) {
4290        use axum::{Router, http::StatusCode, routing::post};
4291
4292        let request_count = Arc::new(AtomicUsize::new(0));
4293        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4294        let addr = listener.local_addr().unwrap();
4295
4296        match failure {
4297            RetryableTransportFailure::DroppedConnection => {
4298                let handler_count = request_count.clone();
4299
4300                tokio::spawn(async move {
4301                    loop {
4302                        match listener.accept().await {
4303                            Ok((socket, _)) => {
4304                                handler_count.fetch_add(1, Ordering::Relaxed);
4305                                drop(socket);
4306                            }
4307                            Err(_) => return,
4308                        }
4309                    }
4310                });
4311            }
4312            RetryableTransportFailure::ApiRateLimit => {
4313                let handler_count = request_count.clone();
4314                let router = Router::new().route(
4315                    endpoint,
4316                    post(move || {
4317                        let handler_count = handler_count.clone();
4318
4319                        async move {
4320                            use axum::response::IntoResponse;
4321
4322                            handler_count.fetch_add(1, Ordering::Relaxed);
4323
4324                            (
4325                                [(axum::http::header::CONTENT_TYPE, "application/json")],
4326                                r#"{"error":["EAPI:Rate limit exceeded"],"result":null}"#,
4327                            )
4328                                .into_response()
4329                        }
4330                    }),
4331                );
4332
4333                tokio::spawn(async move {
4334                    axum::serve(listener, router).await.unwrap();
4335                });
4336            }
4337            RetryableTransportFailure::Http429 | RetryableTransportFailure::Http500 => {
4338                let status = match failure {
4339                    RetryableTransportFailure::Http429 => StatusCode::TOO_MANY_REQUESTS,
4340                    RetryableTransportFailure::Http500 => StatusCode::INTERNAL_SERVER_ERROR,
4341                    RetryableTransportFailure::DroppedConnection
4342                    | RetryableTransportFailure::ApiRateLimit => unreachable!(),
4343                };
4344
4345                let handler_count = request_count.clone();
4346                let router = Router::new().route(
4347                    endpoint,
4348                    post(move || {
4349                        let handler_count = handler_count.clone();
4350                        async move {
4351                            handler_count.fetch_add(1, Ordering::Relaxed);
4352                            status
4353                        }
4354                    }),
4355                );
4356
4357                tokio::spawn(async move {
4358                    axum::serve(listener, router).await.unwrap();
4359                });
4360            }
4361        }
4362
4363        (format!("http://{addr}"), request_count)
4364    }
4365
4366    /// Builds a client with retries enabled (three retries, millisecond backoff) so send-once
4367    /// behavior comes from the command's transport, not from the retry configuration.
4368    fn retry_enabled_spot_client(base_url: String) -> KrakenSpotRawHttpClient {
4369        KrakenSpotRawHttpClient::with_credentials(
4370            "test".to_string(),
4371            "c2VjcmV0".to_string(),
4372            KrakenEnvironment::Live,
4373            Some(base_url),
4374            10,
4375            Some(3),
4376            Some(1),
4377            Some(2),
4378            None,
4379            100,
4380        )
4381        .unwrap()
4382    }
4383
4384    /// A spot command that can change venue state reaches the venue exactly once on a retryable
4385    /// failure: a retransmitted cancel or edit may act on venue state twice.
4386    #[rstest]
4387    #[case::cancel_order_dropped_connection(
4388        StateChangingSpotCommand::CancelOrder,
4389        RetryableTransportFailure::DroppedConnection
4390    )]
4391    #[case::cancel_order_http_429(
4392        StateChangingSpotCommand::CancelOrder,
4393        RetryableTransportFailure::Http429
4394    )]
4395    #[case::cancel_order_http_500(
4396        StateChangingSpotCommand::CancelOrder,
4397        RetryableTransportFailure::Http500
4398    )]
4399    #[case::cancel_order_api_rate_limit(
4400        StateChangingSpotCommand::CancelOrder,
4401        RetryableTransportFailure::ApiRateLimit
4402    )]
4403    #[case::cancel_all_dropped_connection(
4404        StateChangingSpotCommand::CancelAll,
4405        RetryableTransportFailure::DroppedConnection
4406    )]
4407    #[case::cancel_all_http_429(
4408        StateChangingSpotCommand::CancelAll,
4409        RetryableTransportFailure::Http429
4410    )]
4411    #[case::cancel_all_http_500(
4412        StateChangingSpotCommand::CancelAll,
4413        RetryableTransportFailure::Http500
4414    )]
4415    #[case::cancel_all_api_rate_limit(
4416        StateChangingSpotCommand::CancelAll,
4417        RetryableTransportFailure::ApiRateLimit
4418    )]
4419    #[case::edit_order_dropped_connection(
4420        StateChangingSpotCommand::EditOrder,
4421        RetryableTransportFailure::DroppedConnection
4422    )]
4423    #[case::edit_order_http_429(
4424        StateChangingSpotCommand::EditOrder,
4425        RetryableTransportFailure::Http429
4426    )]
4427    #[case::edit_order_http_500(
4428        StateChangingSpotCommand::EditOrder,
4429        RetryableTransportFailure::Http500
4430    )]
4431    #[case::edit_order_api_rate_limit(
4432        StateChangingSpotCommand::EditOrder,
4433        RetryableTransportFailure::ApiRateLimit
4434    )]
4435    #[tokio::test]
4436    async fn test_state_changing_spot_command_sends_once_on_retryable_failure(
4437        #[case] command: StateChangingSpotCommand,
4438        #[case] failure: RetryableTransportFailure,
4439    ) {
4440        let (base_url, request_count) = spawn_failing_spot_mock(command.endpoint(), failure).await;
4441        let client = retry_enabled_spot_client(base_url);
4442
4443        let result = command.send(&client).await;
4444
4445        // The failing attempt must be retryable-class, so the single request count below
4446        // proves the command's transport is send-once rather than the failure being final.
4447        assert!(
4448            result.as_ref().is_err_and(kraken_http_should_retry),
4449            "{command:?} on {failure:?} must fail retryably, received {result:?}"
4450        );
4451        assert_eq!(
4452            request_count.load(Ordering::Relaxed),
4453            1,
4454            "{command:?} on {failure:?} must reach the venue exactly once"
4455        );
4456    }
4457
4458    /// Reads keep the retrying transport: a transient HTTP 500 is retried and then succeeds.
4459    #[tokio::test]
4460    async fn test_spot_read_request_still_retries_transient_failure() {
4461        use axum::{
4462            Router,
4463            http::{StatusCode, header},
4464            routing::any,
4465        };
4466
4467        let request_count = Arc::new(AtomicUsize::new(0));
4468        let handler_count = request_count.clone();
4469        let body = include_str!("../../../test_data/http_server_time.json").to_string();
4470
4471        let router = Router::new().route(
4472            "/0/public/Time",
4473            any(move || {
4474                let handler_count = handler_count.clone();
4475                let body = body.clone();
4476                async move {
4477                    use axum::response::IntoResponse;
4478
4479                    if handler_count.fetch_add(1, Ordering::Relaxed) == 0 {
4480                        StatusCode::INTERNAL_SERVER_ERROR.into_response()
4481                    } else {
4482                        ([(header::CONTENT_TYPE, "application/json")], body).into_response()
4483                    }
4484                }
4485            }),
4486        );
4487
4488        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4489        let addr = listener.local_addr().unwrap();
4490        tokio::spawn(async move {
4491            axum::serve(listener, router).await.unwrap();
4492        });
4493
4494        let client = retry_enabled_spot_client(format!("http://{addr}"));
4495
4496        let server_time = client.get_server_time().await.unwrap();
4497
4498        assert_eq!(request_count.load(Ordering::Relaxed), 2);
4499        assert_eq!(server_time.unixtime, 1_762_820_224);
4500        assert_eq!(server_time.rfc1123, "Tue, 11 Nov 25 00:17:04 +0000");
4501    }
4502
4503    fn cache_test_spot_instrument(client: &KrakenSpotHttpClient) -> InstrumentId {
4504        let instrument_id = InstrumentId::from("XBT/USD.KRAKEN");
4505
4506        client.cache_instrument(InstrumentAny::CurrencyPair(
4507            CurrencyPair::builder()
4508                .instrument_id(instrument_id)
4509                .raw_symbol(Symbol::new("XBTUSD"))
4510                .base_currency(Currency::BTC())
4511                .quote_currency(Currency::USD())
4512                .price_precision(1)
4513                .size_precision(8)
4514                .price_increment(Price::from("0.1"))
4515                .size_increment(Quantity::from("0.00000001"))
4516                .ts_event(0.into())
4517                .ts_init(0.into())
4518                .build()
4519                .unwrap(),
4520        ));
4521
4522        instrument_id
4523    }
4524
4525    fn cache_test_spot_instrument_with_leverage(
4526        client: &KrakenSpotHttpClient,
4527        leverage_buy: &[i32],
4528        leverage_sell: &[i32],
4529    ) -> InstrumentId {
4530        let instrument_id = cache_test_spot_instrument(client);
4531        let raw_symbol = Ustr::from("XBTUSD");
4532        client.leverage_tiers_cache.rcu(|m| {
4533            m.insert(raw_symbol, (leverage_buy.to_vec(), leverage_sell.to_vec()));
4534        });
4535        instrument_id
4536    }
4537
4538    #[rstest]
4539    fn test_build_add_order_params_leverage_serialized_as_ratio() {
4540        let client = KrakenSpotHttpClient::default();
4541        let instrument_id =
4542            cache_test_spot_instrument_with_leverage(&client, &[2, 3, 5], &[2, 3, 5]);
4543
4544        let params = client
4545            .build_add_order_params(
4546                instrument_id,
4547                ClientOrderId::new("spot-margin-buy"),
4548                OrderSide::Buy,
4549                OrderType::Limit,
4550                Quantity::from("0.01"),
4551                TimeInForce::Gtc,
4552                None,
4553                Some(Price::from("50000")),
4554                None,
4555                None,
4556                None,
4557                None,
4558                false,
4559                false,
4560                false,
4561                None,
4562                Some(3),
4563                AccountType::Margin,
4564            )
4565            .unwrap();
4566
4567        assert_eq!(params.leverage, Some("3:1".to_string()));
4568    }
4569
4570    #[rstest]
4571    fn test_build_add_order_params_invalid_leverage_rejected() {
4572        let client = KrakenSpotHttpClient::default();
4573        let instrument_id =
4574            cache_test_spot_instrument_with_leverage(&client, &[2, 3, 5], &[2, 3, 5]);
4575
4576        let err = client
4577            .build_add_order_params(
4578                instrument_id,
4579                ClientOrderId::new("spot-margin-bad"),
4580                OrderSide::Buy,
4581                OrderType::Limit,
4582                Quantity::from("0.01"),
4583                TimeInForce::Gtc,
4584                None,
4585                Some(Price::from("50000")),
4586                None,
4587                None,
4588                None,
4589                None,
4590                false,
4591                false,
4592                false,
4593                None,
4594                Some(7),
4595                AccountType::Margin,
4596            )
4597            .unwrap_err();
4598
4599        assert!(
4600            err.to_string().contains("not supported"),
4601            "Expected tier-validation error: {err}"
4602        );
4603    }
4604
4605    #[rstest]
4606    fn test_build_add_order_params_no_leverage_is_cash() {
4607        let client = KrakenSpotHttpClient::default();
4608        let instrument_id =
4609            cache_test_spot_instrument_with_leverage(&client, &[2, 3, 5], &[2, 3, 5]);
4610
4611        let params = client
4612            .build_add_order_params(
4613                instrument_id,
4614                ClientOrderId::new("spot-cash"),
4615                OrderSide::Buy,
4616                OrderType::Limit,
4617                Quantity::from("0.01"),
4618                TimeInForce::Gtc,
4619                None,
4620                Some(Price::from("50000")),
4621                None,
4622                None,
4623                None,
4624                None,
4625                false,
4626                false,
4627                false,
4628                None,
4629                None,
4630                AccountType::Cash,
4631            )
4632            .unwrap();
4633
4634        assert_eq!(
4635            params.leverage, None,
4636            "Cash order should not have leverage field"
4637        );
4638    }
4639
4640    #[rstest]
4641    fn test_build_add_order_params_rejects_per_order_leverage_in_cash_mode() {
4642        let client = KrakenSpotHttpClient::default();
4643        let instrument_id = cache_test_spot_instrument(&client);
4644
4645        let err = client
4646            .build_add_order_params(
4647                instrument_id,
4648                ClientOrderId::new("cash-with-leverage"),
4649                OrderSide::Buy,
4650                OrderType::Limit,
4651                Quantity::from("0.01"),
4652                TimeInForce::Gtc,
4653                None,
4654                Some(Price::from("50000")),
4655                None,
4656                None,
4657                None,
4658                None,
4659                false,
4660                false,
4661                false,
4662                None,
4663                Some(3),
4664                AccountType::Cash,
4665            )
4666            .unwrap_err();
4667
4668        assert!(
4669            err.to_string().contains("Margin"),
4670            "Expected Margin mode rejection: {err}"
4671        );
4672    }
4673
4674    #[rstest]
4675    fn test_build_add_order_params_reduce_only_forwarded_in_margin_mode() {
4676        let client = KrakenSpotHttpClient::default();
4677        let instrument_id = cache_test_spot_instrument(&client);
4678
4679        let params = client
4680            .build_add_order_params(
4681                instrument_id,
4682                ClientOrderId::new("margin-reduce-only"),
4683                OrderSide::Sell,
4684                OrderType::Limit,
4685                Quantity::from("0.01"),
4686                TimeInForce::Gtc,
4687                None,
4688                Some(Price::from("50000")),
4689                None,
4690                None,
4691                None,
4692                None,
4693                true,
4694                false,
4695                false,
4696                None,
4697                None,
4698                AccountType::Margin,
4699            )
4700            .unwrap();
4701
4702        assert_eq!(params.reduce_only, Some(true));
4703    }
4704
4705    #[rstest]
4706    fn test_build_add_order_params_rejects_reduce_only_in_cash_mode() {
4707        let client = KrakenSpotHttpClient::default();
4708        let instrument_id = cache_test_spot_instrument(&client);
4709
4710        let err = client
4711            .build_add_order_params(
4712                instrument_id,
4713                ClientOrderId::new("cash-reduce-only"),
4714                OrderSide::Sell,
4715                OrderType::Limit,
4716                Quantity::from("0.01"),
4717                TimeInForce::Gtc,
4718                None,
4719                Some(Price::from("50000")),
4720                None,
4721                None,
4722                None,
4723                None,
4724                true,
4725                false,
4726                false,
4727                None,
4728                None,
4729                AccountType::Cash,
4730            )
4731            .unwrap_err();
4732
4733        assert!(
4734            err.to_string().contains("reduce_only requires"),
4735            "expected reduce_only Margin rejection: {err}"
4736        );
4737    }
4738
4739    #[rstest]
4740    fn test_build_add_order_params_rejects_leverage_when_tiers_not_loaded() {
4741        let client = KrakenSpotHttpClient::default();
4742        let instrument_id = cache_test_spot_instrument(&client);
4743
4744        let err = client
4745            .build_add_order_params(
4746                instrument_id,
4747                ClientOrderId::new("missing-tiers"),
4748                OrderSide::Buy,
4749                OrderType::Limit,
4750                Quantity::from("0.01"),
4751                TimeInForce::Gtc,
4752                None,
4753                Some(Price::from("50000")),
4754                None,
4755                None,
4756                None,
4757                None,
4758                false,
4759                false,
4760                false,
4761                None,
4762                Some(3),
4763                AccountType::Margin,
4764            )
4765            .unwrap_err();
4766
4767        assert!(
4768            err.to_string().contains("Leverage tiers not loaded"),
4769            "expected cache-miss rejection: {err}"
4770        );
4771    }
4772}