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, 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.get(&base).map_or_default(Vec::as_slice);
2589            let total: Decimal = rows.iter().map(|(_, amount)| *amount).sum();
2590            let held = Quantity::from_decimal_dp(total, size_precision)?;
2591
2592            if !held.is_zero() {
2593                if !reports
2594                    .iter()
2595                    .any(|report| report.instrument_id == instrument_id)
2596                {
2597                    let keys: Vec<&str> = rows
2598                        .iter()
2599                        .filter(|(_, amount)| !amount.is_zero())
2600                        .map(|(key, _)| *key)
2601                        .collect();
2602                    log::warn!(
2603                        "Withholding flat position report for {instrument_id}: {base} balance {held} held in {}",
2604                        keys.join(", "),
2605                    );
2606                }
2607                continue;
2608            }
2609
2610            reports.push(PositionStatusReport::new(
2611                account_id,
2612                instrument_id,
2613                PositionSide::Flat,
2614                Quantity::zero(size_precision),
2615                ts_init,
2616                ts_init,
2617                None,
2618                None,
2619                None,
2620            ));
2621        }
2622
2623        Ok(reports)
2624    }
2625
2626    /// Returns whether a bulk position read covers `instrument_id`, so that an absent report is
2627    /// evidence the position is flat.
2628    ///
2629    /// This mirrors [`Self::request_position_status_reports`] with `instrument_id` left unset.
2630    /// Margin mode reads `OpenPositions`, which reports leveraged positions only, and cash mode
2631    /// without `use_spot_position_reports` reads nothing, so neither covers a spot holding. The
2632    /// wallet read covers an instrument only when it would enumerate it, which one shared
2633    /// predicate decides for the read and for this answer alike.
2634    pub fn covers_bulk_position_reports(
2635        &self,
2636        instrument_id: InstrumentId,
2637        account_type: AccountType,
2638        use_spot_position_reports: bool,
2639        quote_currency: Ustr,
2640    ) -> bool {
2641        if account_type == AccountType::Margin || !use_spot_position_reports {
2642            return false;
2643        }
2644
2645        self.get_cached_instrument(&instrument_id.symbol.inner())
2646            .is_some_and(|instrument| {
2647                wallet_report_base_currency(&instrument, quote_currency).is_some()
2648            })
2649    }
2650
2651    /// Generates position reports from Kraken `OpenPositions` (margin mode).
2652    async fn generate_margin_position_reports(
2653        &self,
2654        account_id: AccountId,
2655        instrument_id: Option<InstrumentId>,
2656    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2657        let open_positions = self
2658            .inner
2659            .get_open_positions(&SpotOpenPositionsParams::default())
2660            .await?;
2661
2662        let ts_init = self.generate_ts_init();
2663
2664        // Aggregate individual lot entries by pair into a signed net quantity.
2665        // Kraken returns one entry per order lot (keyed by ordertxid); buy lots add to net
2666        // quantity and sell lots subtract. A single signed value per pair is correct for a
2667        // NETTING account and avoids emitting conflicting long+short reports for the same
2668        // instrument when opposing lots exist on the same pair. Aggregation uses `Decimal`
2669        // so opposing lots cancel exactly and partial-close noise does not leave residual
2670        // float dust in the reported quantity.
2671        let mut agg: IndexMap<String, OpenPositionAggregate> = IndexMap::new();
2672
2673        let target_pair: Option<Ustr> = match &instrument_id {
2674            Some(target_id) => match self.get_cached_instrument(&target_id.symbol.inner()) {
2675                Some(inst) => Some(Ustr::from(inst.raw_symbol().as_str())),
2676                None => return Ok(Vec::new()),
2677            },
2678            None => None,
2679        };
2680
2681        for (_pos_id, pos) in open_positions.iter() {
2682            if let Some(pair) = target_pair
2683                && pair.as_str() != pos.pair
2684            {
2685                continue;
2686            }
2687
2688            if let Some(status) = pos.posstatus.as_deref()
2689                && status != "open"
2690            {
2691                log::debug!(
2692                    "Skipping non-open OpenPositions entry for {}: posstatus={status}",
2693                    pos.pair,
2694                );
2695                continue;
2696            }
2697
2698            let instrument = self
2699                .get_instrument_by_raw_symbol(pos.pair.as_str())
2700                .ok_or_else(|| {
2701                    anyhow::anyhow!(
2702                        "OpenPositions: instrument not in cache for pair {}",
2703                        pos.pair
2704                    )
2705                })?;
2706
2707            let vol = Decimal::from_str_exact(&pos.vol)
2708                .with_context(|| format!("OpenPositions: failed to parse vol for {}", pos.pair))?;
2709            let vol_closed = Decimal::from_str_exact(&pos.vol_closed).with_context(|| {
2710                format!("OpenPositions: failed to parse vol_closed for {}", pos.pair)
2711            })?;
2712
2713            let lot_net = (vol - vol_closed).max(Decimal::ZERO);
2714            let signed_lot = match pos.side {
2715                KrakenOrderSide::Buy => lot_net,
2716                KrakenOrderSide::Sell => -lot_net,
2717            };
2718
2719            // `cost` is the quote volume for the whole `vol`, so the lot's entry price is their
2720            // ratio. Accumulate each side separately: a blended average across opposing lots
2721            // would not describe the surviving exposure.
2722            let cost = Decimal::from_str_exact(&pos.cost)
2723                .with_context(|| format!("OpenPositions: failed to parse cost for {}", pos.pair))?;
2724
2725            let entry = agg
2726                .entry(pos.pair.clone())
2727                .or_insert_with(|| OpenPositionAggregate::new(instrument.id()));
2728            entry.signed_qty += signed_lot;
2729
2730            if !vol.is_zero() {
2731                let entry_px = cost / vol;
2732
2733                match pos.side {
2734                    KrakenOrderSide::Buy => {
2735                        entry.long_qty += lot_net;
2736                        entry.long_notional += lot_net * entry_px;
2737                    }
2738                    KrakenOrderSide::Sell => {
2739                        entry.short_qty += lot_net;
2740                        entry.short_notional += lot_net * entry_px;
2741                    }
2742                }
2743            }
2744        }
2745
2746        let mut reports = Vec::new();
2747
2748        for (_, aggregate) in agg {
2749            let signed_qty = aggregate.signed_qty;
2750            let inst_id = aggregate.instrument_id;
2751            let instrument = self
2752                .get_cached_instrument(&inst_id.symbol.inner())
2753                .ok_or_else(|| InstrumentLookupError::not_found(inst_id))?;
2754
2755            let side = if signed_qty.is_sign_positive() && !signed_qty.is_zero() {
2756                PositionSide::Long
2757            } else if signed_qty.is_sign_negative() && !signed_qty.is_zero() {
2758                PositionSide::Short
2759            } else {
2760                PositionSide::Flat
2761            };
2762            let quantity = Quantity::from_decimal_dp(signed_qty.abs(), instrument.size_precision())
2763                .map_err(|e| {
2764                    anyhow::anyhow!("OpenPositions: failed to build Quantity for {inst_id}: {e:?}")
2765                })?;
2766            let avg_px_open = aggregate.avg_px_open(side);
2767            let report = PositionStatusReport::new(
2768                account_id,
2769                inst_id,
2770                side,
2771                quantity,
2772                ts_init,
2773                ts_init,
2774                None,
2775                None,
2776                avg_px_open,
2777            )
2778            // Kraken averages the lots that remain open under FIFO, so after a partial close it
2779            // describes the surviving lots rather than the opening fills. It can open a position
2780            // from flat, but must not be compared with a netting average.
2781            .with_avg_px_open_reconciliation(AvgPxReconciliation::OpeningOnly);
2782            reports.push(report);
2783        }
2784
2785        // If a specific instrument was requested but no open position exists for it, emit
2786        // a FLAT report so the engine can reconcile a previously-open position to closed.
2787        // (Kraken omits fully-closed positions from OpenPositions entirely.)
2788        // Only emit for instruments known to this spot client; a missing cache entry means
2789        // the target belongs to a different product type (e.g. futures) and must not receive
2790        // a spurious FLAT from the spot reconciliation path.
2791        if let Some(target_id) = instrument_id {
2792            let already_reported = reports.iter().any(|r| r.instrument_id == target_id);
2793
2794            if !already_reported
2795                && let Some(instrument) = self.get_cached_instrument(&target_id.symbol.inner())
2796            {
2797                let precision = instrument.size_precision();
2798                reports.push(PositionStatusReport::new(
2799                    account_id,
2800                    target_id,
2801                    PositionSide::Flat,
2802                    Quantity::zero(precision),
2803                    ts_init,
2804                    ts_init,
2805                    None,
2806                    None,
2807                    None,
2808                ));
2809            }
2810        }
2811
2812        Ok(reports)
2813    }
2814
2815    /// Generates SPOT position reports from wallet balances.
2816    ///
2817    /// Kraken spot balances are simple totals (no borrowing concept). A requested instrument is
2818    /// reported LONG for a positive balance and FLAT otherwise. The bulk read reports LONG for each
2819    /// covered instrument whose balance is nonzero at its size precision and omits every other
2820    /// instrument.
2821    async fn generate_spot_position_reports_from_wallet(
2822        &self,
2823        account_id: AccountId,
2824        instrument_id: Option<InstrumentId>,
2825        quote_currency: Ustr,
2826    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2827        let balances_raw = self.inner.get_balance().await?;
2828        let ts_init = self.generate_ts_init();
2829        self.spot_position_reports_from_balances(
2830            &balances_raw,
2831            account_id,
2832            instrument_id,
2833            quote_currency,
2834            ts_init,
2835        )
2836    }
2837
2838    fn spot_position_reports_from_balances(
2839        &self,
2840        balances_raw: &BalanceResponse,
2841        account_id: AccountId,
2842        instrument_id: Option<InstrumentId>,
2843        quote_currency: Ustr,
2844        ts_init: UnixNanos,
2845    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2846        let mut wallet_by_coin: HashMap<Ustr, Decimal> = HashMap::new();
2847
2848        for (currency_code, amount_str) in balances_raw {
2849            let balance = match Decimal::from_str_exact(amount_str) {
2850                Ok(b) => b,
2851                Err(_) => continue,
2852            };
2853
2854            if balance.is_zero() {
2855                continue;
2856            }
2857
2858            wallet_by_coin.insert(Ustr::from(normalize_currency_code(currency_code)), balance);
2859        }
2860
2861        let mut reports = Vec::new();
2862
2863        if let Some(instrument_id) = instrument_id {
2864            if let Some(instrument) = self.get_cached_instrument(&instrument_id.symbol.inner()) {
2865                let base_currency = match instrument.base_currency() {
2866                    Some(currency) => currency,
2867                    None => return Ok(reports),
2868                };
2869
2870                let coin = Ustr::from(base_currency.code.as_str());
2871                let wallet_balance = wallet_by_coin.get(&coin).copied().unwrap_or(Decimal::ZERO);
2872
2873                let side = if wallet_balance > Decimal::ZERO {
2874                    PositionSide::Long
2875                } else {
2876                    PositionSide::Flat
2877                };
2878
2879                let abs_balance = wallet_balance.abs();
2880                let quantity = Quantity::from_decimal_dp(abs_balance, instrument.size_precision())?;
2881
2882                let report = PositionStatusReport::new(
2883                    account_id,
2884                    instrument_id,
2885                    side,
2886                    quantity,
2887                    ts_init,
2888                    ts_init,
2889                    None,
2890                    None,
2891                    None,
2892                );
2893
2894                reports.push(report);
2895            }
2896        } else {
2897            let instruments_guard = self.instruments_cache.load();
2898            for instrument in instruments_guard.values() {
2899                let Some(base_currency) = wallet_report_base_currency(instrument, quote_currency)
2900                else {
2901                    continue;
2902                };
2903
2904                let coin = Ustr::from(base_currency.code.as_str());
2905                let wallet_balance = wallet_by_coin.get(&coin).copied().unwrap_or(Decimal::ZERO);
2906
2907                if wallet_balance.is_zero() {
2908                    continue;
2909                }
2910
2911                let side = PositionSide::Long;
2912                let quantity =
2913                    Quantity::from_decimal_dp(wallet_balance, instrument.size_precision())?;
2914
2915                if quantity.is_zero() {
2916                    continue;
2917                }
2918
2919                log::debug!(
2920                    "Spot position: {} {} (quote: {})",
2921                    quantity,
2922                    base_currency.code,
2923                    instrument.quote_currency().code
2924                );
2925
2926                let report = PositionStatusReport::new(
2927                    account_id,
2928                    instrument.id(),
2929                    side,
2930                    quantity,
2931                    ts_init,
2932                    ts_init,
2933                    None,
2934                    None,
2935                    None,
2936                );
2937
2938                reports.push(report);
2939            }
2940        }
2941
2942        Ok(reports)
2943    }
2944
2945    /// Submits a new order to the Kraken Spot exchange.
2946    ///
2947    /// Returns the venue order ID on success. WebSocket handles all execution events.
2948    ///
2949    /// # Errors
2950    ///
2951    /// Returns an error if:
2952    /// - Credentials are missing.
2953    /// - The instrument is not found in cache.
2954    /// - The order type or time in force is not supported.
2955    /// - The request fails.
2956    /// - The order is rejected.
2957    /// - The response carries an invalid order ID.
2958    #[expect(clippy::too_many_arguments)]
2959    pub async fn submit_order(
2960        &self,
2961        _account_id: AccountId,
2962        instrument_id: InstrumentId,
2963        client_order_id: ClientOrderId,
2964        order_side: OrderSide,
2965        order_type: OrderType,
2966        quantity: Quantity,
2967        time_in_force: TimeInForce,
2968        expire_time: Option<UnixNanos>,
2969        price: Option<Price>,
2970        trigger_price: Option<Price>,
2971        trigger_type: Option<TriggerType>,
2972        trailing_offset: Option<Decimal>,
2973        limit_offset: Option<Decimal>,
2974        reduce_only: bool,
2975        post_only: bool,
2976        quote_quantity: bool,
2977        display_qty: Option<Quantity>,
2978        leverage: Option<u16>,
2979        account_type: AccountType,
2980    ) -> anyhow::Result<VenueOrderId> {
2981        let params = self.build_add_order_params(
2982            instrument_id,
2983            client_order_id,
2984            order_side,
2985            order_type,
2986            quantity,
2987            time_in_force,
2988            expire_time,
2989            price,
2990            trigger_price,
2991            trigger_type,
2992            trailing_offset,
2993            limit_offset,
2994            reduce_only,
2995            post_only,
2996            quote_quantity,
2997            display_qty,
2998            leverage,
2999            account_type,
3000        )?;
3001        let response = self.inner.add_order(&params).await?;
3002
3003        let venue_order_id =
3004            response
3005                .txid
3006                .first()
3007                .ok_or_else(|| KrakenSubmitOrderError::MissingOrderId {
3008                    detail: "transaction ID was absent".to_string(),
3009                })?;
3010
3011        parse_venue_order_id(venue_order_id, "spot submit response").map_err(|e| {
3012            KrakenSubmitOrderError::InvalidOrderId {
3013                detail: format!("{e:#}"),
3014            }
3015            .into()
3016        })
3017    }
3018
3019    /// Submits multiple orders to the Kraken Spot exchange.
3020    ///
3021    /// Automatically groups orders by pair and chunks batch requests at the venue
3022    /// limit. Single-order groups fall back to `AddOrder`.
3023    #[expect(clippy::type_complexity)]
3024    pub async fn submit_orders_batch(
3025        &self,
3026        orders: Vec<(
3027            InstrumentId,
3028            ClientOrderId,
3029            OrderSide,
3030            OrderType,
3031            Quantity,
3032            TimeInForce,
3033            Option<UnixNanos>,
3034            Option<Price>,
3035            Option<Price>,
3036            Option<TriggerType>,
3037            Option<Decimal>,
3038            Option<Decimal>,
3039            bool,
3040            bool,
3041            bool,
3042            Option<Quantity>,
3043            Option<u16>,
3044        )>,
3045        account_type: AccountType,
3046    ) -> anyhow::Result<Vec<String>> {
3047        Ok(self
3048            .send_order_batches(orders, account_type)
3049            .await
3050            .into_iter()
3051            .map(|result| match result {
3052                Ok(order) if order.txid.is_some() => "placed".to_string(),
3053                Ok(order) => order.error.unwrap_or_else(|| "Unknown error".to_string()),
3054                Err(e)
3055                    if matches!(
3056                        e.downcast_ref::<KrakenBatchOrderError>(),
3057                        Some(KrakenBatchOrderError::Validation { .. })
3058                    ) =>
3059                {
3060                    format!("validation_error: {e}")
3061                }
3062                Err(e) => format!("batch_error: {e}"),
3063            })
3064            .collect())
3065    }
3066
3067    pub(crate) async fn send_order_batches(
3068        &self,
3069        orders: Vec<SpotBatchOrder>,
3070        account_type: AccountType,
3071    ) -> Vec<anyhow::Result<SpotBatchOrderResponse>> {
3072        let count = orders.len();
3073        if count == 0 {
3074            return Vec::new();
3075        }
3076
3077        let mut results: Vec<Option<anyhow::Result<SpotBatchOrderResponse>>> =
3078            (0..count).map(|_| None).collect();
3079        let mut grouped: AHashMap<Ustr, Vec<(usize, KrakenSpotAddOrderParams)>> = AHashMap::new();
3080
3081        for (
3082            idx,
3083            (
3084                instrument_id,
3085                client_order_id,
3086                order_side,
3087                order_type,
3088                quantity,
3089                time_in_force,
3090                expire_time,
3091                price,
3092                trigger_price,
3093                trigger_type,
3094                trailing_offset,
3095                limit_offset,
3096                reduce_only,
3097                post_only,
3098                quote_quantity,
3099                display_qty,
3100                leverage,
3101            ),
3102        ) in orders.into_iter().enumerate()
3103        {
3104            match self.build_add_order_params(
3105                instrument_id,
3106                client_order_id,
3107                order_side,
3108                order_type,
3109                quantity,
3110                time_in_force,
3111                expire_time,
3112                price,
3113                trigger_price,
3114                trigger_type,
3115                trailing_offset,
3116                limit_offset,
3117                reduce_only,
3118                post_only,
3119                quote_quantity,
3120                display_qty,
3121                leverage,
3122                account_type,
3123            ) {
3124                Ok(params) => {
3125                    grouped.entry(params.pair).or_default().push((idx, params));
3126                }
3127                Err(e) => {
3128                    results[idx] = Some(Err(KrakenBatchOrderError::Validation {
3129                        reason: e.to_string(),
3130                    }
3131                    .into()));
3132                }
3133            }
3134        }
3135
3136        let mut batches = Vec::new();
3137        let mut grouped_orders: Vec<_> = grouped.into_values().collect();
3138        grouped_orders.sort_by_key(|group| group.first().map_or(usize::MAX, |(idx, _)| *idx));
3139        for group in grouped_orders {
3140            batches.extend(group.chunks(BATCH_SUBMIT_LIMIT).map(|chunk| chunk.to_vec()));
3141        }
3142
3143        for (batch_index, batch) in batches.iter().enumerate() {
3144            let response = if batch.len() == 1 {
3145                self.inner
3146                    .add_order(&batch[0].1)
3147                    .await
3148                    .map(|response| SpotAddOrderBatchResponse {
3149                        orders: vec![SpotBatchOrderResponse {
3150                            descr: response.descr,
3151                            error: None,
3152                            txid: response.txid.into_iter().next(),
3153                        }],
3154                    })
3155            } else {
3156                let params = KrakenSpotAddOrderBatchParams {
3157                    pair: batch[0].1.pair,
3158                    orders: batch
3159                        .iter()
3160                        .map(|(_, params)| params.clone().into())
3161                        .collect(),
3162                    asset_class: batch[0].1.asset_class,
3163                };
3164                self.inner.add_order_batch(&params).await
3165            };
3166
3167            match response {
3168                // AddOrderBatch returns result items in request order, so exact cardinality makes
3169                // positional correlation unambiguous.
3170                Ok(response) if response.orders.len() == batch.len() => {
3171                    for ((idx, _), order) in batch.iter().zip(response.orders) {
3172                        results[*idx] = Some(Ok(order));
3173                    }
3174                }
3175                Ok(response) => {
3176                    for (idx, _) in batch {
3177                        results[*idx] = Some(Err(KrakenBatchOrderError::ResponseCount {
3178                            expected: batch.len(),
3179                            actual: response.orders.len(),
3180                        }
3181                        .into()));
3182                    }
3183                }
3184                Err(e) => {
3185                    for (idx, _) in batch {
3186                        results[*idx] = Some(Err(anyhow::Error::new(e.clone())));
3187                    }
3188
3189                    for later_batch in &batches[batch_index + 1..] {
3190                        for (idx, _) in later_batch {
3191                            results[*idx] = Some(Err(KrakenBatchOrderError::NotAttempted.into()));
3192                        }
3193                    }
3194                    break;
3195                }
3196            }
3197        }
3198
3199        results
3200            .into_iter()
3201            .map(|result| result.unwrap_or_else(|| Err(KrakenBatchOrderError::NotAttempted.into())))
3202            .collect()
3203    }
3204
3205    /// Modifies an existing order on the Kraken Spot exchange using atomic amend.
3206    ///
3207    /// Uses the AmendOrder endpoint which modifies the order in-place,
3208    /// keeping the same order ID and queue position.
3209    ///
3210    /// Returns the supplied `venue_order_id` as `Some`, or `None` when amending
3211    /// by `client_order_id` alone.
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<Option<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 if provided
3265        Ok(venue_order_id)
3266    }
3267
3268    /// Cancels an order on the Kraken Spot exchange.
3269    ///
3270    /// # Errors
3271    ///
3272    /// Returns an error if:
3273    /// - Credentials are missing.
3274    /// - Neither client_order_id nor venue_order_id is provided.
3275    /// - The request fails.
3276    /// - The order cancellation is rejected.
3277    pub async fn cancel_order(
3278        &self,
3279        _account_id: AccountId,
3280        instrument_id: InstrumentId,
3281        client_order_id: Option<ClientOrderId>,
3282        venue_order_id: Option<VenueOrderId>,
3283    ) -> anyhow::Result<()> {
3284        let _ = self
3285            .get_cached_instrument(&instrument_id.symbol.inner())
3286            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
3287
3288        let txid = venue_order_id.as_ref().map(|id| id.to_string());
3289        let cl_ord_id = client_order_id.as_ref().map(truncate_cl_ord_id);
3290
3291        if txid.is_none() && cl_ord_id.is_none() {
3292            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
3293        }
3294
3295        // Prefer txid (venue identifier) since Kraken always knows it.
3296        // cl_ord_id may not be known to Kraken for reconciled orders.
3297        let mut builder = KrakenSpotCancelOrderParamsBuilder::default();
3298
3299        if let Some(ref id) = txid {
3300            builder.txid(id.clone());
3301        } else if let Some(ref id) = cl_ord_id {
3302            builder.cl_ord_id(id.clone());
3303        }
3304        let params = builder
3305            .build()
3306            .map_err(|e| anyhow::anyhow!("Failed to build cancel params: {e}"))?;
3307
3308        self.inner.cancel_order(&params).await?;
3309
3310        Ok(())
3311    }
3312
3313    /// Cancels multiple orders on the Kraken Spot exchange (batched, max 50 per request).
3314    pub async fn cancel_orders_batch(
3315        &self,
3316        venue_order_ids: Vec<VenueOrderId>,
3317    ) -> anyhow::Result<i32> {
3318        if venue_order_ids.is_empty() {
3319            return Ok(0);
3320        }
3321
3322        let mut total_cancelled = 0;
3323
3324        for chunk in venue_order_ids.chunks(BATCH_CANCEL_LIMIT) {
3325            let orders: Vec<String> = chunk.iter().map(|id| id.to_string()).collect();
3326            let params = KrakenSpotCancelOrderBatchParams {
3327                orders,
3328                cl_ord_ids: Vec::new(),
3329            };
3330
3331            let response = self.inner.cancel_order_batch(&params).await?;
3332            total_cancelled += response.count;
3333        }
3334
3335        Ok(total_cancelled)
3336    }
3337
3338    #[expect(clippy::too_many_arguments)]
3339    fn build_add_order_params(
3340        &self,
3341        instrument_id: InstrumentId,
3342        client_order_id: ClientOrderId,
3343        order_side: OrderSide,
3344        order_type: OrderType,
3345        quantity: Quantity,
3346        time_in_force: TimeInForce,
3347        expire_time: Option<UnixNanos>,
3348        price: Option<Price>,
3349        trigger_price: Option<Price>,
3350        trigger_type: Option<TriggerType>,
3351        trailing_offset: Option<Decimal>,
3352        limit_offset: Option<Decimal>,
3353        reduce_only: bool,
3354        post_only: bool,
3355        quote_quantity: bool,
3356        display_qty: Option<Quantity>,
3357        leverage: Option<u16>,
3358        account_type: AccountType,
3359    ) -> anyhow::Result<KrakenSpotAddOrderParams> {
3360        let instrument = self
3361            .get_cached_instrument(&instrument_id.symbol.inner())
3362            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
3363
3364        let raw_symbol = instrument.raw_symbol().inner();
3365        let asset_class = Self::asset_class_for(&instrument);
3366
3367        let kraken_side = match order_side {
3368            OrderSide::Buy => KrakenOrderSide::Buy,
3369            OrderSide::Sell => KrakenOrderSide::Sell,
3370        };
3371
3372        let kraken_order_type = match order_type {
3373            OrderType::Market => KrakenOrderType::Market,
3374            OrderType::Limit => KrakenOrderType::Limit,
3375            OrderType::StopMarket => KrakenOrderType::StopLoss,
3376            OrderType::StopLimit => KrakenOrderType::StopLossLimit,
3377            OrderType::MarketIfTouched => KrakenOrderType::TakeProfit,
3378            OrderType::LimitIfTouched => KrakenOrderType::TakeProfitLimit,
3379            OrderType::TrailingStopMarket => KrakenOrderType::TrailingStop,
3380            OrderType::TrailingStopLimit => KrakenOrderType::TrailingStopLimit,
3381            _ => anyhow::bail!("Unsupported order type: {order_type:?}"),
3382        };
3383
3384        let mut oflags = Vec::new();
3385        let is_limit_order = matches!(
3386            order_type,
3387            OrderType::Limit
3388                | OrderType::StopLimit
3389                | OrderType::LimitIfTouched
3390                | OrderType::TrailingStopLimit
3391        );
3392
3393        if time_in_force == TimeInForce::Fok && order_type != OrderType::Limit {
3394            anyhow::bail!("FOK time in force only supported for LIMIT orders on Kraken Spot");
3395        }
3396
3397        let (timeinforce, expiretm) =
3398            compute_time_in_force(is_limit_order, time_in_force, expire_time)?;
3399
3400        if post_only {
3401            oflags.push(KRAKEN_OFLAG_POST_ONLY);
3402        }
3403
3404        if quote_quantity {
3405            oflags.push(KRAKEN_OFLAG_QUOTE_QUANTITY);
3406        }
3407
3408        let mut builder = KrakenSpotAddOrderParamsBuilder::default();
3409        builder
3410            .cl_ord_id(truncate_cl_ord_id(&client_order_id))
3411            .broker(NAUTILUS_KRAKEN_BROKER_ID)
3412            .pair(raw_symbol)
3413            .side(kraken_side)
3414            .volume(quantity.to_string())
3415            .order_type(kraken_order_type);
3416
3417        let is_conditional = matches!(
3418            order_type,
3419            OrderType::StopMarket
3420                | OrderType::StopLimit
3421                | OrderType::MarketIfTouched
3422                | OrderType::LimitIfTouched
3423                | OrderType::TrailingStopMarket
3424                | OrderType::TrailingStopLimit
3425        );
3426
3427        let is_trailing = matches!(
3428            order_type,
3429            OrderType::TrailingStopMarket | OrderType::TrailingStopLimit
3430        );
3431
3432        if is_trailing {
3433            if trigger_price.is_some() {
3434                anyhow::bail!(
3435                    "Kraken Spot trailing stops do not support activation trigger prices"
3436                );
3437            }
3438
3439            if let Some(offset) = trailing_offset {
3440                builder.price(offset.to_string());
3441            }
3442
3443            if let Some(offset) = limit_offset {
3444                builder.price2(offset.to_string());
3445            }
3446        } else if is_conditional {
3447            if let Some(trigger) = trigger_price {
3448                builder.price(trigger.to_string());
3449            }
3450
3451            if let Some(limit) = price {
3452                builder.price2(limit.to_string());
3453            }
3454        } else if let Some(limit) = price {
3455            builder.price(limit.to_string());
3456        }
3457
3458        if is_conditional {
3459            match trigger_type {
3460                Some(TriggerType::IndexPrice) => {
3461                    builder.trigger("index".to_string());
3462                }
3463                Some(TriggerType::LastPrice | TriggerType::Default) | None => {}
3464                Some(other) => {
3465                    anyhow::bail!(
3466                        "Unsupported trigger type for Kraken Spot: {other:?} (only LastPrice and IndexPrice supported)"
3467                    );
3468                }
3469            }
3470        }
3471
3472        if !oflags.is_empty() {
3473            builder.oflags(oflags.join(","));
3474        }
3475
3476        if let Some(tif) = timeinforce {
3477            builder.timeinforce(tif);
3478        }
3479
3480        if let Some(expire) = expiretm {
3481            builder.expiretm(expire);
3482        }
3483
3484        if let Some(dq) = display_qty {
3485            builder.displayvol(dq.to_string());
3486        }
3487
3488        if let Some(ac) = asset_class {
3489            builder.asset_class(ac);
3490        }
3491
3492        if leverage.is_some() && account_type != AccountType::Margin {
3493            anyhow::bail!("leverage requires spot_account_type=Margin (current: Cash)");
3494        }
3495
3496        if let Some(n) = leverage {
3497            let tiers = self.leverage_tiers_cache.get_cloned(&raw_symbol);
3498            let (buy_tiers, sell_tiers) = tiers.ok_or_else(|| {
3499                anyhow::anyhow!(
3500                    "Leverage tiers not loaded for {raw_symbol}; cannot validate leverage {n}:1 (instruments must be initialized before submitting margin orders)"
3501                )
3502            })?;
3503            let valid_tiers = match order_side {
3504                OrderSide::Buy => buy_tiers,
3505                _ => sell_tiers,
3506            };
3507            let side_label = match order_side {
3508                OrderSide::Buy => "buy",
3509                _ => "sell",
3510            };
3511
3512            if valid_tiers.is_empty() {
3513                anyhow::bail!("Leverage not supported for {raw_symbol} on {side_label} side");
3514            }
3515
3516            if !valid_tiers.contains(&(n as i32)) {
3517                anyhow::bail!(
3518                    "Leverage {n}:1 not supported for {raw_symbol} on {side_label} side (valid: {valid_tiers:?})"
3519                );
3520            }
3521            builder.leverage(format!("{n}:1"));
3522        }
3523
3524        if reduce_only {
3525            if account_type != AccountType::Margin {
3526                anyhow::bail!("reduce_only requires spot_account_type=Margin (current: Cash)");
3527            }
3528            builder.reduce_only(true);
3529        }
3530
3531        builder
3532            .build()
3533            .map_err(|e| anyhow::anyhow!("Failed to build order params: {e}"))
3534    }
3535}
3536
3537fn collect_spot_statuses(
3538    asset_pairs: &AssetPairsResponse,
3539) -> AHashMap<InstrumentId, MarketStatusAction> {
3540    asset_pairs
3541        .iter()
3542        .map(|(_, definition)| {
3543            let symbol_str = definition.wsname.as_ref().unwrap_or(&definition.altname);
3544            let normalized_symbol = normalize_spot_symbol(symbol_str.as_str());
3545            let instrument_id = InstrumentId::new(Symbol::new(&normalized_symbol), *KRAKEN_VENUE);
3546            let action = definition
3547                .status
3548                .map_or(MarketStatusAction::Trading, MarketStatusAction::from);
3549
3550            (instrument_id, action)
3551        })
3552        .collect()
3553}
3554
3555/// Maps raw symbol (altname, e.g. "XBTUSD") to leverage tiers.
3556type LeverageTiersCache = Arc<AtomicMap<Ustr, (Vec<i32>, Vec<i32>)>>;
3557
3558/// Accumulates `OpenPositions` lots for one pair.
3559///
3560/// Each side is tracked separately, so the entry average describes the side that survives netting
3561/// rather than blending opposing lots.
3562struct OpenPositionAggregate {
3563    instrument_id: InstrumentId,
3564    signed_qty: Decimal,
3565    long_qty: Decimal,
3566    long_notional: Decimal,
3567    short_qty: Decimal,
3568    short_notional: Decimal,
3569}
3570
3571impl OpenPositionAggregate {
3572    fn new(instrument_id: InstrumentId) -> Self {
3573        Self {
3574            instrument_id,
3575            signed_qty: Decimal::ZERO,
3576            long_qty: Decimal::ZERO,
3577            long_notional: Decimal::ZERO,
3578            short_qty: Decimal::ZERO,
3579            short_notional: Decimal::ZERO,
3580        }
3581    }
3582
3583    /// Returns the entry average for the netted side, or `None` when it cannot be derived.
3584    fn avg_px_open(&self, side: PositionSide) -> Option<Decimal> {
3585        match side {
3586            PositionSide::Long if !self.long_qty.is_zero() => {
3587                Some(self.long_notional / self.long_qty)
3588            }
3589            PositionSide::Short if !self.short_qty.is_zero() => {
3590                Some(self.short_notional / self.short_qty)
3591            }
3592            _ => None,
3593        }
3594    }
3595}
3596
3597struct TradeBalanceSnapshot {
3598    margins: Vec<MarginBalance>,
3599    metrics: IndexMap<String, String>,
3600    free_margin: Decimal,
3601    equity: Decimal,
3602}
3603
3604/// Returns the base currency whose wallet balance the bulk position read reports for `instrument`,
3605/// or `None` when the read skips it.
3606///
3607/// The read only covers pairs quoted in the configured `spot_positions_quote_currency`, and it
3608/// needs a base currency to name the holding. A configured code matches in either spelling, so an
3609/// existing `ZEUR` setting still selects euro-quoted instruments now that they carry `EUR`. Both
3610/// decisions live here so that the coverage declared through
3611/// [`KrakenSpotHttpClient::covers_bulk_position_reports`] cannot drift from what the read actually
3612/// enumerates.
3613fn wallet_report_base_currency(
3614    instrument: &InstrumentAny,
3615    quote_currency: Ustr,
3616) -> Option<Currency> {
3617    let quote_filter = Ustr::from(normalize_currency_code(quote_currency.as_str()));
3618    if instrument.quote_currency().code != quote_filter {
3619        return None;
3620    }
3621
3622    instrument.base_currency()
3623}
3624
3625/// Returns the covered base currency that a `Balance` row counts toward, or `None`.
3626///
3627/// The whole key matches first, so a dotted code such as `BRK.Bx` stays whole. Otherwise a dotted
3628/// key counts toward the code before its last dot, as is or with trailing digits stripped, so
3629/// `XBT.F`, `L3.F`, `DOT28.S` and `EUR.HOLD` count toward `BTC`, `L3`, `DOT` and `EUR`.
3630fn covered_balance_base(key: &str, covered_bases: &HashSet<Ustr>) -> Option<Ustr> {
3631    let whole = Ustr::from(normalize_currency_code(key));
3632    if covered_bases.contains(&whole) {
3633        return Some(whole);
3634    }
3635
3636    let (code, _) = key.rsplit_once('.')?;
3637    let base = Ustr::from(normalize_currency_code(code));
3638    if covered_bases.contains(&base) {
3639        return Some(base);
3640    }
3641
3642    let stripped = code.trim_end_matches(|c: char| c.is_ascii_digit());
3643    let base = Ustr::from(normalize_currency_code(stripped));
3644    covered_bases.contains(&base).then_some(base)
3645}
3646
3647/// Parses an optional `BalanceEx` credit amount, treating an absent field as zero.
3648///
3649/// Kraken only includes `credit` and `credit_used` for accounts holding a credit line, so their
3650/// absence means no credit rather than an unknown amount. Returns `None` when the field is present
3651/// but unparsable, so the caller can skip the balance rather than understate it.
3652fn optional_credit_amount(value: Option<&str>) -> Option<Decimal> {
3653    match value {
3654        Some(amount) => Decimal::from_str_exact(amount).ok(),
3655        None => Some(Decimal::ZERO),
3656    }
3657}
3658
3659/// Resolves the Nautilus [`Currency`] used to denominate `TradeBalance` margin metrics.
3660///
3661/// Kraken's `TradeBalance` defaults to `ZUSD` when no asset is supplied. This maps Kraken's
3662/// legacy asset codes to their standard equivalents and falls back to a 2dp fiat currency for
3663/// unknown codes so unusual collateral assets still produce a tagged `MarginBalance`.
3664fn trade_balance_currency(asset: Option<&str>) -> Currency {
3665    let raw = asset.unwrap_or("ZUSD");
3666    let normalized = normalize_currency_code(raw);
3667    Currency::try_from_str(normalized)
3668        .unwrap_or_else(|| Currency::new(normalized, 2, 0, normalized, CurrencyType::Fiat))
3669}
3670
3671fn compute_time_in_force(
3672    is_limit_order: bool,
3673    time_in_force: TimeInForce,
3674    expire_time: Option<UnixNanos>,
3675) -> anyhow::Result<(Option<String>, Option<String>)> {
3676    if !is_limit_order {
3677        return Ok((None, None));
3678    }
3679
3680    match time_in_force {
3681        TimeInForce::Gtc => Ok((None, None)),
3682        TimeInForce::Ioc => Ok((Some("IOC".to_string()), None)),
3683        TimeInForce::Fok => Ok((Some("FOK".to_string()), None)),
3684        TimeInForce::Gtd => {
3685            let expire = expire_time.ok_or_else(|| {
3686                anyhow::anyhow!("GTD time in force requires expire_time parameter")
3687            })?;
3688            let expire_secs = expire.as_u64() / NANOSECONDS_IN_SECOND;
3689            Ok((Some("GTD".to_string()), Some(expire_secs.to_string())))
3690        }
3691        _ => anyhow::bail!("Unsupported time in force: {time_in_force:?}"),
3692    }
3693}
3694
3695#[cfg(test)]
3696mod tests {
3697    use std::{
3698        sync::{
3699            Arc,
3700            atomic::{AtomicUsize, Ordering},
3701        },
3702        time::Duration,
3703    };
3704
3705    use axum::{Router, http::header, routing::post};
3706    use nautilus_model::instruments::CurrencyPair;
3707    use nautilus_testkit::http::assert_http_redirect_rejected;
3708    use rstest::rstest;
3709
3710    use super::*;
3711
3712    #[tokio::test]
3713    async fn test_authenticated_client_rejects_redirects() {
3714        let client = KrakenSpotRawHttpClient::with_credentials(
3715            "key".into(),
3716            "secret".into(),
3717            KrakenEnvironment::Live,
3718            None,
3719            3,
3720            Some(0),
3721            None,
3722            None,
3723            None,
3724            10,
3725        )
3726        .unwrap()
3727        .client;
3728        assert_http_redirect_rejected(|url| async move {
3729            client
3730                .get(url, None, None, Some(3), None)
3731                .await
3732                .unwrap()
3733                .status
3734                .as_u16()
3735        })
3736        .await;
3737    }
3738
3739    #[rstest]
3740    fn test_raw_client_creation() {
3741        let client = KrakenSpotRawHttpClient::default();
3742        assert!(client.credential.is_none());
3743    }
3744
3745    #[rstest]
3746    fn test_raw_client_with_credentials() {
3747        let client = KrakenSpotRawHttpClient::with_credentials(
3748            "test_key".to_string(),
3749            "test_secret".to_string(),
3750            KrakenEnvironment::Live,
3751            None,
3752            60,
3753            None,
3754            None,
3755            None,
3756            None,
3757            KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND,
3758        )
3759        .unwrap();
3760        assert!(client.credential.is_some());
3761    }
3762
3763    #[rstest]
3764    #[tokio::test]
3765    async fn test_order_request_cancellation_before_transport() {
3766        let client = Arc::new(KrakenSpotRawHttpClient::default());
3767        let guard = client.auth_mutex.lock().await;
3768        let cancellation_token = client.cancellation_token();
3769        let waiting_token = cancellation_token.clone();
3770        let waiting_client = Arc::clone(&client);
3771        let waiting = tokio::spawn(async move {
3772            waiting_client
3773                .lock_order_request(&waiting_token)
3774                .await
3775                .map(drop)
3776        });
3777
3778        tokio::task::yield_now().await;
3779        client.cancel_all_requests();
3780        let waiting_result = tokio::time::timeout(Duration::from_secs(1), waiting)
3781            .await
3782            .expect("auth lock wait should stop on cancellation")
3783            .expect("auth lock task should complete");
3784        let request_result = client
3785            .send_order_request(
3786                Method::POST,
3787                "/0/private/AddOrder",
3788                KrakenSpotRawHttpClient::default_headers(),
3789                None,
3790                &cancellation_token,
3791            )
3792            .await;
3793        drop(guard);
3794        client.reset_cancellation_token();
3795        let reset_token = client.cancellation_token();
3796
3797        assert!(matches!(
3798            waiting_result,
3799            Err(KrakenHttpError::RequestNotStarted(ref message))
3800                if message == "Request canceled before transport invocation"
3801        ));
3802        assert!(matches!(
3803            request_result,
3804            Err(KrakenHttpError::RequestNotStarted(ref message))
3805                if message == "Request canceled before transport invocation"
3806        ));
3807        assert!(!reset_token.is_cancelled());
3808    }
3809
3810    #[rstest]
3811    #[tokio::test]
3812    async fn test_trade_volume_request_cancellation_before_transport() {
3813        let client = KrakenSpotRawHttpClient::with_credentials(
3814            "test_key".to_string(),
3815            "dGVzdF9hcGlfc2VjcmV0X2Jhc2U2NA==".to_string(),
3816            KrakenEnvironment::Live,
3817            Some("http://127.0.0.1:1".to_string()),
3818            1,
3819            None,
3820            None,
3821            None,
3822            None,
3823            KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND,
3824        )
3825        .unwrap();
3826        let params = SpotTradeVolumeParams {
3827            pair: SpotTradeVolumePairs::Names("XBTUSDT".to_string()),
3828        };
3829        client.cancel_all_requests();
3830
3831        let result = client.get_trade_volume(&params).await;
3832
3833        assert!(matches!(
3834            result,
3835            Err(KrakenHttpError::NetworkError(ref message))
3836                if message.contains("canceled") || message.contains("cancelled")
3837        ));
3838    }
3839
3840    #[rstest]
3841    fn test_client_creation() {
3842        let client = KrakenSpotHttpClient::default();
3843        assert!(client.instruments_cache.is_empty());
3844    }
3845
3846    #[rstest]
3847    fn test_client_with_credentials() {
3848        let client = KrakenSpotHttpClient::with_credentials(
3849            "test_key".to_string(),
3850            "test_secret".to_string(),
3851            KrakenEnvironment::Live,
3852            None,
3853            60,
3854            None,
3855            None,
3856            None,
3857            None,
3858            KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND,
3859        )
3860        .unwrap();
3861        assert!(client.instruments_cache.is_empty());
3862    }
3863
3864    #[rstest]
3865    fn test_nonce_generation_strictly_increasing() {
3866        let client = KrakenSpotRawHttpClient::default();
3867
3868        let nonce1 = client.generate_nonce();
3869        let nonce2 = client.generate_nonce();
3870        let nonce3 = client.generate_nonce();
3871
3872        assert!(
3873            nonce2 > nonce1,
3874            "nonce2 ({nonce2}) should be > nonce1 ({nonce1})"
3875        );
3876        assert!(
3877            nonce3 > nonce2,
3878            "nonce3 ({nonce3}) should be > nonce2 ({nonce2})"
3879        );
3880    }
3881
3882    #[rstest]
3883    fn test_nonce_is_nanosecond_timestamp() {
3884        let client = KrakenSpotRawHttpClient::default();
3885
3886        let nonce = client.generate_nonce();
3887
3888        // Nonce should be a nanosecond timestamp (roughly 1.7e18 for Dec 2025)
3889        // Verify it's in a reasonable range (> 1.5e18, which is ~2017)
3890        assert!(
3891            nonce > 1_500_000_000_000_000_000,
3892            "Nonce should be nanosecond timestamp"
3893        );
3894    }
3895
3896    #[rstest]
3897    #[case::gtc_limit(true, TimeInForce::Gtc, None, None, None)]
3898    #[case::ioc_limit(true, TimeInForce::Ioc, None, Some("IOC"), None)]
3899    #[case::fok_limit(true, TimeInForce::Fok, None, Some("FOK"), None)]
3900    #[case::gtd_limit_with_expire(
3901        true,
3902        TimeInForce::Gtd,
3903        Some(1_704_067_200_000_000_000u64),
3904        Some("GTD"),
3905        Some("1704067200")
3906    )]
3907    #[case::gtc_market(false, TimeInForce::Gtc, None, None, None)]
3908    #[case::ioc_market(false, TimeInForce::Ioc, None, None, None)]
3909    fn test_compute_time_in_force_success(
3910        #[case] is_limit: bool,
3911        #[case] tif: TimeInForce,
3912        #[case] expire_nanos: Option<u64>,
3913        #[case] expected_tif: Option<&str>,
3914        #[case] expected_expire: Option<&str>,
3915    ) {
3916        let expire_time = expire_nanos.map(UnixNanos::from);
3917        let result = compute_time_in_force(is_limit, tif, expire_time).unwrap();
3918        assert_eq!(result.0, expected_tif.map(String::from));
3919        assert_eq!(result.1, expected_expire.map(String::from));
3920    }
3921
3922    #[rstest]
3923    #[case::gtd_missing_expire(TimeInForce::Gtd, None, "expire_time")]
3924    fn test_compute_time_in_force_errors(
3925        #[case] tif: TimeInForce,
3926        #[case] expire_nanos: Option<u64>,
3927        #[case] expected_error: &str,
3928    ) {
3929        let expire_time = expire_nanos.map(UnixNanos::from);
3930        let result = compute_time_in_force(true, tif, expire_time);
3931        assert!(result.is_err());
3932        assert!(result.unwrap_err().to_string().contains(expected_error));
3933    }
3934
3935    #[rstest]
3936    fn test_build_add_order_params_sets_index_trigger_for_conditional_orders() {
3937        let client = KrakenSpotHttpClient::default();
3938        let instrument_id = cache_test_spot_instrument(&client);
3939
3940        let params = client
3941            .build_add_order_params(
3942                instrument_id,
3943                ClientOrderId::new("spot-trigger-index"),
3944                OrderSide::Buy,
3945                OrderType::StopMarket,
3946                Quantity::from("0.01"),
3947                TimeInForce::Gtc,
3948                None,
3949                None,
3950                Some(Price::from("50000")),
3951                Some(TriggerType::IndexPrice),
3952                None,
3953                None,
3954                false,
3955                false,
3956                false,
3957                None,
3958                None,
3959                AccountType::Cash,
3960            )
3961            .unwrap();
3962
3963        assert_eq!(params.trigger, Some("index".to_string()));
3964        assert_eq!(params.price, Some("50000".to_string()));
3965    }
3966
3967    #[rstest]
3968    fn test_build_add_order_params_sets_trailing_offsets() {
3969        let client = KrakenSpotHttpClient::default();
3970        let instrument_id = cache_test_spot_instrument(&client);
3971
3972        let params = client
3973            .build_add_order_params(
3974                instrument_id,
3975                ClientOrderId::new("spot-trailing"),
3976                OrderSide::Sell,
3977                OrderType::TrailingStopLimit,
3978                Quantity::from("0.01"),
3979                TimeInForce::Gtc,
3980                None,
3981                Some(Price::from("49900")),
3982                None,
3983                Some(TriggerType::LastPrice),
3984                Some(Decimal::from(50)),
3985                Some(Decimal::from(25)),
3986                false,
3987                false,
3988                false,
3989                Some(Quantity::from("0.005")),
3990                None,
3991                AccountType::Cash,
3992            )
3993            .unwrap();
3994
3995        assert_eq!(params.price, Some("50".to_string()));
3996        assert_eq!(params.price2, Some("25".to_string()));
3997        assert_eq!(params.trigger, None);
3998        assert_eq!(params.displayvol, Some("0.005".to_string()));
3999    }
4000
4001    #[rstest]
4002    fn test_build_add_order_params_rejects_unsupported_trigger_type() {
4003        let client = KrakenSpotHttpClient::default();
4004        let instrument_id = cache_test_spot_instrument(&client);
4005
4006        let error = client
4007            .build_add_order_params(
4008                instrument_id,
4009                ClientOrderId::new("spot-trigger-invalid"),
4010                OrderSide::Buy,
4011                OrderType::StopMarket,
4012                Quantity::from("0.01"),
4013                TimeInForce::Gtc,
4014                None,
4015                None,
4016                Some(Price::from("50000")),
4017                Some(TriggerType::MarkPrice),
4018                None,
4019                None,
4020                false,
4021                false,
4022                false,
4023                None,
4024                None,
4025                AccountType::Cash,
4026            )
4027            .unwrap_err();
4028
4029        assert!(
4030            error
4031                .to_string()
4032                .contains("Unsupported trigger type for Kraken Spot")
4033        );
4034    }
4035
4036    fn cache_spot_pair(
4037        client: &KrakenSpotHttpClient,
4038        symbol: &str,
4039        quote: Currency,
4040    ) -> InstrumentId {
4041        let instrument_id = InstrumentId::from(symbol);
4042
4043        client.cache_instrument(InstrumentAny::CurrencyPair(
4044            CurrencyPair::builder()
4045                .instrument_id(instrument_id)
4046                .raw_symbol(Symbol::new(instrument_id.symbol.as_str()))
4047                .base_currency(Currency::BTC())
4048                .quote_currency(quote)
4049                .price_precision(1)
4050                .size_precision(8)
4051                .price_increment(Price::from("0.1"))
4052                .size_increment(Quantity::from("0.00000001"))
4053                .ts_event(0.into())
4054                .ts_init(0.into())
4055                .build()
4056                .unwrap(),
4057        ));
4058
4059        instrument_id
4060    }
4061
4062    /// Bulk position coverage must answer for exactly the instruments the bulk read enumerates.
4063    ///
4064    /// The wallet read only reports pairs quoted in `spot_positions_quote_currency`, so claiming
4065    /// coverage for every instrument would let an absent report force-close a holding the read
4066    /// could never have reported.
4067    #[rstest]
4068    #[case(AccountType::Margin, true, "XBT/USDT.KRAKEN", false)]
4069    #[case(AccountType::Margin, false, "XBT/USDT.KRAKEN", false)]
4070    #[case(AccountType::Cash, false, "XBT/USDT.KRAKEN", false)]
4071    #[case(AccountType::Cash, true, "XBT/USDT.KRAKEN", true)]
4072    #[case(AccountType::Cash, true, "XBT/USD.KRAKEN", false)]
4073    #[case(AccountType::Cash, true, "XBT/EUR.KRAKEN", false)]
4074    fn test_covers_bulk_position_reports(
4075        #[case] account_type: AccountType,
4076        #[case] use_spot_position_reports: bool,
4077        #[case] instrument: &str,
4078        #[case] expected: bool,
4079    ) {
4080        let client = KrakenSpotHttpClient::default();
4081        cache_spot_pair(&client, "XBT/USDT.KRAKEN", Currency::USDT());
4082        cache_spot_pair(&client, "XBT/USD.KRAKEN", Currency::USD());
4083
4084        // `XBT/EUR` is never cached, standing for an instrument the read cannot enumerate.
4085        let covered = client.covers_bulk_position_reports(
4086            InstrumentId::from(instrument),
4087            account_type,
4088            use_spot_position_reports,
4089            Ustr::from("USDT"),
4090        );
4091
4092        assert_eq!(covered, expected);
4093    }
4094
4095    /// A legacy quote code must select the same instruments as its standard spelling.
4096    ///
4097    /// Instruments now carry standard codes, so `ZEUR` has to normalize to `EUR` or an existing
4098    /// setting would stop matching and an absent report could close a holding the read still sees.
4099    #[rstest]
4100    fn test_covers_bulk_position_reports_accepts_legacy_quote_code() {
4101        let client = KrakenSpotHttpClient::default();
4102        let eur = cache_spot_pair(&client, "XBT/EUR.KRAKEN", Currency::EUR());
4103        cache_spot_pair(&client, "XBT/USDT.KRAKEN", Currency::USDT());
4104
4105        let legacy =
4106            client.covers_bulk_position_reports(eur, AccountType::Cash, true, Ustr::from("ZEUR"));
4107        let standard =
4108            client.covers_bulk_position_reports(eur, AccountType::Cash, true, Ustr::from("EUR"));
4109        let other = client.covers_bulk_position_reports(
4110            InstrumentId::from("XBT/USDT.KRAKEN"),
4111            AccountType::Cash,
4112            true,
4113            Ustr::from("ZEUR"),
4114        );
4115
4116        assert!(legacy);
4117        assert!(standard);
4118        assert!(!other);
4119    }
4120
4121    /// A `Balance` row counts toward the covered base it names, in any spelling or suffix, and a
4122    /// dotted base code stays whole when it is itself covered.
4123    #[rstest]
4124    #[case::legacy("XXBT", &["BTC"], Some("BTC"))]
4125    #[case::standard("XBT", &["BTC"], Some("BTC"))]
4126    #[case::suffixed("XBT.F", &["BTC"], Some("BTC"))]
4127    #[case::legacy_suffixed("XXBT.F", &["BTC"], Some("BTC"))]
4128    #[case::margin_suffix("XBT.M", &["BTC"], Some("BTC"))]
4129    #[case::staked("DOT.S", &["DOT"], Some("DOT"))]
4130    #[case::staked_term("DOT28.S", &["DOT"], Some("DOT"))]
4131    #[case::staked_digit_code("ETH2.S", &["ETH"], Some("ETH"))]
4132    #[case::staked_term_atom("ATOM21.S", &["ATOM"], Some("ATOM"))]
4133    #[case::hold("EUR.HOLD", &["EUR"], Some("EUR"))]
4134    #[case::hold_uncovered("EUR.HOLD", &["BTC"], None)]
4135    #[case::bare_digit_code("ETH2", &["ETH"], None)]
4136    #[case::bare_digit_code_luna("LUNA2", &["LUNA"], None)]
4137    #[case::fee_credit("KFEE", &["BTC"], None)]
4138    #[case::uncovered("XXBT", &["ETH"], None)]
4139    #[case::digit_base_suffixed("L3.F", &["L3"], Some("L3"))]
4140    #[case::digit_base_before_stripped("LUNA2.S", &["LUNA2", "LUNA"], Some("LUNA2"))]
4141    #[case::digit_base_stripped("LUNA2.S", &["LUNA"], Some("LUNA"))]
4142    #[case::dotted_base_whole("BRK.Bx", &["BRK.Bx", "BRK"], Some("BRK.Bx"))]
4143    #[case::dotted_base_prefix("BRK.Bx", &["BRK"], Some("BRK"))]
4144    fn test_covered_balance_base(
4145        #[case] key: &str,
4146        #[case] covered: &[&str],
4147        #[case] expected: Option<&str>,
4148    ) {
4149        let covered_bases: HashSet<Ustr> = covered.iter().map(|code| Ustr::from(code)).collect();
4150
4151        assert_eq!(
4152            covered_balance_base(key, &covered_bases),
4153            expected.map(Ustr::from)
4154        );
4155    }
4156
4157    /// An order the venue placed, answered with a transaction ID the model cannot hold, returns the
4158    /// typed error: an untyped one would read as a command never sent and reject a live order.
4159    #[rstest]
4160    #[tokio::test]
4161    async fn test_submit_order_returns_a_typed_error_for_an_invalid_order_id() {
4162        use axum::{Router, http::header, routing::any};
4163
4164        let body = include_str!("../../../test_data/http_add_order_spot.json")
4165            .replace("OUF4EM-FRGI2-MQMWZD", "");
4166        let app = Router::new().route(
4167            "/0/private/AddOrder",
4168            any(move || {
4169                let body = body.clone();
4170                async move { ([(header::CONTENT_TYPE, "application/json")], body) }
4171            }),
4172        );
4173        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4174        let addr = listener.local_addr().unwrap();
4175        tokio::spawn(async move {
4176            axum::serve(listener, app).await.unwrap();
4177        });
4178        let client = KrakenSpotHttpClient::with_credentials(
4179            "test".to_string(),
4180            "c2VjcmV0".to_string(),
4181            KrakenEnvironment::Live,
4182            Some(format!("http://{addr}")),
4183            10,
4184            None,
4185            None,
4186            None,
4187            None,
4188            10,
4189        )
4190        .unwrap();
4191        let instrument_id = cache_test_spot_instrument(&client);
4192
4193        let error = client
4194            .submit_order(
4195                AccountId::from("KRAKEN-001"),
4196                instrument_id,
4197                ClientOrderId::from("O-SUBMIT"),
4198                OrderSide::Buy,
4199                OrderType::Limit,
4200                Quantity::from("0.00100000"),
4201                TimeInForce::Gtc,
4202                None,
4203                Some(Price::from("50000.0")),
4204                None,
4205                None,
4206                None,
4207                None,
4208                false,
4209                false,
4210                false,
4211                None,
4212                None,
4213                AccountType::Cash,
4214            )
4215            .await
4216            .unwrap_err();
4217
4218        assert!(
4219            matches!(
4220                error.downcast_ref::<KrakenSubmitOrderError>(),
4221                Some(KrakenSubmitOrderError::InvalidOrderId { detail })
4222                    if detail.starts_with("Invalid order_id '' in Kraken spot submit response")
4223            ),
4224            "{error:#}"
4225        );
4226    }
4227
4228    /// A spot command that can change venue state, with the endpoint it writes to.
4229    #[derive(Clone, Copy, Debug)]
4230    enum StateChangingSpotCommand {
4231        CancelOrder,
4232        CancelAll,
4233        EditOrder,
4234    }
4235
4236    impl StateChangingSpotCommand {
4237        fn endpoint(self) -> &'static str {
4238            match self {
4239                Self::CancelOrder => "/0/private/CancelOrder",
4240                Self::CancelAll => "/0/private/CancelAll",
4241                Self::EditOrder => "/0/private/EditOrder",
4242            }
4243        }
4244
4245        async fn send(
4246            self,
4247            client: &KrakenSpotRawHttpClient,
4248        ) -> anyhow::Result<(), KrakenHttpError> {
4249            match self {
4250                Self::CancelOrder => {
4251                    let params = KrakenSpotCancelOrderParamsBuilder::default()
4252                        .txid("V-001".to_string())
4253                        .build()
4254                        .expect("cancel params should build");
4255                    client.cancel_order(&params).await.map(|_| ())
4256                }
4257                Self::CancelAll => client.cancel_all_orders().await.map(|_| ()),
4258                Self::EditOrder => {
4259                    let params = KrakenSpotEditOrderParamsBuilder::default()
4260                        .pair(Ustr::from("XXBTZUSD"))
4261                        .txid("V-001".to_string())
4262                        .volume("0.00100000".to_string())
4263                        .build()
4264                        .expect("edit params should build");
4265                    client.edit_order(&params).await.map(|_| ())
4266                }
4267            }
4268        }
4269    }
4270
4271    /// A retryable transport failure as the mock venue presents it.
4272    #[derive(Clone, Copy, Debug)]
4273    enum RetryableTransportFailure {
4274        /// Accepted connections are dropped before any response, failing at the transport layer.
4275        DroppedConnection,
4276        /// HTTP 429, which the client classifies as a retryable network error.
4277        Http429,
4278        /// HTTP 500, which the client classifies as a retryable network error.
4279        Http500,
4280        /// HTTP 200 carrying a rate-limit error array, Kraken's other retryable class.
4281        ApiRateLimit,
4282    }
4283
4284    /// Serves `endpoint` with the given failure and counts the requests that reach it.
4285    async fn spawn_failing_spot_mock(
4286        endpoint: &'static str,
4287        failure: RetryableTransportFailure,
4288    ) -> (String, Arc<AtomicUsize>) {
4289        use axum::{Router, http::StatusCode, routing::post};
4290
4291        let request_count = Arc::new(AtomicUsize::new(0));
4292        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4293        let addr = listener.local_addr().unwrap();
4294
4295        match failure {
4296            RetryableTransportFailure::DroppedConnection => {
4297                let handler_count = request_count.clone();
4298
4299                tokio::spawn(async move {
4300                    loop {
4301                        match listener.accept().await {
4302                            Ok((socket, _)) => {
4303                                handler_count.fetch_add(1, Ordering::Relaxed);
4304                                drop(socket);
4305                            }
4306                            Err(_) => return,
4307                        }
4308                    }
4309                });
4310            }
4311            RetryableTransportFailure::ApiRateLimit => {
4312                let handler_count = request_count.clone();
4313                let router = Router::new().route(
4314                    endpoint,
4315                    post(move || {
4316                        let handler_count = handler_count.clone();
4317
4318                        async move {
4319                            use axum::response::IntoResponse;
4320
4321                            handler_count.fetch_add(1, Ordering::Relaxed);
4322
4323                            (
4324                                [(axum::http::header::CONTENT_TYPE, "application/json")],
4325                                r#"{"error":["EAPI:Rate limit exceeded"],"result":null}"#,
4326                            )
4327                                .into_response()
4328                        }
4329                    }),
4330                );
4331
4332                tokio::spawn(async move {
4333                    axum::serve(listener, router).await.unwrap();
4334                });
4335            }
4336            RetryableTransportFailure::Http429 | RetryableTransportFailure::Http500 => {
4337                let status = match failure {
4338                    RetryableTransportFailure::Http429 => StatusCode::TOO_MANY_REQUESTS,
4339                    RetryableTransportFailure::Http500 => StatusCode::INTERNAL_SERVER_ERROR,
4340                    RetryableTransportFailure::DroppedConnection
4341                    | RetryableTransportFailure::ApiRateLimit => unreachable!(),
4342                };
4343
4344                let handler_count = request_count.clone();
4345                let router = Router::new().route(
4346                    endpoint,
4347                    post(move || {
4348                        let handler_count = handler_count.clone();
4349                        async move {
4350                            handler_count.fetch_add(1, Ordering::Relaxed);
4351                            status
4352                        }
4353                    }),
4354                );
4355
4356                tokio::spawn(async move {
4357                    axum::serve(listener, router).await.unwrap();
4358                });
4359            }
4360        }
4361
4362        (format!("http://{addr}"), request_count)
4363    }
4364
4365    /// Builds a client with retries enabled (three retries, millisecond backoff) so send-once
4366    /// behavior comes from the command's transport, not from the retry configuration.
4367    fn retry_enabled_spot_client(base_url: String) -> KrakenSpotRawHttpClient {
4368        KrakenSpotRawHttpClient::with_credentials(
4369            "test".to_string(),
4370            "c2VjcmV0".to_string(),
4371            KrakenEnvironment::Live,
4372            Some(base_url),
4373            10,
4374            Some(3),
4375            Some(1),
4376            Some(2),
4377            None,
4378            100,
4379        )
4380        .unwrap()
4381    }
4382
4383    /// A spot command that can change venue state reaches the venue exactly once on a retryable
4384    /// failure: a retransmitted cancel or edit may act on venue state twice.
4385    #[rstest]
4386    #[case::cancel_order_dropped_connection(
4387        StateChangingSpotCommand::CancelOrder,
4388        RetryableTransportFailure::DroppedConnection
4389    )]
4390    #[case::cancel_order_http_429(
4391        StateChangingSpotCommand::CancelOrder,
4392        RetryableTransportFailure::Http429
4393    )]
4394    #[case::cancel_order_http_500(
4395        StateChangingSpotCommand::CancelOrder,
4396        RetryableTransportFailure::Http500
4397    )]
4398    #[case::cancel_order_api_rate_limit(
4399        StateChangingSpotCommand::CancelOrder,
4400        RetryableTransportFailure::ApiRateLimit
4401    )]
4402    #[case::cancel_all_dropped_connection(
4403        StateChangingSpotCommand::CancelAll,
4404        RetryableTransportFailure::DroppedConnection
4405    )]
4406    #[case::cancel_all_http_429(
4407        StateChangingSpotCommand::CancelAll,
4408        RetryableTransportFailure::Http429
4409    )]
4410    #[case::cancel_all_http_500(
4411        StateChangingSpotCommand::CancelAll,
4412        RetryableTransportFailure::Http500
4413    )]
4414    #[case::cancel_all_api_rate_limit(
4415        StateChangingSpotCommand::CancelAll,
4416        RetryableTransportFailure::ApiRateLimit
4417    )]
4418    #[case::edit_order_dropped_connection(
4419        StateChangingSpotCommand::EditOrder,
4420        RetryableTransportFailure::DroppedConnection
4421    )]
4422    #[case::edit_order_http_429(
4423        StateChangingSpotCommand::EditOrder,
4424        RetryableTransportFailure::Http429
4425    )]
4426    #[case::edit_order_http_500(
4427        StateChangingSpotCommand::EditOrder,
4428        RetryableTransportFailure::Http500
4429    )]
4430    #[case::edit_order_api_rate_limit(
4431        StateChangingSpotCommand::EditOrder,
4432        RetryableTransportFailure::ApiRateLimit
4433    )]
4434    #[tokio::test]
4435    async fn test_state_changing_spot_command_sends_once_on_retryable_failure(
4436        #[case] command: StateChangingSpotCommand,
4437        #[case] failure: RetryableTransportFailure,
4438    ) {
4439        let (base_url, request_count) = spawn_failing_spot_mock(command.endpoint(), failure).await;
4440        let client = retry_enabled_spot_client(base_url);
4441
4442        let result = command.send(&client).await;
4443
4444        // The failing attempt must be retryable-class, so the single request count below
4445        // proves the command's transport is send-once rather than the failure being final.
4446        assert!(
4447            result.as_ref().is_err_and(kraken_http_should_retry),
4448            "{command:?} on {failure:?} must fail retryably, received {result:?}"
4449        );
4450        assert_eq!(
4451            request_count.load(Ordering::Relaxed),
4452            1,
4453            "{command:?} on {failure:?} must reach the venue exactly once"
4454        );
4455    }
4456
4457    /// Reads keep the retrying transport: a transient HTTP 500 is retried and then succeeds.
4458    #[tokio::test]
4459    async fn test_spot_read_request_still_retries_transient_failure() {
4460        use axum::{
4461            Router,
4462            http::{StatusCode, header},
4463            routing::any,
4464        };
4465
4466        let request_count = Arc::new(AtomicUsize::new(0));
4467        let handler_count = request_count.clone();
4468        let body = include_str!("../../../test_data/http_server_time.json").to_string();
4469
4470        let router = Router::new().route(
4471            "/0/public/Time",
4472            any(move || {
4473                let handler_count = handler_count.clone();
4474                let body = body.clone();
4475                async move {
4476                    use axum::response::IntoResponse;
4477
4478                    if handler_count.fetch_add(1, Ordering::Relaxed) == 0 {
4479                        StatusCode::INTERNAL_SERVER_ERROR.into_response()
4480                    } else {
4481                        ([(header::CONTENT_TYPE, "application/json")], body).into_response()
4482                    }
4483                }
4484            }),
4485        );
4486
4487        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4488        let addr = listener.local_addr().unwrap();
4489        tokio::spawn(async move {
4490            axum::serve(listener, router).await.unwrap();
4491        });
4492
4493        let client = retry_enabled_spot_client(format!("http://{addr}"));
4494
4495        let server_time = client.get_server_time().await.unwrap();
4496
4497        assert_eq!(request_count.load(Ordering::Relaxed), 2);
4498        assert_eq!(server_time.unixtime, 1_762_820_224);
4499        assert_eq!(server_time.rfc1123, "Tue, 11 Nov 25 00:17:04 +0000");
4500    }
4501
4502    fn cache_test_spot_instrument(client: &KrakenSpotHttpClient) -> InstrumentId {
4503        let instrument_id = InstrumentId::from("XBT/USD.KRAKEN");
4504
4505        client.cache_instrument(InstrumentAny::CurrencyPair(
4506            CurrencyPair::builder()
4507                .instrument_id(instrument_id)
4508                .raw_symbol(Symbol::new("XBTUSD"))
4509                .base_currency(Currency::BTC())
4510                .quote_currency(Currency::USD())
4511                .price_precision(1)
4512                .size_precision(8)
4513                .price_increment(Price::from("0.1"))
4514                .size_increment(Quantity::from("0.00000001"))
4515                .ts_event(0.into())
4516                .ts_init(0.into())
4517                .build()
4518                .unwrap(),
4519        ));
4520
4521        instrument_id
4522    }
4523
4524    fn cache_test_spot_instrument_with_leverage(
4525        client: &KrakenSpotHttpClient,
4526        leverage_buy: &[i32],
4527        leverage_sell: &[i32],
4528    ) -> InstrumentId {
4529        let instrument_id = cache_test_spot_instrument(client);
4530        let raw_symbol = Ustr::from("XBTUSD");
4531        client.leverage_tiers_cache.rcu(|m| {
4532            m.insert(raw_symbol, (leverage_buy.to_vec(), leverage_sell.to_vec()));
4533        });
4534        instrument_id
4535    }
4536
4537    #[rstest]
4538    fn test_build_add_order_params_leverage_serialized_as_ratio() {
4539        let client = KrakenSpotHttpClient::default();
4540        let instrument_id =
4541            cache_test_spot_instrument_with_leverage(&client, &[2, 3, 5], &[2, 3, 5]);
4542
4543        let params = client
4544            .build_add_order_params(
4545                instrument_id,
4546                ClientOrderId::new("spot-margin-buy"),
4547                OrderSide::Buy,
4548                OrderType::Limit,
4549                Quantity::from("0.01"),
4550                TimeInForce::Gtc,
4551                None,
4552                Some(Price::from("50000")),
4553                None,
4554                None,
4555                None,
4556                None,
4557                false,
4558                false,
4559                false,
4560                None,
4561                Some(3),
4562                AccountType::Margin,
4563            )
4564            .unwrap();
4565
4566        assert_eq!(params.leverage, Some("3:1".to_string()));
4567    }
4568
4569    #[rstest]
4570    fn test_build_add_order_params_invalid_leverage_rejected() {
4571        let client = KrakenSpotHttpClient::default();
4572        let instrument_id =
4573            cache_test_spot_instrument_with_leverage(&client, &[2, 3, 5], &[2, 3, 5]);
4574
4575        let err = client
4576            .build_add_order_params(
4577                instrument_id,
4578                ClientOrderId::new("spot-margin-bad"),
4579                OrderSide::Buy,
4580                OrderType::Limit,
4581                Quantity::from("0.01"),
4582                TimeInForce::Gtc,
4583                None,
4584                Some(Price::from("50000")),
4585                None,
4586                None,
4587                None,
4588                None,
4589                false,
4590                false,
4591                false,
4592                None,
4593                Some(7),
4594                AccountType::Margin,
4595            )
4596            .unwrap_err();
4597
4598        assert!(
4599            err.to_string().contains("not supported"),
4600            "Expected tier-validation error: {err}"
4601        );
4602    }
4603
4604    #[rstest]
4605    fn test_build_add_order_params_no_leverage_is_cash() {
4606        let client = KrakenSpotHttpClient::default();
4607        let instrument_id =
4608            cache_test_spot_instrument_with_leverage(&client, &[2, 3, 5], &[2, 3, 5]);
4609
4610        let params = client
4611            .build_add_order_params(
4612                instrument_id,
4613                ClientOrderId::new("spot-cash"),
4614                OrderSide::Buy,
4615                OrderType::Limit,
4616                Quantity::from("0.01"),
4617                TimeInForce::Gtc,
4618                None,
4619                Some(Price::from("50000")),
4620                None,
4621                None,
4622                None,
4623                None,
4624                false,
4625                false,
4626                false,
4627                None,
4628                None,
4629                AccountType::Cash,
4630            )
4631            .unwrap();
4632
4633        assert_eq!(
4634            params.leverage, None,
4635            "Cash order should not have leverage field"
4636        );
4637    }
4638
4639    #[rstest]
4640    fn test_build_add_order_params_rejects_per_order_leverage_in_cash_mode() {
4641        let client = KrakenSpotHttpClient::default();
4642        let instrument_id = cache_test_spot_instrument(&client);
4643
4644        let err = client
4645            .build_add_order_params(
4646                instrument_id,
4647                ClientOrderId::new("cash-with-leverage"),
4648                OrderSide::Buy,
4649                OrderType::Limit,
4650                Quantity::from("0.01"),
4651                TimeInForce::Gtc,
4652                None,
4653                Some(Price::from("50000")),
4654                None,
4655                None,
4656                None,
4657                None,
4658                false,
4659                false,
4660                false,
4661                None,
4662                Some(3),
4663                AccountType::Cash,
4664            )
4665            .unwrap_err();
4666
4667        assert!(
4668            err.to_string().contains("Margin"),
4669            "Expected Margin mode rejection: {err}"
4670        );
4671    }
4672
4673    #[rstest]
4674    fn test_build_add_order_params_reduce_only_forwarded_in_margin_mode() {
4675        let client = KrakenSpotHttpClient::default();
4676        let instrument_id = cache_test_spot_instrument(&client);
4677
4678        let params = client
4679            .build_add_order_params(
4680                instrument_id,
4681                ClientOrderId::new("margin-reduce-only"),
4682                OrderSide::Sell,
4683                OrderType::Limit,
4684                Quantity::from("0.01"),
4685                TimeInForce::Gtc,
4686                None,
4687                Some(Price::from("50000")),
4688                None,
4689                None,
4690                None,
4691                None,
4692                true,
4693                false,
4694                false,
4695                None,
4696                None,
4697                AccountType::Margin,
4698            )
4699            .unwrap();
4700
4701        assert_eq!(params.reduce_only, Some(true));
4702    }
4703
4704    #[rstest]
4705    fn test_build_add_order_params_rejects_reduce_only_in_cash_mode() {
4706        let client = KrakenSpotHttpClient::default();
4707        let instrument_id = cache_test_spot_instrument(&client);
4708
4709        let err = client
4710            .build_add_order_params(
4711                instrument_id,
4712                ClientOrderId::new("cash-reduce-only"),
4713                OrderSide::Sell,
4714                OrderType::Limit,
4715                Quantity::from("0.01"),
4716                TimeInForce::Gtc,
4717                None,
4718                Some(Price::from("50000")),
4719                None,
4720                None,
4721                None,
4722                None,
4723                true,
4724                false,
4725                false,
4726                None,
4727                None,
4728                AccountType::Cash,
4729            )
4730            .unwrap_err();
4731
4732        assert!(
4733            err.to_string().contains("reduce_only requires"),
4734            "expected reduce_only Margin rejection: {err}"
4735        );
4736    }
4737
4738    #[rstest]
4739    fn test_build_add_order_params_rejects_leverage_when_tiers_not_loaded() {
4740        let client = KrakenSpotHttpClient::default();
4741        let instrument_id = cache_test_spot_instrument(&client);
4742
4743        let err = client
4744            .build_add_order_params(
4745                instrument_id,
4746                ClientOrderId::new("missing-tiers"),
4747                OrderSide::Buy,
4748                OrderType::Limit,
4749                Quantity::from("0.01"),
4750                TimeInForce::Gtc,
4751                None,
4752                Some(Price::from("50000")),
4753                None,
4754                None,
4755                None,
4756                None,
4757                false,
4758                false,
4759                false,
4760                None,
4761                Some(3),
4762                AccountType::Margin,
4763            )
4764            .unwrap_err();
4765
4766        assert!(
4767            err.to_string().contains("Leverage tiers not loaded"),
4768            "expected cache-miss rejection: {err}"
4769        );
4770    }
4771
4772    #[rstest]
4773    #[case::venue_id(None, Some(VenueOrderId::from("V-ORDER-001")))]
4774    #[case::client_id(Some(ClientOrderId::new("C-ORDER-001")), None)]
4775    #[tokio::test]
4776    async fn test_modify_order_returns_supplied_venue_id(
4777        #[case] client_order_id: Option<ClientOrderId>,
4778        #[case] venue_order_id: Option<VenueOrderId>,
4779    ) {
4780        let app = Router::new().route(
4781            "/0/private/AmendOrder",
4782            post(|| async {
4783                (
4784                    [(header::CONTENT_TYPE, "application/json")],
4785                    include_str!("../../../test_data/http_amend_order_spot.json"),
4786                )
4787            }),
4788        );
4789
4790        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4791        let addr = listener.local_addr().unwrap();
4792        tokio::spawn(async move {
4793            axum::serve(listener, app).await.unwrap();
4794        });
4795
4796        let client = KrakenSpotHttpClient::with_credentials(
4797            "test".to_string(),
4798            "c2VjcmV0".to_string(),
4799            KrakenEnvironment::Live,
4800            Some(format!("http://{addr}")),
4801            10,
4802            None,
4803            None,
4804            None,
4805            None,
4806            10,
4807        )
4808        .unwrap();
4809        let instrument_id = cache_test_spot_instrument(&client);
4810
4811        let result = client
4812            .modify_order(
4813                instrument_id,
4814                client_order_id,
4815                venue_order_id,
4816                Some(Quantity::from("0.02")),
4817                Some(Price::from("51000.0")),
4818                None,
4819            )
4820            .await
4821            .unwrap();
4822
4823        assert_eq!(result, venue_order_id);
4824    }
4825
4826    #[rstest]
4827    #[tokio::test]
4828    async fn test_modify_order_without_ids_fails() {
4829        let client = KrakenSpotHttpClient::default();
4830        let instrument_id = cache_test_spot_instrument(&client);
4831
4832        let err = client
4833            .modify_order(
4834                instrument_id,
4835                None,
4836                None,
4837                Some(Quantity::from("0.02")),
4838                Some(Price::from("51000.0")),
4839                None,
4840            )
4841            .await
4842            .unwrap_err();
4843
4844        assert!(
4845            err.to_string()
4846                .contains("Either client_order_id or venue_order_id must be provided"),
4847            "expected missing ID rejection: {err}"
4848        );
4849    }
4850}