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,
20    fmt::Debug,
21    num::NonZeroU32,
22    sync::{
23        Arc, RwLock,
24        atomic::{AtomicBool, Ordering},
25    },
26};
27
28use chrono::{DateTime, Utc};
29use dashmap::DashMap;
30use indexmap::IndexMap;
31use nautilus_core::{
32    AtomicTime, UUID4, consts::NAUTILUS_USER_AGENT, datetime::NANOSECONDS_IN_SECOND,
33    nanos::UnixNanos, time::get_atomic_clock_realtime,
34};
35use nautilus_model::{
36    data::{Bar, BarType, TradeTick},
37    enums::{AccountType, CurrencyType, OrderSide, OrderType, PositionSideSpecified, TimeInForce},
38    events::AccountState,
39    identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
40    instruments::{Instrument, InstrumentAny},
41    reports::{FillReport, OrderStatusReport, PositionStatusReport},
42    types::{AccountBalance, Currency, Money, Price, Quantity},
43};
44use nautilus_network::{
45    http::{HttpClient, Method, USER_AGENT},
46    ratelimiter::quota::Quota,
47    retry::{RetryConfig, RetryManager},
48};
49use serde::de::DeserializeOwned;
50use tokio_util::sync::CancellationToken;
51use ustr::Ustr;
52
53use super::{models::*, query::*};
54use crate::{
55    common::{
56        consts::NAUTILUS_KRAKEN_BROKER_ID,
57        credential::KrakenCredential,
58        enums::{KrakenEnvironment, KrakenOrderSide, KrakenOrderType, KrakenProductType},
59        parse::{
60            bar_type_to_spot_interval, normalize_currency_code, parse_bar, parse_fill_report,
61            parse_order_status_report, parse_spot_instrument, parse_trade_tick_from_array,
62        },
63        urls::get_kraken_http_base_url,
64    },
65    http::error::KrakenHttpError,
66};
67
68/// Default Kraken Spot REST API rate limit (requests per second).
69pub const KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND: u32 = 5;
70
71const KRAKEN_GLOBAL_RATE_KEY: &str = "kraken:spot:global";
72
73/// Maximum orders per batch cancel request for Kraken Spot API.
74const BATCH_CANCEL_LIMIT: usize = 50;
75
76/// Computes the time-in-force and expiration time parameters for Kraken Spot orders.
77///
78/// Returns a tuple of (timeinforce, expiretm) for use in order requests.
79/// For limit orders, handles GTC, IOC, and GTD. Market orders return (None, None).
80fn compute_time_in_force(
81    is_limit_order: bool,
82    time_in_force: TimeInForce,
83    expire_time: Option<UnixNanos>,
84) -> anyhow::Result<(Option<String>, Option<String>)> {
85    if is_limit_order {
86        match time_in_force {
87            TimeInForce::Gtc => Ok((None, None)), // Default, no parameter needed
88            TimeInForce::Ioc => Ok((Some("IOC".to_string()), None)),
89            TimeInForce::Fok => {
90                anyhow::bail!("FOK time in force not supported by Kraken Spot API")
91            }
92            TimeInForce::Gtd => {
93                let expire = expire_time.ok_or_else(|| {
94                    anyhow::anyhow!("GTD time in force requires expire_time parameter")
95                })?;
96                // Convert nanoseconds to seconds for Kraken API
97                let expire_secs = expire.as_u64() / NANOSECONDS_IN_SECOND;
98                Ok((Some("GTD".to_string()), Some(expire_secs.to_string())))
99            }
100            _ => anyhow::bail!("Unsupported time in force: {time_in_force:?}"),
101        }
102    } else {
103        // Market orders are inherently immediate, timeinforce not applicable
104        Ok((None, None))
105    }
106}
107
108/// Raw HTTP client for low-level Kraken Spot API operations.
109///
110/// This client handles request/response operations with the Kraken Spot API,
111/// returning venue-specific response types. It does not parse to Nautilus domain types.
112pub struct KrakenSpotRawHttpClient {
113    base_url: String,
114    client: HttpClient,
115    credential: Option<KrakenCredential>,
116    retry_manager: RetryManager<KrakenHttpError>,
117    cancellation_token: CancellationToken,
118    clock: &'static AtomicTime,
119    /// Mutex to serialize authenticated requests, ensuring nonces arrive at Kraken in order
120    auth_mutex: tokio::sync::Mutex<()>,
121}
122
123impl Default for KrakenSpotRawHttpClient {
124    fn default() -> Self {
125        Self::new(
126            KrakenEnvironment::Mainnet,
127            None,
128            Some(60),
129            None,
130            None,
131            None,
132            None,
133            None,
134        )
135        .expect("Failed to create default KrakenSpotRawHttpClient")
136    }
137}
138
139impl Debug for KrakenSpotRawHttpClient {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        f.debug_struct(stringify!(KrakenSpotRawHttpClient))
142            .field("base_url", &self.base_url)
143            .field("has_credentials", &self.credential.is_some())
144            .finish()
145    }
146}
147
148impl KrakenSpotRawHttpClient {
149    /// Creates a new [`KrakenSpotRawHttpClient`].
150    #[allow(clippy::too_many_arguments)]
151    pub fn new(
152        environment: KrakenEnvironment,
153        base_url_override: Option<String>,
154        timeout_secs: Option<u64>,
155        max_retries: Option<u32>,
156        retry_delay_ms: Option<u64>,
157        retry_delay_max_ms: Option<u64>,
158        proxy_url: Option<String>,
159        max_requests_per_second: Option<u32>,
160    ) -> anyhow::Result<Self> {
161        let retry_config = RetryConfig {
162            max_retries: max_retries.unwrap_or(3),
163            initial_delay_ms: retry_delay_ms.unwrap_or(1000),
164            max_delay_ms: retry_delay_max_ms.unwrap_or(10_000),
165            backoff_factor: 2.0,
166            jitter_ms: 1000,
167            operation_timeout_ms: Some(60_000),
168            immediate_first: false,
169            max_elapsed_ms: Some(180_000),
170        };
171
172        let retry_manager = RetryManager::new(retry_config);
173        let base_url = base_url_override.unwrap_or_else(|| {
174            get_kraken_http_base_url(KrakenProductType::Spot, environment).to_string()
175        });
176
177        let rate_limit =
178            max_requests_per_second.unwrap_or(KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND);
179
180        Ok(Self {
181            base_url,
182            client: HttpClient::new(
183                Self::default_headers(),
184                vec![],
185                Self::rate_limiter_quotas(rate_limit),
186                Some(Self::default_quota(rate_limit)),
187                timeout_secs,
188                proxy_url,
189            )
190            .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?,
191            credential: None,
192            retry_manager,
193            cancellation_token: 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    #[allow(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: Option<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: Option<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        let rate_limit =
230            max_requests_per_second.unwrap_or(KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND);
231
232        Ok(Self {
233            base_url,
234            client: HttpClient::new(
235                Self::default_headers(),
236                vec![],
237                Self::rate_limiter_quotas(rate_limit),
238                Some(Self::default_quota(rate_limit)),
239                timeout_secs,
240                proxy_url,
241            )
242            .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?,
243            credential: Some(KrakenCredential::new(api_key, api_secret)),
244            retry_manager,
245            cancellation_token: CancellationToken::new(),
246            clock: get_atomic_clock_realtime(),
247            auth_mutex: tokio::sync::Mutex::new(()),
248        })
249    }
250
251    /// Generates a unique nonce for Kraken Spot API requests.
252    ///
253    /// Uses `AtomicTime` for strict monotonicity. The nanosecond timestamp
254    /// guarantees uniqueness even for rapid consecutive calls.
255    fn generate_nonce(&self) -> u64 {
256        self.clock.get_time_ns().as_u64()
257    }
258
259    /// Returns the base URL for this client.
260    pub fn base_url(&self) -> &str {
261        &self.base_url
262    }
263
264    /// Returns the credential for this client, if set.
265    pub fn credential(&self) -> Option<&KrakenCredential> {
266        self.credential.as_ref()
267    }
268
269    /// Cancels all pending HTTP requests.
270    pub fn cancel_all_requests(&self) {
271        self.cancellation_token.cancel();
272    }
273
274    /// Returns the cancellation token for this client.
275    pub fn cancellation_token(&self) -> &CancellationToken {
276        &self.cancellation_token
277    }
278
279    fn default_headers() -> HashMap<String, String> {
280        HashMap::from([(USER_AGENT.to_string(), NAUTILUS_USER_AGENT.to_string())])
281    }
282
283    fn default_quota(max_requests_per_second: u32) -> Quota {
284        Quota::per_second(
285            NonZeroU32::new(max_requests_per_second).unwrap_or_else(|| {
286                NonZeroU32::new(KRAKEN_SPOT_DEFAULT_RATE_LIMIT_PER_SECOND).unwrap()
287            }),
288        )
289    }
290
291    fn rate_limiter_quotas(max_requests_per_second: u32) -> Vec<(String, Quota)> {
292        vec![(
293            KRAKEN_GLOBAL_RATE_KEY.to_string(),
294            Self::default_quota(max_requests_per_second),
295        )]
296    }
297
298    fn rate_limit_keys(endpoint: &str) -> Vec<String> {
299        let normalized = endpoint.split('?').next().unwrap_or(endpoint);
300        let route = format!("kraken:spot:{normalized}");
301        vec![KRAKEN_GLOBAL_RATE_KEY.to_string(), route]
302    }
303
304    fn sign_spot(
305        &self,
306        path: &str,
307        nonce: u64,
308        params: &HashMap<String, String>,
309    ) -> anyhow::Result<(HashMap<String, String>, String)> {
310        let credential = self
311            .credential
312            .as_ref()
313            .ok_or_else(|| anyhow::anyhow!("Missing credentials"))?;
314
315        let (signature, post_data) = credential.sign_spot(path, nonce, params)?;
316
317        let mut headers = HashMap::new();
318        headers.insert("API-Key".to_string(), credential.api_key().to_string());
319        headers.insert("API-Sign".to_string(), signature);
320
321        Ok((headers, post_data))
322    }
323
324    async fn send_request<T: DeserializeOwned>(
325        &self,
326        method: Method,
327        endpoint: &str,
328        body: Option<Vec<u8>>,
329        authenticate: bool,
330    ) -> anyhow::Result<KrakenResponse<T>, KrakenHttpError> {
331        // Serialize authenticated requests to ensure nonces arrive at Kraken in order.
332        // Without this, concurrent requests can race through the network and arrive
333        // out-of-order, causing "Invalid nonce" errors.
334        let _guard = if authenticate {
335            Some(self.auth_mutex.lock().await)
336        } else {
337            None
338        };
339
340        let endpoint = endpoint.to_string();
341        let url = format!("{}{endpoint}", self.base_url);
342        let method_clone = method.clone();
343        let body_clone = body.clone();
344
345        let operation = || {
346            let url = url.clone();
347            let method = method_clone.clone();
348            let body = body_clone.clone();
349            let endpoint = endpoint.clone();
350
351            async move {
352                let mut headers = Self::default_headers();
353
354                let final_body = if authenticate {
355                    let nonce = self.generate_nonce();
356                    tracing::debug!("Generated nonce {nonce} for {endpoint}");
357
358                    let params: HashMap<String, String> = if let Some(ref body_bytes) = body {
359                        let body_str = std::str::from_utf8(body_bytes).map_err(|e| {
360                            KrakenHttpError::ParseError(format!(
361                                "Invalid UTF-8 in request body: {e}"
362                            ))
363                        })?;
364                        serde_urlencoded::from_str(body_str).map_err(|e| {
365                            KrakenHttpError::ParseError(format!(
366                                "Failed to parse request params: {e}"
367                            ))
368                        })?
369                    } else {
370                        HashMap::new()
371                    };
372
373                    let (auth_headers, post_data) = self
374                        .sign_spot(&endpoint, nonce, &params)
375                        .map_err(|e| KrakenHttpError::NetworkError(e.to_string()))?;
376                    headers.extend(auth_headers);
377                    Some(post_data.into_bytes())
378                } else {
379                    body
380                };
381
382                if method == Method::POST {
383                    headers.insert(
384                        "Content-Type".to_string(),
385                        "application/x-www-form-urlencoded".to_string(),
386                    );
387                }
388
389                let rate_limit_keys = Self::rate_limit_keys(&endpoint);
390
391                let response = self
392                    .client
393                    .request(
394                        method,
395                        url,
396                        None,
397                        Some(headers),
398                        final_body,
399                        None,
400                        Some(rate_limit_keys),
401                    )
402                    .await
403                    .map_err(|e| KrakenHttpError::NetworkError(e.to_string()))?;
404
405                let status = response.status.as_u16();
406                if status >= 400 {
407                    let body = String::from_utf8_lossy(&response.body).to_string();
408                    // Don't retry authentication errors
409                    if status == 401 || status == 403 {
410                        return Err(KrakenHttpError::AuthenticationError(format!(
411                            "HTTP error {status}: {body}"
412                        )));
413                    }
414                    return Err(KrakenHttpError::NetworkError(format!(
415                        "HTTP error {status}: {body}"
416                    )));
417                }
418
419                let response_text = String::from_utf8(response.body.to_vec()).map_err(|e| {
420                    KrakenHttpError::ParseError(format!("Failed to parse response as UTF-8: {e}"))
421                })?;
422
423                let kraken_response: KrakenResponse<T> = serde_json::from_str(&response_text)
424                    .map_err(|e| {
425                        KrakenHttpError::ParseError(format!("Failed to deserialize response: {e}"))
426                    })?;
427
428                if !kraken_response.error.is_empty() {
429                    return Err(KrakenHttpError::ApiError(kraken_response.error.clone()));
430                }
431
432                Ok(kraken_response)
433            }
434        };
435
436        let should_retry =
437            |error: &KrakenHttpError| -> bool { matches!(error, KrakenHttpError::NetworkError(_)) };
438        let create_error = |msg: String| -> KrakenHttpError { KrakenHttpError::NetworkError(msg) };
439
440        self.retry_manager
441            .execute_with_retry_with_cancel(
442                &endpoint,
443                operation,
444                should_retry,
445                create_error,
446                &self.cancellation_token,
447            )
448            .await
449    }
450
451    /// Requests the server time from Kraken.
452    pub async fn get_server_time(&self) -> anyhow::Result<ServerTime, KrakenHttpError> {
453        let response: KrakenResponse<ServerTime> = self
454            .send_request(Method::GET, "/0/public/Time", None, false)
455            .await?;
456
457        response.result.ok_or_else(|| {
458            KrakenHttpError::ParseError("Missing result in server time response".to_string())
459        })
460    }
461
462    /// Requests the system status from Kraken.
463    pub async fn get_system_status(&self) -> anyhow::Result<SystemStatus, KrakenHttpError> {
464        let response: KrakenResponse<SystemStatus> = self
465            .send_request(Method::GET, "/0/public/SystemStatus", None, false)
466            .await?;
467
468        response.result.ok_or_else(|| {
469            KrakenHttpError::ParseError("Missing result in system status response".to_string())
470        })
471    }
472
473    /// Requests tradable asset pairs from Kraken.
474    pub async fn get_asset_pairs(
475        &self,
476        pairs: Option<Vec<String>>,
477    ) -> anyhow::Result<AssetPairsResponse, KrakenHttpError> {
478        let endpoint = if let Some(pairs) = pairs {
479            format!("/0/public/AssetPairs?pair={}", pairs.join(","))
480        } else {
481            "/0/public/AssetPairs".to_string()
482        };
483
484        let response: KrakenResponse<AssetPairsResponse> = self
485            .send_request(Method::GET, &endpoint, None, false)
486            .await?;
487
488        response.result.ok_or_else(|| {
489            KrakenHttpError::ParseError("Missing result in asset pairs response".to_string())
490        })
491    }
492
493    /// Requests ticker information for asset pairs.
494    pub async fn get_ticker(
495        &self,
496        pairs: Vec<String>,
497    ) -> anyhow::Result<TickerResponse, KrakenHttpError> {
498        let endpoint = format!("/0/public/Ticker?pair={}", pairs.join(","));
499
500        let response: KrakenResponse<TickerResponse> = self
501            .send_request(Method::GET, &endpoint, None, false)
502            .await?;
503
504        response.result.ok_or_else(|| {
505            KrakenHttpError::ParseError("Missing result in ticker response".to_string())
506        })
507    }
508
509    /// Requests OHLC candlestick data for an asset pair.
510    pub async fn get_ohlc(
511        &self,
512        pair: &str,
513        interval: Option<u32>,
514        since: Option<i64>,
515    ) -> anyhow::Result<OhlcResponse, KrakenHttpError> {
516        let mut endpoint = format!("/0/public/OHLC?pair={pair}");
517
518        if let Some(interval) = interval {
519            endpoint.push_str(&format!("&interval={interval}"));
520        }
521        if let Some(since) = since {
522            endpoint.push_str(&format!("&since={since}"));
523        }
524
525        let response: KrakenResponse<OhlcResponse> = self
526            .send_request(Method::GET, &endpoint, None, false)
527            .await?;
528
529        response.result.ok_or_else(|| {
530            KrakenHttpError::ParseError("Missing result in OHLC response".to_string())
531        })
532    }
533
534    /// Requests order book depth for an asset pair.
535    pub async fn get_book_depth(
536        &self,
537        pair: &str,
538        count: Option<u32>,
539    ) -> anyhow::Result<OrderBookResponse, KrakenHttpError> {
540        let mut endpoint = format!("/0/public/Depth?pair={pair}");
541
542        if let Some(count) = count {
543            endpoint.push_str(&format!("&count={count}"));
544        }
545
546        let response: KrakenResponse<OrderBookResponse> = self
547            .send_request(Method::GET, &endpoint, None, false)
548            .await?;
549
550        response.result.ok_or_else(|| {
551            KrakenHttpError::ParseError("Missing result in book depth response".to_string())
552        })
553    }
554
555    /// Requests recent trades for an asset pair.
556    pub async fn get_trades(
557        &self,
558        pair: &str,
559        since: Option<String>,
560    ) -> anyhow::Result<TradesResponse, KrakenHttpError> {
561        let mut endpoint = format!("/0/public/Trades?pair={pair}");
562
563        if let Some(since) = since {
564            endpoint.push_str(&format!("&since={since}"));
565        }
566
567        let response: KrakenResponse<TradesResponse> = self
568            .send_request(Method::GET, &endpoint, None, false)
569            .await?;
570
571        response.result.ok_or_else(|| {
572            KrakenHttpError::ParseError("Missing result in trades response".to_string())
573        })
574    }
575
576    /// Requests an authentication token for WebSocket connections.
577    pub async fn get_websockets_token(&self) -> anyhow::Result<WebSocketToken, KrakenHttpError> {
578        if self.credential.is_none() {
579            return Err(KrakenHttpError::AuthenticationError(
580                "API credentials required for GetWebSocketsToken".to_string(),
581            ));
582        }
583
584        let response: KrakenResponse<WebSocketToken> = self
585            .send_request(Method::POST, "/0/private/GetWebSocketsToken", None, true)
586            .await?;
587
588        response.result.ok_or_else(|| {
589            KrakenHttpError::ParseError("Missing result in websockets token response".to_string())
590        })
591    }
592
593    /// Requests all open orders (requires authentication).
594    pub async fn get_open_orders(
595        &self,
596        trades: Option<bool>,
597        userref: Option<i64>,
598    ) -> anyhow::Result<IndexMap<String, SpotOrder>, KrakenHttpError> {
599        if self.credential.is_none() {
600            return Err(KrakenHttpError::AuthenticationError(
601                "API credentials required for OpenOrders".to_string(),
602            ));
603        }
604
605        let mut params = vec![];
606        if let Some(trades_flag) = trades {
607            params.push(format!("trades={trades_flag}"));
608        }
609        if let Some(userref_val) = userref {
610            params.push(format!("userref={userref_val}"));
611        }
612
613        let body = if params.is_empty() {
614            None
615        } else {
616            Some(params.join("&").into_bytes())
617        };
618
619        let response: KrakenResponse<SpotOpenOrdersResult> = self
620            .send_request(Method::POST, "/0/private/OpenOrders", body, true)
621            .await?;
622
623        let result = response.result.ok_or_else(|| {
624            KrakenHttpError::ParseError("Missing result in open orders response".to_string())
625        })?;
626
627        Ok(result.open)
628    }
629
630    /// Requests closed orders history (requires authentication).
631    pub async fn get_closed_orders(
632        &self,
633        trades: Option<bool>,
634        userref: Option<i64>,
635        start: Option<i64>,
636        end: Option<i64>,
637        ofs: Option<i32>,
638        closetime: Option<String>,
639    ) -> anyhow::Result<IndexMap<String, SpotOrder>, KrakenHttpError> {
640        if self.credential.is_none() {
641            return Err(KrakenHttpError::AuthenticationError(
642                "API credentials required for ClosedOrders".to_string(),
643            ));
644        }
645
646        let mut params = vec![];
647        if let Some(trades_flag) = trades {
648            params.push(format!("trades={trades_flag}"));
649        }
650        if let Some(userref_val) = userref {
651            params.push(format!("userref={userref_val}"));
652        }
653        if let Some(start_val) = start {
654            params.push(format!("start={start_val}"));
655        }
656        if let Some(end_val) = end {
657            params.push(format!("end={end_val}"));
658        }
659        if let Some(ofs_val) = ofs {
660            params.push(format!("ofs={ofs_val}"));
661        }
662        if let Some(closetime_val) = closetime {
663            params.push(format!("closetime={closetime_val}"));
664        }
665
666        let body = if params.is_empty() {
667            None
668        } else {
669            Some(params.join("&").into_bytes())
670        };
671
672        let response: KrakenResponse<SpotClosedOrdersResult> = self
673            .send_request(Method::POST, "/0/private/ClosedOrders", body, true)
674            .await?;
675
676        let result = response.result.ok_or_else(|| {
677            KrakenHttpError::ParseError("Missing result in closed orders response".to_string())
678        })?;
679
680        Ok(result.closed)
681    }
682
683    /// Requests trades history (requires authentication).
684    pub async fn get_trades_history(
685        &self,
686        trade_type: Option<String>,
687        trades: Option<bool>,
688        start: Option<i64>,
689        end: Option<i64>,
690        ofs: Option<i32>,
691    ) -> anyhow::Result<IndexMap<String, SpotTrade>, KrakenHttpError> {
692        if self.credential.is_none() {
693            return Err(KrakenHttpError::AuthenticationError(
694                "API credentials required for TradesHistory".to_string(),
695            ));
696        }
697
698        let mut params = vec![];
699        if let Some(type_val) = trade_type {
700            params.push(format!("type={type_val}"));
701        }
702        if let Some(trades_flag) = trades {
703            params.push(format!("trades={trades_flag}"));
704        }
705        if let Some(start_val) = start {
706            params.push(format!("start={start_val}"));
707        }
708        if let Some(end_val) = end {
709            params.push(format!("end={end_val}"));
710        }
711        if let Some(ofs_val) = ofs {
712            params.push(format!("ofs={ofs_val}"));
713        }
714
715        let body = if params.is_empty() {
716            None
717        } else {
718            Some(params.join("&").into_bytes())
719        };
720
721        let response: KrakenResponse<SpotTradesHistoryResult> = self
722            .send_request(Method::POST, "/0/private/TradesHistory", body, true)
723            .await?;
724
725        let result = response.result.ok_or_else(|| {
726            KrakenHttpError::ParseError("Missing result in trades history response".to_string())
727        })?;
728
729        Ok(result.trades)
730    }
731
732    /// Submits a new order (requires authentication).
733    pub async fn add_order(
734        &self,
735        params: &KrakenSpotAddOrderParams,
736    ) -> anyhow::Result<SpotAddOrderResponse, KrakenHttpError> {
737        if self.credential.is_none() {
738            return Err(KrakenHttpError::AuthenticationError(
739                "API credentials required for adding orders".to_string(),
740            ));
741        }
742
743        let param_string = serde_urlencoded::to_string(params)
744            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to encode params: {e}")))?;
745        let body = Some(param_string.into_bytes());
746
747        let response: KrakenResponse<SpotAddOrderResponse> = self
748            .send_request(Method::POST, "/0/private/AddOrder", body, true)
749            .await?;
750
751        response
752            .result
753            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
754    }
755
756    /// Cancels an open order (requires authentication).
757    pub async fn cancel_order(
758        &self,
759        params: &KrakenSpotCancelOrderParams,
760    ) -> anyhow::Result<SpotCancelOrderResponse, KrakenHttpError> {
761        if self.credential.is_none() {
762            return Err(KrakenHttpError::AuthenticationError(
763                "API credentials required for canceling orders".to_string(),
764            ));
765        }
766
767        let param_string = serde_urlencoded::to_string(params)
768            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to encode params: {e}")))?;
769
770        let body = Some(param_string.into_bytes());
771
772        let response: KrakenResponse<SpotCancelOrderResponse> = self
773            .send_request(Method::POST, "/0/private/CancelOrder", body, true)
774            .await?;
775
776        response
777            .result
778            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
779    }
780
781    /// Cancels multiple orders in a single batch request (max 50 orders).
782    pub async fn cancel_order_batch(
783        &self,
784        params: &KrakenSpotCancelOrderBatchParams,
785    ) -> anyhow::Result<SpotCancelOrderBatchResponse, KrakenHttpError> {
786        let credential = self.credential.as_ref().ok_or_else(|| {
787            KrakenHttpError::AuthenticationError(
788                "API credentials required for canceling orders".to_string(),
789            )
790        })?;
791
792        // Serialize authenticated requests to ensure nonces arrive at Kraken in order
793        let _guard = self.auth_mutex.lock().await;
794
795        let endpoint = "/0/private/CancelOrderBatch";
796        let nonce = self.generate_nonce();
797
798        // CancelOrderBatch uses JSON body with nonce included
799        let json_body = serde_json::json!({
800            "nonce": nonce.to_string(),
801            "orders": params.orders
802        });
803        let json_str = serde_json::to_string(&json_body)
804            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to serialize: {e}")))?;
805
806        let signature = credential
807            .sign_spot_json(endpoint, nonce, &json_str)
808            .map_err(|e| KrakenHttpError::AuthenticationError(format!("Failed to sign: {e}")))?;
809
810        let mut headers = Self::default_headers();
811        headers.insert("API-Key".to_string(), credential.api_key().to_string());
812        headers.insert("API-Sign".to_string(), signature);
813        headers.insert("Content-Type".to_string(), "application/json".to_string());
814
815        let url = format!("{}{endpoint}", self.base_url);
816        let rate_limit_keys = Self::rate_limit_keys(endpoint);
817
818        let response = self
819            .client
820            .request(
821                Method::POST,
822                url,
823                None,
824                Some(headers),
825                Some(json_str.into_bytes()),
826                None,
827                Some(rate_limit_keys),
828            )
829            .await
830            .map_err(|e| KrakenHttpError::NetworkError(e.to_string()))?;
831
832        if response.status.as_u16() >= 400 {
833            let status = response.status.as_u16();
834            let body = String::from_utf8_lossy(&response.body).to_string();
835            if status == 401 || status == 403 {
836                return Err(KrakenHttpError::AuthenticationError(format!(
837                    "HTTP error {status}: {body}"
838                )));
839            }
840            return Err(KrakenHttpError::NetworkError(format!(
841                "HTTP error {status}: {body}"
842            )));
843        }
844
845        let response_text = String::from_utf8(response.body.to_vec())
846            .map_err(|e| KrakenHttpError::ParseError(format!("Invalid UTF-8: {e}")))?;
847
848        let kraken_response: KrakenResponse<SpotCancelOrderBatchResponse> =
849            serde_json::from_str(&response_text).map_err(|e| {
850                KrakenHttpError::ParseError(format!("Failed to parse response: {e}"))
851            })?;
852
853        kraken_response
854            .result
855            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
856    }
857
858    /// Cancels all open orders (requires authentication).
859    pub async fn cancel_all_orders(
860        &self,
861    ) -> anyhow::Result<SpotCancelOrderResponse, KrakenHttpError> {
862        if self.credential.is_none() {
863            return Err(KrakenHttpError::AuthenticationError(
864                "API credentials required for canceling orders".to_string(),
865            ));
866        }
867
868        let response: KrakenResponse<SpotCancelOrderResponse> = self
869            .send_request(Method::POST, "/0/private/CancelAll", None, true)
870            .await?;
871
872        response
873            .result
874            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
875    }
876
877    /// Edits an existing order (cancel and replace).
878    pub async fn edit_order(
879        &self,
880        params: &KrakenSpotEditOrderParams,
881    ) -> anyhow::Result<SpotEditOrderResponse, KrakenHttpError> {
882        if self.credential.is_none() {
883            return Err(KrakenHttpError::AuthenticationError(
884                "API credentials required for editing orders".to_string(),
885            ));
886        }
887
888        let param_string = serde_urlencoded::to_string(params)
889            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to encode params: {e}")))?;
890
891        let body = Some(param_string.into_bytes());
892
893        let response: KrakenResponse<SpotEditOrderResponse> = self
894            .send_request(Method::POST, "/0/private/EditOrder", body, true)
895            .await?;
896
897        response
898            .result
899            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
900    }
901
902    /// Amends an existing order in-place (no cancel/replace).
903    pub async fn amend_order(
904        &self,
905        params: &KrakenSpotAmendOrderParams,
906    ) -> anyhow::Result<SpotAmendOrderResponse, KrakenHttpError> {
907        if self.credential.is_none() {
908            return Err(KrakenHttpError::AuthenticationError(
909                "API credentials required for amending orders".to_string(),
910            ));
911        }
912
913        let param_string = serde_urlencoded::to_string(params)
914            .map_err(|e| KrakenHttpError::ParseError(format!("Failed to encode params: {e}")))?;
915
916        let body = Some(param_string.into_bytes());
917
918        let response: KrakenResponse<SpotAmendOrderResponse> = self
919            .send_request(Method::POST, "/0/private/AmendOrder", body, true)
920            .await?;
921
922        response
923            .result
924            .ok_or_else(|| KrakenHttpError::ParseError("Missing result in response".to_string()))
925    }
926
927    /// Requests account balances (requires authentication).
928    pub async fn get_balance(&self) -> anyhow::Result<BalanceResponse, KrakenHttpError> {
929        if self.credential.is_none() {
930            return Err(KrakenHttpError::AuthenticationError(
931                "API credentials required for Balance".to_string(),
932            ));
933        }
934
935        let response: KrakenResponse<BalanceResponse> = self
936            .send_request(Method::POST, "/0/private/Balance", None, true)
937            .await?;
938
939        response.result.ok_or_else(|| {
940            KrakenHttpError::ParseError("Missing result in balance response".to_string())
941        })
942    }
943}
944
945/// High-level HTTP client for the Kraken Spot REST API.
946///
947/// This client wraps the raw client and provides Nautilus domain types.
948/// It maintains an instrument cache and uses it to parse venue responses
949/// into Nautilus domain objects.
950#[cfg_attr(
951    feature = "python",
952    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.kraken")
953)]
954pub struct KrakenSpotHttpClient {
955    pub(crate) inner: Arc<KrakenSpotRawHttpClient>,
956    pub(crate) instruments_cache: Arc<DashMap<Ustr, InstrumentAny>>,
957    cache_initialized: Arc<AtomicBool>,
958    use_spot_position_reports: Arc<AtomicBool>,
959    spot_positions_quote_currency: Arc<RwLock<Ustr>>,
960}
961
962impl Clone for KrakenSpotHttpClient {
963    fn clone(&self) -> Self {
964        Self {
965            inner: self.inner.clone(),
966            instruments_cache: self.instruments_cache.clone(),
967            cache_initialized: self.cache_initialized.clone(),
968            use_spot_position_reports: self.use_spot_position_reports.clone(),
969            spot_positions_quote_currency: self.spot_positions_quote_currency.clone(),
970        }
971    }
972}
973
974impl Default for KrakenSpotHttpClient {
975    fn default() -> Self {
976        Self::new(
977            KrakenEnvironment::Mainnet,
978            None,
979            Some(60),
980            None,
981            None,
982            None,
983            None,
984            None,
985        )
986        .expect("Failed to create default KrakenSpotHttpClient")
987    }
988}
989
990impl Debug for KrakenSpotHttpClient {
991    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
992        f.debug_struct(stringify!(KrakenSpotHttpClient))
993            .field("inner", &self.inner)
994            .finish()
995    }
996}
997
998impl KrakenSpotHttpClient {
999    /// Creates a new [`KrakenSpotHttpClient`].
1000    #[allow(clippy::too_many_arguments)]
1001    pub fn new(
1002        environment: KrakenEnvironment,
1003        base_url_override: Option<String>,
1004        timeout_secs: Option<u64>,
1005        max_retries: Option<u32>,
1006        retry_delay_ms: Option<u64>,
1007        retry_delay_max_ms: Option<u64>,
1008        proxy_url: Option<String>,
1009        max_requests_per_second: Option<u32>,
1010    ) -> anyhow::Result<Self> {
1011        Ok(Self {
1012            inner: Arc::new(KrakenSpotRawHttpClient::new(
1013                environment,
1014                base_url_override,
1015                timeout_secs,
1016                max_retries,
1017                retry_delay_ms,
1018                retry_delay_max_ms,
1019                proxy_url,
1020                max_requests_per_second,
1021            )?),
1022            instruments_cache: Arc::new(DashMap::new()),
1023            cache_initialized: Arc::new(AtomicBool::new(false)),
1024            use_spot_position_reports: Arc::new(AtomicBool::new(false)),
1025            spot_positions_quote_currency: Arc::new(RwLock::new(Ustr::from("USDT"))),
1026        })
1027    }
1028
1029    /// Creates a new [`KrakenSpotHttpClient`] with credentials.
1030    #[allow(clippy::too_many_arguments)]
1031    pub fn with_credentials(
1032        api_key: String,
1033        api_secret: String,
1034        environment: KrakenEnvironment,
1035        base_url_override: Option<String>,
1036        timeout_secs: Option<u64>,
1037        max_retries: Option<u32>,
1038        retry_delay_ms: Option<u64>,
1039        retry_delay_max_ms: Option<u64>,
1040        proxy_url: Option<String>,
1041        max_requests_per_second: Option<u32>,
1042    ) -> anyhow::Result<Self> {
1043        Ok(Self {
1044            inner: Arc::new(KrakenSpotRawHttpClient::with_credentials(
1045                api_key,
1046                api_secret,
1047                environment,
1048                base_url_override,
1049                timeout_secs,
1050                max_retries,
1051                retry_delay_ms,
1052                retry_delay_max_ms,
1053                proxy_url,
1054                max_requests_per_second,
1055            )?),
1056            instruments_cache: Arc::new(DashMap::new()),
1057            cache_initialized: Arc::new(AtomicBool::new(false)),
1058            use_spot_position_reports: Arc::new(AtomicBool::new(false)),
1059            spot_positions_quote_currency: Arc::new(RwLock::new(Ustr::from("USDT"))),
1060        })
1061    }
1062
1063    /// Creates a new [`KrakenSpotHttpClient`] loading credentials from environment variables.
1064    ///
1065    /// Looks for `KRAKEN_SPOT_API_KEY` and `KRAKEN_SPOT_API_SECRET`.
1066    ///
1067    /// Note: Kraken Spot does not have a testnet/demo environment.
1068    ///
1069    /// Falls back to unauthenticated client if credentials are not set.
1070    #[allow(clippy::too_many_arguments)]
1071    pub fn from_env(
1072        environment: KrakenEnvironment,
1073        base_url_override: Option<String>,
1074        timeout_secs: Option<u64>,
1075        max_retries: Option<u32>,
1076        retry_delay_ms: Option<u64>,
1077        retry_delay_max_ms: Option<u64>,
1078        proxy_url: Option<String>,
1079        max_requests_per_second: Option<u32>,
1080    ) -> anyhow::Result<Self> {
1081        if let Some(credential) = KrakenCredential::from_env_spot() {
1082            let (api_key, api_secret) = credential.into_parts();
1083            Self::with_credentials(
1084                api_key,
1085                api_secret,
1086                environment,
1087                base_url_override,
1088                timeout_secs,
1089                max_retries,
1090                retry_delay_ms,
1091                retry_delay_max_ms,
1092                proxy_url,
1093                max_requests_per_second,
1094            )
1095        } else {
1096            Self::new(
1097                environment,
1098                base_url_override,
1099                timeout_secs,
1100                max_retries,
1101                retry_delay_ms,
1102                retry_delay_max_ms,
1103                proxy_url,
1104                max_requests_per_second,
1105            )
1106        }
1107    }
1108
1109    /// Cancels all pending HTTP requests.
1110    pub fn cancel_all_requests(&self) {
1111        self.inner.cancel_all_requests();
1112    }
1113
1114    /// Returns the cancellation token for this client.
1115    pub fn cancellation_token(&self) -> &CancellationToken {
1116        self.inner.cancellation_token()
1117    }
1118
1119    /// Caches an instrument for symbol lookup.
1120    pub fn cache_instrument(&self, instrument: InstrumentAny) {
1121        self.instruments_cache
1122            .insert(instrument.symbol().inner(), instrument);
1123        self.cache_initialized.store(true, Ordering::Release);
1124    }
1125
1126    /// Caches multiple instruments for symbol lookup.
1127    pub fn cache_instruments(&self, instruments: Vec<InstrumentAny>) {
1128        for instrument in instruments {
1129            self.instruments_cache
1130                .insert(instrument.symbol().inner(), instrument);
1131        }
1132        self.cache_initialized.store(true, Ordering::Release);
1133    }
1134
1135    /// Gets an instrument from the cache by symbol.
1136    pub fn get_cached_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
1137        self.instruments_cache
1138            .get(symbol)
1139            .map(|entry| entry.value().clone())
1140    }
1141
1142    fn get_instrument_by_raw_symbol(&self, raw_symbol: &str) -> Option<InstrumentAny> {
1143        self.instruments_cache
1144            .iter()
1145            .find(|entry| entry.value().raw_symbol().as_str() == raw_symbol)
1146            .map(|entry| entry.value().clone())
1147    }
1148
1149    fn generate_ts_init(&self) -> UnixNanos {
1150        get_atomic_clock_realtime().get_time_ns()
1151    }
1152
1153    /// Sets whether to generate position reports from wallet balances for SPOT instruments.
1154    pub fn set_use_spot_position_reports(&self, value: bool) {
1155        self.use_spot_position_reports
1156            .store(value, Ordering::Relaxed);
1157    }
1158
1159    /// Sets the quote currency filter for spot position reports.
1160    pub fn set_spot_positions_quote_currency(&self, currency: &str) {
1161        let mut guard = self.spot_positions_quote_currency.write().expect("lock");
1162        *guard = Ustr::from(currency);
1163    }
1164
1165    /// Requests an authentication token for WebSocket connections.
1166    pub async fn get_websockets_token(&self) -> anyhow::Result<WebSocketToken, KrakenHttpError> {
1167        self.inner.get_websockets_token().await
1168    }
1169
1170    /// Requests tradable instruments from Kraken.
1171    pub async fn request_instruments(
1172        &self,
1173        pairs: Option<Vec<String>>,
1174    ) -> anyhow::Result<Vec<InstrumentAny>, KrakenHttpError> {
1175        let ts_init = self.generate_ts_init();
1176        let asset_pairs = self.inner.get_asset_pairs(pairs).await?;
1177
1178        let instruments: Vec<InstrumentAny> = asset_pairs
1179            .iter()
1180            .filter_map(|(pair_name, definition)| {
1181                match parse_spot_instrument(pair_name, definition, ts_init, ts_init) {
1182                    Ok(instrument) => Some(instrument),
1183                    Err(e) => {
1184                        tracing::warn!("Failed to parse instrument {pair_name}: {e}");
1185                        None
1186                    }
1187                }
1188            })
1189            .collect();
1190
1191        Ok(instruments)
1192    }
1193
1194    /// Requests historical trades for an instrument.
1195    pub async fn request_trades(
1196        &self,
1197        instrument_id: InstrumentId,
1198        start: Option<DateTime<Utc>>,
1199        end: Option<DateTime<Utc>>,
1200        limit: Option<u64>,
1201    ) -> anyhow::Result<Vec<TradeTick>, KrakenHttpError> {
1202        let instrument = self
1203            .get_cached_instrument(&instrument_id.symbol.inner())
1204            .ok_or_else(|| {
1205                KrakenHttpError::ParseError(format!(
1206                    "Instrument not found in cache: {instrument_id}",
1207                ))
1208            })?;
1209
1210        let raw_symbol = instrument.raw_symbol().to_string();
1211        let ts_init = self.generate_ts_init();
1212
1213        // Kraken trades API expects nanoseconds since epoch as string
1214        let since = start.map(|dt| (dt.timestamp_nanos_opt().unwrap_or(0) as u64).to_string());
1215        let response = self.inner.get_trades(&raw_symbol, since).await?;
1216
1217        let end_ns = end.map(|dt| dt.timestamp_nanos_opt().unwrap_or(0) as u64);
1218        let mut trades = Vec::new();
1219
1220        for (_pair_name, trade_arrays) in &response.data {
1221            for trade_array in trade_arrays {
1222                match parse_trade_tick_from_array(trade_array, &instrument, ts_init) {
1223                    Ok(trade_tick) => {
1224                        if let Some(end_nanos) = end_ns
1225                            && trade_tick.ts_event.as_u64() > end_nanos
1226                        {
1227                            continue;
1228                        }
1229                        trades.push(trade_tick);
1230
1231                        if let Some(limit_count) = limit
1232                            && trades.len() >= limit_count as usize
1233                        {
1234                            return Ok(trades);
1235                        }
1236                    }
1237                    Err(e) => {
1238                        tracing::warn!("Failed to parse trade tick: {e}");
1239                    }
1240                }
1241            }
1242        }
1243
1244        Ok(trades)
1245    }
1246
1247    /// Requests historical bars/OHLC data for an instrument.
1248    pub async fn request_bars(
1249        &self,
1250        bar_type: BarType,
1251        start: Option<DateTime<Utc>>,
1252        end: Option<DateTime<Utc>>,
1253        limit: Option<u64>,
1254    ) -> anyhow::Result<Vec<Bar>, KrakenHttpError> {
1255        let instrument_id = bar_type.instrument_id();
1256        let instrument = self
1257            .get_cached_instrument(&instrument_id.symbol.inner())
1258            .ok_or_else(|| {
1259                KrakenHttpError::ParseError(format!(
1260                    "Instrument not found in cache: {instrument_id}"
1261                ))
1262            })?;
1263
1264        let raw_symbol = instrument.raw_symbol().to_string();
1265        let ts_init = self.generate_ts_init();
1266
1267        let interval = Some(
1268            bar_type_to_spot_interval(bar_type)
1269                .map_err(|e| KrakenHttpError::ParseError(e.to_string()))?,
1270        );
1271
1272        // Kraken OHLC API expects Unix timestamp in seconds
1273        let since = start.map(|dt| dt.timestamp());
1274        let end_ns = end.map(|dt| dt.timestamp_nanos_opt().unwrap_or(0) as u64);
1275        let response = self.inner.get_ohlc(&raw_symbol, interval, since).await?;
1276
1277        let mut bars = Vec::new();
1278
1279        for (_pair_name, ohlc_arrays) in &response.data {
1280            for ohlc_array in ohlc_arrays {
1281                if ohlc_array.len() < 8 {
1282                    let len = ohlc_array.len();
1283                    tracing::warn!("OHLC array too short: {len}");
1284                    continue;
1285                }
1286
1287                let ohlc = OhlcData {
1288                    time: ohlc_array[0].as_i64().unwrap_or(0),
1289                    open: ohlc_array[1].as_str().unwrap_or("0").to_string(),
1290                    high: ohlc_array[2].as_str().unwrap_or("0").to_string(),
1291                    low: ohlc_array[3].as_str().unwrap_or("0").to_string(),
1292                    close: ohlc_array[4].as_str().unwrap_or("0").to_string(),
1293                    vwap: ohlc_array[5].as_str().unwrap_or("0").to_string(),
1294                    volume: ohlc_array[6].as_str().unwrap_or("0").to_string(),
1295                    count: ohlc_array[7].as_i64().unwrap_or(0),
1296                };
1297
1298                match parse_bar(&ohlc, &instrument, bar_type, ts_init) {
1299                    Ok(bar) => {
1300                        if let Some(end_nanos) = end_ns
1301                            && bar.ts_event.as_u64() > end_nanos
1302                        {
1303                            continue;
1304                        }
1305                        bars.push(bar);
1306
1307                        if let Some(limit_count) = limit
1308                            && bars.len() >= limit_count as usize
1309                        {
1310                            return Ok(bars);
1311                        }
1312                    }
1313                    Err(e) => {
1314                        tracing::warn!("Failed to parse bar: {e}");
1315                    }
1316                }
1317            }
1318        }
1319
1320        Ok(bars)
1321    }
1322
1323    /// Requests account state (balances) from Kraken.
1324    ///
1325    /// Returns an `AccountState` containing all currency balances.
1326    pub async fn request_account_state(
1327        &self,
1328        account_id: AccountId,
1329    ) -> anyhow::Result<AccountState> {
1330        let balances_raw = self.inner.get_balance().await?;
1331        let ts_init = self.generate_ts_init();
1332
1333        let balances: Vec<AccountBalance> = balances_raw
1334            .iter()
1335            .filter_map(|(currency_code, amount_str)| {
1336                let amount = amount_str.parse::<f64>().ok()?;
1337                if amount == 0.0 {
1338                    return None;
1339                }
1340
1341                // Kraken uses X-prefixed names for some currencies (e.g., XXBT for BTC)
1342                let normalized_code = currency_code
1343                    .strip_prefix("X")
1344                    .or_else(|| currency_code.strip_prefix("Z"))
1345                    .unwrap_or(currency_code);
1346
1347                let currency = Currency::new(
1348                    normalized_code,
1349                    8, // Default precision
1350                    0,
1351                    "0",
1352                    CurrencyType::Crypto,
1353                );
1354
1355                let total = Money::new(amount, currency);
1356                let locked = Money::new(0.0, currency);
1357
1358                // Balance endpoint returns total only, so free = total (no locked info)
1359                Some(AccountBalance::new(total, locked, total))
1360            })
1361            .collect();
1362
1363        Ok(AccountState::new(
1364            account_id,
1365            AccountType::Cash,
1366            balances,
1367            vec![], // No margins for spot
1368            true,   // reported
1369            UUID4::new(),
1370            ts_init,
1371            ts_init,
1372            None,
1373        ))
1374    }
1375
1376    /// Requests order status reports from Kraken.
1377    pub async fn request_order_status_reports(
1378        &self,
1379        account_id: AccountId,
1380        instrument_id: Option<InstrumentId>,
1381        start: Option<DateTime<Utc>>,
1382        end: Option<DateTime<Utc>>,
1383        open_only: bool,
1384    ) -> anyhow::Result<Vec<OrderStatusReport>> {
1385        let ts_init = self.generate_ts_init();
1386        let mut all_reports = Vec::new();
1387
1388        let open_orders = self.inner.get_open_orders(Some(true), None).await?;
1389
1390        for (order_id, order) in &open_orders {
1391            if let Some(ref target_id) = instrument_id {
1392                let instrument = self.get_cached_instrument(&target_id.symbol.inner());
1393                if let Some(inst) = instrument
1394                    && inst.raw_symbol().as_str() != order.descr.pair
1395                {
1396                    continue;
1397                }
1398            }
1399
1400            if let Some(instrument) = self.get_instrument_by_raw_symbol(order.descr.pair.as_str()) {
1401                match parse_order_status_report(order_id, order, &instrument, account_id, ts_init) {
1402                    Ok(report) => all_reports.push(report),
1403                    Err(e) => {
1404                        tracing::warn!("Failed to parse order {order_id}: {e}");
1405                    }
1406                }
1407            }
1408        }
1409
1410        if open_only {
1411            return Ok(all_reports);
1412        }
1413
1414        // Kraken API expects Unix timestamps in seconds
1415        let start_ts = start.map(|dt| dt.timestamp());
1416        let end_ts = end.map(|dt| dt.timestamp());
1417
1418        let mut offset = 0;
1419        const PAGE_SIZE: i32 = 50;
1420
1421        loop {
1422            let closed_orders = self
1423                .inner
1424                .get_closed_orders(Some(true), None, start_ts, end_ts, Some(offset), None)
1425                .await?;
1426
1427            if closed_orders.is_empty() {
1428                break;
1429            }
1430
1431            for (order_id, order) in &closed_orders {
1432                if let Some(ref target_id) = instrument_id {
1433                    let instrument = self.get_cached_instrument(&target_id.symbol.inner());
1434                    if let Some(inst) = instrument
1435                        && inst.raw_symbol().as_str() != order.descr.pair
1436                    {
1437                        continue;
1438                    }
1439                }
1440
1441                if let Some(instrument) =
1442                    self.get_instrument_by_raw_symbol(order.descr.pair.as_str())
1443                {
1444                    match parse_order_status_report(
1445                        order_id,
1446                        order,
1447                        &instrument,
1448                        account_id,
1449                        ts_init,
1450                    ) {
1451                        Ok(report) => all_reports.push(report),
1452                        Err(e) => {
1453                            tracing::warn!("Failed to parse order {order_id}: {e}");
1454                        }
1455                    }
1456                }
1457            }
1458
1459            offset += PAGE_SIZE;
1460        }
1461
1462        Ok(all_reports)
1463    }
1464
1465    /// Requests fill/trade reports from Kraken.
1466    pub async fn request_fill_reports(
1467        &self,
1468        account_id: AccountId,
1469        instrument_id: Option<InstrumentId>,
1470        start: Option<DateTime<Utc>>,
1471        end: Option<DateTime<Utc>>,
1472    ) -> anyhow::Result<Vec<FillReport>> {
1473        let ts_init = self.generate_ts_init();
1474        let mut all_reports = Vec::new();
1475
1476        // Kraken API expects Unix timestamps in seconds
1477        let start_ts = start.map(|dt| dt.timestamp());
1478        let end_ts = end.map(|dt| dt.timestamp());
1479
1480        let mut offset = 0;
1481        const PAGE_SIZE: i32 = 50;
1482
1483        loop {
1484            let trades = self
1485                .inner
1486                .get_trades_history(None, Some(true), start_ts, end_ts, Some(offset))
1487                .await?;
1488
1489            if trades.is_empty() {
1490                break;
1491            }
1492
1493            for (trade_id, trade) in &trades {
1494                if let Some(ref target_id) = instrument_id {
1495                    let instrument = self.get_cached_instrument(&target_id.symbol.inner());
1496                    if let Some(inst) = instrument
1497                        && inst.raw_symbol().as_str() != trade.pair
1498                    {
1499                        continue;
1500                    }
1501                }
1502
1503                if let Some(instrument) = self.get_instrument_by_raw_symbol(trade.pair.as_str()) {
1504                    match parse_fill_report(trade_id, trade, &instrument, account_id, ts_init) {
1505                        Ok(report) => all_reports.push(report),
1506                        Err(e) => {
1507                            tracing::warn!("Failed to parse trade {trade_id}: {e}");
1508                        }
1509                    }
1510                }
1511            }
1512
1513            offset += PAGE_SIZE;
1514        }
1515
1516        Ok(all_reports)
1517    }
1518
1519    /// Requests position status reports for SPOT instruments.
1520    ///
1521    /// Returns wallet balances as position reports if `use_spot_position_reports` is enabled.
1522    /// Otherwise returns an empty vector (spot traditionally has no "positions").
1523    pub async fn request_position_status_reports(
1524        &self,
1525        account_id: AccountId,
1526        instrument_id: Option<InstrumentId>,
1527    ) -> anyhow::Result<Vec<PositionStatusReport>> {
1528        if self.use_spot_position_reports.load(Ordering::Relaxed) {
1529            self.generate_spot_position_reports_from_wallet(account_id, instrument_id)
1530                .await
1531        } else {
1532            Ok(Vec::new())
1533        }
1534    }
1535
1536    /// Generates SPOT position reports from wallet balances.
1537    ///
1538    /// Kraken spot balances are simple totals (no borrowing concept).
1539    /// Positive balances are reported as LONG positions.
1540    /// Zero balances are reported as FLAT.
1541    async fn generate_spot_position_reports_from_wallet(
1542        &self,
1543        account_id: AccountId,
1544        instrument_id: Option<InstrumentId>,
1545    ) -> anyhow::Result<Vec<PositionStatusReport>> {
1546        let balances_raw = self.inner.get_balance().await?;
1547        let ts_init = self.generate_ts_init();
1548        let mut wallet_by_coin: HashMap<Ustr, f64> = HashMap::new();
1549
1550        for (currency_code, amount_str) in balances_raw.iter() {
1551            let balance = match amount_str.parse::<f64>() {
1552                Ok(b) => b,
1553                Err(_) => continue,
1554            };
1555
1556            if balance == 0.0 {
1557                continue;
1558            }
1559
1560            wallet_by_coin.insert(Ustr::from(normalize_currency_code(currency_code)), balance);
1561        }
1562
1563        let mut reports = Vec::new();
1564
1565        if let Some(instrument_id) = instrument_id {
1566            if let Some(instrument) = self.get_cached_instrument(&instrument_id.symbol.inner()) {
1567                let base_currency = match instrument.base_currency() {
1568                    Some(currency) => currency,
1569                    None => return Ok(reports),
1570                };
1571
1572                let coin = Ustr::from(normalize_currency_code(base_currency.code.as_str()));
1573                let wallet_balance = wallet_by_coin.get(&coin).copied().unwrap_or(0.0);
1574
1575                let side = if wallet_balance > 0.0 {
1576                    PositionSideSpecified::Long
1577                } else {
1578                    PositionSideSpecified::Flat
1579                };
1580
1581                let abs_balance = wallet_balance.abs();
1582                let quantity = Quantity::new(abs_balance, instrument.size_precision());
1583
1584                let report = PositionStatusReport::new(
1585                    account_id,
1586                    instrument_id,
1587                    side,
1588                    quantity,
1589                    ts_init,
1590                    ts_init,
1591                    None,
1592                    None,
1593                    None,
1594                );
1595
1596                reports.push(report);
1597            }
1598        } else {
1599            let quote_filter = *self.spot_positions_quote_currency.read().expect("lock");
1600
1601            for entry in self.instruments_cache.iter() {
1602                let instrument = entry.value();
1603
1604                let quote_currency = match instrument.quote_currency() {
1605                    currency if currency.code == quote_filter => currency,
1606                    _ => continue,
1607                };
1608
1609                let base_currency = match instrument.base_currency() {
1610                    Some(currency) => currency,
1611                    None => continue,
1612                };
1613
1614                let coin = Ustr::from(normalize_currency_code(base_currency.code.as_str()));
1615                let wallet_balance = wallet_by_coin.get(&coin).copied().unwrap_or(0.0);
1616
1617                if wallet_balance == 0.0 {
1618                    continue;
1619                }
1620
1621                let side = PositionSideSpecified::Long;
1622                let quantity = Quantity::new(wallet_balance, instrument.size_precision());
1623
1624                if quantity.is_zero() {
1625                    continue;
1626                }
1627
1628                tracing::debug!(
1629                    "Spot position: {} {} (quote: {})",
1630                    quantity,
1631                    base_currency.code,
1632                    quote_currency.code
1633                );
1634
1635                let report = PositionStatusReport::new(
1636                    account_id,
1637                    instrument.id(),
1638                    side,
1639                    quantity,
1640                    ts_init,
1641                    ts_init,
1642                    None,
1643                    None,
1644                    None,
1645                );
1646
1647                reports.push(report);
1648            }
1649        }
1650
1651        Ok(reports)
1652    }
1653
1654    /// Submits a new order to the Kraken Spot exchange.
1655    ///
1656    /// Returns the venue order ID on success. WebSocket handles all execution events.
1657    ///
1658    /// # Errors
1659    ///
1660    /// Returns an error if:
1661    /// - Credentials are missing.
1662    /// - The instrument is not found in cache.
1663    /// - The order type or time in force is not supported.
1664    /// - The request fails.
1665    /// - The order is rejected.
1666    #[allow(clippy::too_many_arguments)]
1667    pub async fn submit_order(
1668        &self,
1669        _account_id: AccountId,
1670        instrument_id: InstrumentId,
1671        client_order_id: ClientOrderId,
1672        order_side: OrderSide,
1673        order_type: OrderType,
1674        quantity: Quantity,
1675        time_in_force: TimeInForce,
1676        expire_time: Option<UnixNanos>,
1677        price: Option<Price>,
1678        trigger_price: Option<Price>,
1679        reduce_only: bool,
1680        post_only: bool,
1681    ) -> anyhow::Result<VenueOrderId> {
1682        let instrument = self
1683            .get_cached_instrument(&instrument_id.symbol.inner())
1684            .ok_or_else(|| anyhow::anyhow!("Instrument not found in cache: {instrument_id}"))?;
1685
1686        let raw_symbol = instrument.raw_symbol().inner();
1687
1688        let kraken_side = match order_side {
1689            OrderSide::Buy => KrakenOrderSide::Buy,
1690            OrderSide::Sell => KrakenOrderSide::Sell,
1691            _ => anyhow::bail!("Invalid order side: {order_side:?}"),
1692        };
1693
1694        let kraken_order_type = match order_type {
1695            OrderType::Market => KrakenOrderType::Market,
1696            OrderType::Limit => KrakenOrderType::Limit,
1697            OrderType::StopMarket => KrakenOrderType::StopLoss,
1698            OrderType::StopLimit => KrakenOrderType::StopLossLimit,
1699            OrderType::MarketIfTouched => KrakenOrderType::TakeProfit,
1700            OrderType::LimitIfTouched => KrakenOrderType::TakeProfitLimit,
1701            _ => anyhow::bail!("Unsupported order type: {order_type:?}"),
1702        };
1703
1704        // Note: timeinforce is only valid for limit-type orders, not market orders
1705        let mut oflags = Vec::new();
1706        let is_limit_order = matches!(
1707            order_type,
1708            OrderType::Limit | OrderType::StopLimit | OrderType::LimitIfTouched
1709        );
1710
1711        let (timeinforce, expiretm) =
1712            compute_time_in_force(is_limit_order, time_in_force, expire_time)?;
1713
1714        if post_only {
1715            oflags.push("post");
1716        }
1717
1718        if reduce_only {
1719            tracing::warn!("reduce_only is not supported by Kraken Spot API, ignoring");
1720        }
1721
1722        let mut builder = KrakenSpotAddOrderParamsBuilder::default();
1723        builder
1724            .cl_ord_id(client_order_id.to_string())
1725            .broker(NAUTILUS_KRAKEN_BROKER_ID)
1726            .pair(raw_symbol)
1727            .side(kraken_side)
1728            .volume(quantity.to_string())
1729            .order_type(kraken_order_type);
1730
1731        // For stop/conditional orders:
1732        // - price = trigger price (when the order activates)
1733        // - price2 = limit price (for stop-limit and take-profit-limit)
1734        // For regular limit orders:
1735        // - price = limit price
1736        let is_conditional = matches!(
1737            order_type,
1738            OrderType::StopMarket
1739                | OrderType::StopLimit
1740                | OrderType::MarketIfTouched
1741                | OrderType::LimitIfTouched
1742        );
1743
1744        if is_conditional {
1745            if let Some(trigger) = trigger_price {
1746                builder.price(trigger.to_string());
1747            }
1748            if let Some(limit) = price {
1749                builder.price2(limit.to_string());
1750            }
1751        } else if let Some(limit) = price {
1752            builder.price(limit.to_string());
1753        }
1754
1755        if !oflags.is_empty() {
1756            builder.oflags(oflags.join(","));
1757        }
1758
1759        if let Some(tif) = timeinforce {
1760            builder.timeinforce(tif);
1761        }
1762
1763        if let Some(expire) = expiretm {
1764            builder.expiretm(expire);
1765        }
1766
1767        let params = builder
1768            .build()
1769            .map_err(|e| anyhow::anyhow!("Failed to build order params: {e}"))?;
1770
1771        let response = self.inner.add_order(&params).await?;
1772
1773        let venue_order_id = response
1774            .txid
1775            .first()
1776            .ok_or_else(|| anyhow::anyhow!("No transaction ID in order response"))?;
1777
1778        Ok(VenueOrderId::new(venue_order_id))
1779    }
1780
1781    /// Modifies an existing order on the Kraken Spot exchange using atomic amend.
1782    ///
1783    /// Uses the AmendOrder endpoint which modifies the order in-place,
1784    /// keeping the same order ID and queue position.
1785    ///
1786    /// # Errors
1787    ///
1788    /// Returns an error if:
1789    /// - Neither `client_order_id` nor `venue_order_id` is provided.
1790    /// - The instrument is not found in cache.
1791    /// - The request fails.
1792    pub async fn modify_order(
1793        &self,
1794        instrument_id: InstrumentId,
1795        client_order_id: Option<ClientOrderId>,
1796        venue_order_id: Option<VenueOrderId>,
1797        quantity: Option<Quantity>,
1798        price: Option<Price>,
1799        trigger_price: Option<Price>,
1800    ) -> anyhow::Result<VenueOrderId> {
1801        let _ = self
1802            .get_cached_instrument(&instrument_id.symbol.inner())
1803            .ok_or_else(|| anyhow::anyhow!("Instrument not found in cache: {instrument_id}"))?;
1804
1805        let txid = venue_order_id.as_ref().map(|id| id.to_string());
1806        let cl_ord_id = client_order_id.as_ref().map(|id| id.to_string());
1807
1808        if txid.is_none() && cl_ord_id.is_none() {
1809            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
1810        }
1811
1812        let mut builder = KrakenSpotAmendOrderParamsBuilder::default();
1813
1814        // Prefer txid (venue_order_id) over cl_ord_id
1815        if let Some(ref id) = txid {
1816            builder.txid(id.clone());
1817        } else if let Some(ref id) = cl_ord_id {
1818            builder.cl_ord_id(id.clone());
1819        }
1820
1821        if let Some(qty) = quantity {
1822            builder.order_qty(qty.to_string());
1823        }
1824        if let Some(p) = price {
1825            builder.limit_price(p.to_string());
1826        }
1827        if let Some(tp) = trigger_price {
1828            builder.trigger_price(tp.to_string());
1829        }
1830
1831        let params = builder
1832            .build()
1833            .map_err(|e| anyhow::anyhow!("Failed to build amend order params: {e}"))?;
1834
1835        let _response = self.inner.amend_order(&params).await?;
1836
1837        // AmendOrder modifies in-place, so the order keeps its original ID
1838        let order_id = venue_order_id
1839            .ok_or_else(|| anyhow::anyhow!("venue_order_id required for amend response"))?;
1840
1841        Ok(order_id)
1842    }
1843
1844    /// Cancels an order on the Kraken Spot exchange.
1845    ///
1846    /// # Errors
1847    ///
1848    /// Returns an error if:
1849    /// - Credentials are missing.
1850    /// - Neither client_order_id nor venue_order_id is provided.
1851    /// - The request fails.
1852    /// - The order cancellation is rejected.
1853    pub async fn cancel_order(
1854        &self,
1855        _account_id: AccountId,
1856        instrument_id: InstrumentId,
1857        client_order_id: Option<ClientOrderId>,
1858        venue_order_id: Option<VenueOrderId>,
1859    ) -> anyhow::Result<()> {
1860        let _ = self
1861            .get_cached_instrument(&instrument_id.symbol.inner())
1862            .ok_or_else(|| anyhow::anyhow!("Instrument not found in cache: {instrument_id}"))?;
1863
1864        let txid = venue_order_id.as_ref().map(|id| id.to_string());
1865        let cl_ord_id = client_order_id.as_ref().map(|id| id.to_string());
1866
1867        if txid.is_none() && cl_ord_id.is_none() {
1868            anyhow::bail!("Either client_order_id or venue_order_id must be provided");
1869        }
1870
1871        // Prefer txid (venue identifier) since Kraken always knows it.
1872        // cl_ord_id may not be known to Kraken for reconciled orders.
1873        let mut builder = KrakenSpotCancelOrderParamsBuilder::default();
1874        if let Some(ref id) = txid {
1875            builder.txid(id.clone());
1876        } else if let Some(ref id) = cl_ord_id {
1877            builder.cl_ord_id(id.clone());
1878        }
1879        let params = builder
1880            .build()
1881            .map_err(|e| anyhow::anyhow!("Failed to build cancel params: {e}"))?;
1882
1883        self.inner.cancel_order(&params).await?;
1884
1885        Ok(())
1886    }
1887
1888    /// Cancels multiple orders on the Kraken Spot exchange (batched, max 50 per request).
1889    pub async fn cancel_orders_batch(
1890        &self,
1891        venue_order_ids: Vec<VenueOrderId>,
1892    ) -> anyhow::Result<i32> {
1893        if venue_order_ids.is_empty() {
1894            return Ok(0);
1895        }
1896
1897        let mut total_cancelled = 0;
1898
1899        for chunk in venue_order_ids.chunks(BATCH_CANCEL_LIMIT) {
1900            let orders: Vec<String> = chunk.iter().map(|id| id.to_string()).collect();
1901            let params = KrakenSpotCancelOrderBatchParams { orders };
1902
1903            let response = self.inner.cancel_order_batch(&params).await?;
1904            total_cancelled += response.count;
1905        }
1906
1907        Ok(total_cancelled)
1908    }
1909}
1910
1911#[cfg(test)]
1912mod tests {
1913    use rstest::rstest;
1914
1915    use super::*;
1916
1917    #[rstest]
1918    fn test_raw_client_creation() {
1919        let client = KrakenSpotRawHttpClient::default();
1920        assert!(client.credential.is_none());
1921    }
1922
1923    #[rstest]
1924    fn test_raw_client_with_credentials() {
1925        let client = KrakenSpotRawHttpClient::with_credentials(
1926            "test_key".to_string(),
1927            "test_secret".to_string(),
1928            KrakenEnvironment::Mainnet,
1929            None,
1930            None,
1931            None,
1932            None,
1933            None,
1934            None,
1935            None,
1936        )
1937        .unwrap();
1938        assert!(client.credential.is_some());
1939    }
1940
1941    #[rstest]
1942    fn test_client_creation() {
1943        let client = KrakenSpotHttpClient::default();
1944        assert!(client.instruments_cache.is_empty());
1945    }
1946
1947    #[rstest]
1948    fn test_client_with_credentials() {
1949        let client = KrakenSpotHttpClient::with_credentials(
1950            "test_key".to_string(),
1951            "test_secret".to_string(),
1952            KrakenEnvironment::Mainnet,
1953            None,
1954            None,
1955            None,
1956            None,
1957            None,
1958            None,
1959            None,
1960        )
1961        .unwrap();
1962        assert!(client.instruments_cache.is_empty());
1963    }
1964
1965    #[rstest]
1966    fn test_nonce_generation_strictly_increasing() {
1967        let client = KrakenSpotRawHttpClient::default();
1968
1969        let nonce1 = client.generate_nonce();
1970        let nonce2 = client.generate_nonce();
1971        let nonce3 = client.generate_nonce();
1972
1973        assert!(
1974            nonce2 > nonce1,
1975            "nonce2 ({nonce2}) should be > nonce1 ({nonce1})"
1976        );
1977        assert!(
1978            nonce3 > nonce2,
1979            "nonce3 ({nonce3}) should be > nonce2 ({nonce2})"
1980        );
1981    }
1982
1983    #[rstest]
1984    fn test_nonce_is_nanosecond_timestamp() {
1985        let client = KrakenSpotRawHttpClient::default();
1986
1987        let nonce = client.generate_nonce();
1988
1989        // Nonce should be a nanosecond timestamp (roughly 1.7e18 for Dec 2025)
1990        // Verify it's in a reasonable range (> 1.5e18, which is ~2017)
1991        assert!(
1992            nonce > 1_500_000_000_000_000_000,
1993            "Nonce should be nanosecond timestamp"
1994        );
1995    }
1996
1997    #[rstest]
1998    #[case::gtc_limit(true, TimeInForce::Gtc, None, None, None)]
1999    #[case::ioc_limit(true, TimeInForce::Ioc, None, Some("IOC"), None)]
2000    #[case::gtd_limit_with_expire(
2001        true,
2002        TimeInForce::Gtd,
2003        Some(1_704_067_200_000_000_000u64),
2004        Some("GTD"),
2005        Some("1704067200")
2006    )]
2007    #[case::gtc_market(false, TimeInForce::Gtc, None, None, None)]
2008    #[case::ioc_market(false, TimeInForce::Ioc, None, None, None)]
2009    fn test_compute_time_in_force_success(
2010        #[case] is_limit: bool,
2011        #[case] tif: TimeInForce,
2012        #[case] expire_nanos: Option<u64>,
2013        #[case] expected_tif: Option<&str>,
2014        #[case] expected_expire: Option<&str>,
2015    ) {
2016        let expire_time = expire_nanos.map(UnixNanos::from);
2017        let result = compute_time_in_force(is_limit, tif, expire_time).unwrap();
2018        assert_eq!(result.0, expected_tif.map(String::from));
2019        assert_eq!(result.1, expected_expire.map(String::from));
2020    }
2021
2022    #[rstest]
2023    #[case::fok_not_supported(TimeInForce::Fok, None, "FOK")]
2024    #[case::gtd_missing_expire(TimeInForce::Gtd, None, "expire_time")]
2025    fn test_compute_time_in_force_errors(
2026        #[case] tif: TimeInForce,
2027        #[case] expire_nanos: Option<u64>,
2028        #[case] expected_error: &str,
2029    ) {
2030        let expire_time = expire_nanos.map(UnixNanos::from);
2031        let result = compute_time_in_force(true, tif, expire_time);
2032        assert!(result.is_err());
2033        assert!(result.unwrap_err().to_string().contains(expected_error));
2034    }
2035}