Skip to main content

nautilus_kraken/execution/
mod.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//! Live execution client implementations for the Kraken adapter.
17//!
18//! This module provides separate execution clients for Kraken Spot and Futures markets:
19//!
20//! - [`KrakenSpotExecutionClient`] - For Spot markets using WebSocket v2
21//! - [`KrakenFuturesExecutionClient`] - For Futures markets
22//!
23//! # Supported Operations
24//!
25//! ## Common
26//! - Order submission (market, limit, stop)
27//! - Order modification
28//! - Order cancellation (single, batch, cancel-all)
29//! - Account state and balance queries
30//!
31//! ## Futures Only
32//! - Position management
33
34mod futures;
35mod spot;
36
37pub use futures::KrakenFuturesExecutionClient;
38use nautilus_common::{cache::Cache, messages::execution::GenerateOrderStatusReport};
39use nautilus_core::UnixNanos;
40use nautilus_live::execution::failure::CommandFailure;
41use nautilus_model::{
42    identifiers::VenueOrderId,
43    orders::{Order, OrderAny},
44    reports::OrderStatusReport,
45};
46pub use spot::KrakenSpotExecutionClient;
47
48use crate::{
49    common::enums::KrakenApiResult,
50    http::{
51        coverage::ReportCoverage,
52        error::{
53            KrakenBatchOrderError, KrakenHttpError, KrakenModifyOrderError, KrakenSubmitOrderError,
54        },
55        futures::client::{FuturesBatchSubmitItem, is_futures_submit_rejection},
56        spot::models::SpotBatchOrderResponse,
57    },
58};
59
60/// The cached order a single-order status command names, by its client order ID or else through
61/// the venue order ID index.
62fn cached_order_for_status_command(
63    cache: &Cache,
64    cmd: &GenerateOrderStatusReport,
65) -> Option<OrderAny> {
66    if let Some(client_order_id) = cmd.client_order_id {
67        return cache.order(&client_order_id).map(|o| o.clone());
68    }
69
70    let venue_order_id = cmd.venue_order_id?;
71    let client_order_id = *cache.client_order_id(&venue_order_id)?;
72    cache.order(&client_order_id).map(|o| o.clone())
73}
74
75/// Answers a single-order lookup that found no report of `order`: absent only when the read rules
76/// the order out, else an error so reconciliation defers rather than resolving an order the read
77/// may have missed.
78fn absent_unless_unread(
79    coverage: &ReportCoverage,
80    venue_order_id: Option<VenueOrderId>,
81    placed_from: Option<UnixNanos>,
82    order: &str,
83) -> anyhow::Result<Option<OrderStatusReport>> {
84    if coverage.rules_out(venue_order_id, placed_from) {
85        return Ok(None);
86    }
87    anyhow::bail!(
88        "No report for order {order} in an order read that does not rule it out; deferring rather \
89         than reporting it missing"
90    )
91}
92
93/// Names the order a status command asks about: its client order ID, else its venue order ID.
94fn status_command_label(
95    cmd: &GenerateOrderStatusReport,
96    venue_order_id: Option<VenueOrderId>,
97) -> String {
98    match (cmd.client_order_id, venue_order_id) {
99        (Some(client_order_id), _) => client_order_id.to_string(),
100        (None, Some(venue_order_id)) => venue_order_id.to_string(),
101        (None, None) => "with neither ID".to_string(),
102    }
103}
104
105/// The earliest time an order can carry at the venue: its creation, or its acceptance when the
106/// engine adopted it from a venue report after the venue had placed it.
107fn earliest_venue_time(order: &OrderAny) -> UnixNanos {
108    let created = order.ts_init();
109    order
110        .ts_accepted()
111        .map_or(created, |accepted| accepted.min(created))
112}
113
114fn command_failure_from_submit_error(error: &anyhow::Error) -> CommandFailure {
115    for cause in error.chain() {
116        if let Some(error) = cause.downcast_ref::<KrakenSubmitOrderError>() {
117            return match error {
118                KrakenSubmitOrderError::Rejected { reason } => {
119                    CommandFailure::venue_rejected(reason)
120                }
121                KrakenSubmitOrderError::MissingStatus
122                | KrakenSubmitOrderError::UnknownStatus { .. }
123                | KrakenSubmitOrderError::MissingOrderId { .. }
124                | KrakenSubmitOrderError::InvalidOrderId { .. }
125                | KrakenSubmitOrderError::PostSubmitLookup { .. } => {
126                    CommandFailure::ambiguous(error.to_string())
127                }
128            };
129        }
130    }
131
132    command_failure_from_order_error(error, true)
133}
134
135fn command_failure_from_modify_error(error: &anyhow::Error) -> CommandFailure {
136    for cause in error.chain() {
137        if let Some(error) = cause.downcast_ref::<KrakenModifyOrderError>() {
138            return match error {
139                KrakenModifyOrderError::Rejected { reason } => {
140                    CommandFailure::venue_rejected(reason)
141                }
142                KrakenModifyOrderError::UnknownStatus { .. }
143                | KrakenModifyOrderError::MissingOrderId
144                | KrakenModifyOrderError::InvalidOrderId { .. } => {
145                    CommandFailure::ambiguous(error.to_string())
146                }
147            };
148        }
149    }
150
151    command_failure_from_order_error(error, true)
152}
153
154fn command_failure_from_spot_batch_error(error: &anyhow::Error) -> CommandFailure {
155    command_failure_from_batch_error(error, true)
156}
157
158fn command_failure_from_futures_batch_error(error: &anyhow::Error) -> CommandFailure {
159    command_failure_from_batch_error(error, false)
160}
161
162fn command_failure_from_batch_error(
163    error: &anyhow::Error,
164    whole_order_rejection: bool,
165) -> CommandFailure {
166    for cause in error.chain() {
167        if let Some(error) = cause.downcast_ref::<KrakenBatchOrderError>() {
168            return match error {
169                KrakenBatchOrderError::Validation { .. } | KrakenBatchOrderError::NotAttempted => {
170                    CommandFailure::not_sent(error.to_string())
171                }
172                KrakenBatchOrderError::ResponseCount { .. }
173                | KrakenBatchOrderError::MissingResponse { .. }
174                | KrakenBatchOrderError::DuplicateResponse { .. } => {
175                    CommandFailure::ambiguous(error.to_string())
176                }
177            };
178        }
179    }
180
181    command_failure_from_order_error(error, whole_order_rejection)
182}
183
184fn command_failure_from_order_error(
185    error: &anyhow::Error,
186    order_api_rejection: bool,
187) -> CommandFailure {
188    let reason = error.to_string();
189
190    for cause in error.chain() {
191        let Some(error) = cause.downcast_ref::<KrakenHttpError>() else {
192            continue;
193        };
194
195        return match error {
196            KrakenHttpError::RequestNotStarted(_) | KrakenHttpError::MissingCredentials => {
197                CommandFailure::not_sent(reason)
198            }
199            KrakenHttpError::ApiError(errors)
200                if order_api_rejection && contains_spot_order_rejection(errors) =>
201            {
202                CommandFailure::venue_rejected(format_api_errors(errors))
203            }
204            KrakenHttpError::NetworkError(_)
205            | KrakenHttpError::ApiError(_)
206            | KrakenHttpError::ParseError(_)
207            | KrakenHttpError::AuthenticationError(_) => CommandFailure::ambiguous(reason),
208        };
209    }
210
211    CommandFailure::not_sent(reason)
212}
213
214fn command_failure_from_spot_batch_item(
215    item: SpotBatchOrderResponse,
216) -> Result<(), CommandFailure> {
217    match (item.txid, item.error) {
218        (Some(_), None) => Ok(()),
219        (None, Some(reason)) => Err(CommandFailure::venue_rejected(reason)),
220        (Some(_), Some(_)) => Err(CommandFailure::ambiguous(
221            "Batch item response contained both a transaction ID and an error",
222        )),
223        (None, None) => Err(CommandFailure::ambiguous(
224            "Batch item response had no transaction ID or error",
225        )),
226    }
227}
228
229fn command_failure_from_futures_batch_item(
230    item: FuturesBatchSubmitItem,
231) -> Result<(), CommandFailure> {
232    let status = item.status.status;
233
234    if item.result != KrakenApiResult::Success {
235        return if is_futures_submit_rejection(&status) {
236            Err(CommandFailure::venue_rejected(status))
237        } else {
238            Err(CommandFailure::ambiguous(format!(
239                "Batch response reported an error with item status: {status}"
240            )))
241        };
242    }
243
244    match status.as_str() {
245        "placed" | "filled" => Ok(()),
246        reason if is_futures_submit_rejection(reason) => {
247            Err(CommandFailure::venue_rejected(reason))
248        }
249        "" => Err(CommandFailure::ambiguous("Empty batch item status")),
250        reason => Err(CommandFailure::ambiguous(format!(
251            "Unknown batch item status: {reason}"
252        ))),
253    }
254}
255
256fn command_failure_from_cancel_error(error: KrakenHttpError) -> CommandFailure {
257    match error {
258        KrakenHttpError::RequestNotStarted(message) => CommandFailure::not_sent(message),
259        KrakenHttpError::MissingCredentials => CommandFailure::not_sent("Missing credentials"),
260        KrakenHttpError::NetworkError(message)
261        | KrakenHttpError::ParseError(message)
262        | KrakenHttpError::AuthenticationError(message) => CommandFailure::ambiguous(message),
263        KrakenHttpError::ApiError(message) => {
264            CommandFailure::ambiguous(format_cancel_api_errors(&message))
265        }
266    }
267}
268
269fn command_failure_from_spot_cancel_error(error: KrakenHttpError) -> CommandFailure {
270    match error {
271        KrakenHttpError::ApiError(message) if contains_spot_cancel_rejection(&message) => {
272            CommandFailure::venue_rejected(format_cancel_api_errors(&message))
273        }
274        KrakenHttpError::ApiError(message) => {
275            CommandFailure::ambiguous(format_cancel_api_errors(&message))
276        }
277        other => command_failure_from_cancel_error(other),
278    }
279}
280
281fn contains_spot_order_rejection(errors: &[String]) -> bool {
282    errors.iter().any(|e| e.trim_start().starts_with("EOrder:"))
283}
284
285fn contains_spot_cancel_rejection(errors: &[String]) -> bool {
286    contains_spot_order_rejection(errors)
287}
288
289fn format_api_errors(errors: &[String]) -> String {
290    if errors.is_empty() {
291        "unknown error (empty error list)".to_string()
292    } else {
293        errors.join(", ")
294    }
295}
296
297fn format_cancel_api_errors(errors: &[String]) -> String {
298    format_api_errors(errors)
299}
300
301#[cfg(test)]
302mod tests {
303    use rstest::rstest;
304
305    use super::*;
306
307    #[rstest]
308    #[case::missing_credentials(
309        KrakenHttpError::MissingCredentials,
310        CommandFailure::NotSent("Missing credentials".to_string())
311    )]
312    #[case::local_authentication(
313        KrakenHttpError::RequestNotStarted("Failed to sign request".to_string()),
314        CommandFailure::NotSent("Failed to sign request".to_string())
315    )]
316    #[case::http_authentication(
317        KrakenHttpError::AuthenticationError("HTTP error 401: Unauthorized".to_string()),
318        CommandFailure::Ambiguous("HTTP error 401: Unauthorized".to_string())
319    )]
320    fn test_cancel_failure_preserves_authentication_phase(
321        #[case] error: KrakenHttpError,
322        #[case] expected: CommandFailure,
323        #[values(false, true)] spot: bool,
324    ) {
325        let actual = if spot {
326            command_failure_from_spot_cancel_error(error)
327        } else {
328            command_failure_from_cancel_error(error)
329        };
330
331        assert_eq!(actual, expected);
332    }
333
334    /// The venue has acted on a response carrying a malformed order ID, so neither command may read
335    /// as not sent: that would reject a live order or deny an applied edit.
336    #[rstest]
337    fn test_invalid_order_id_in_a_command_response_is_ambiguous() {
338        let submit = anyhow::Error::new(KrakenSubmitOrderError::InvalidOrderId {
339            detail: "Invalid order_id '' in Kraken spot submit response".to_string(),
340        });
341        let modify = anyhow::Error::new(KrakenModifyOrderError::InvalidOrderId {
342            detail: "Invalid order_id '' in Kraken futures edit response".to_string(),
343        });
344
345        assert_eq!(
346            command_failure_from_submit_error(&submit),
347            CommandFailure::Ambiguous(
348                "Invalid order_id '' in Kraken spot submit response".to_string()
349            )
350        );
351        assert_eq!(
352            command_failure_from_modify_error(&modify),
353            CommandFailure::Ambiguous(
354                "Invalid order_id '' in Kraken futures edit response".to_string()
355            )
356        );
357    }
358
359    #[rstest]
360    fn test_post_submit_phase_overrides_nested_not_sent_error() {
361        let error = anyhow::Error::new(KrakenSubmitOrderError::PostSubmitLookup {
362            source: KrakenHttpError::RequestNotStarted("lookup was not sent".to_string()).into(),
363        });
364
365        assert_eq!(
366            command_failure_from_submit_error(&error),
367            CommandFailure::Ambiguous(
368                "Order lookup failed after submission: Request not started: lookup was not sent"
369                    .to_string()
370            )
371        );
372    }
373
374    #[rstest]
375    fn test_request_not_started_is_not_sent() {
376        let error = anyhow::Error::new(KrakenHttpError::RequestNotStarted(
377            "request encoding failed".to_string(),
378        ));
379
380        assert_eq!(
381            command_failure_from_submit_error(&error),
382            CommandFailure::NotSent("Request not started: request encoding failed".to_string())
383        );
384    }
385
386    /// A venue `EOrder` rate-limit refusal is a rejection, not an ambiguous retry failure:
387    /// Kraken definitively refused the cancel and the order remains live. The error text is
388    /// retryable-class for reads, so pin the deliberate classification difference.
389    #[rstest]
390    fn test_spot_cancel_venue_rate_limit_refusal_is_a_rejection() {
391        let error = KrakenHttpError::ApiError(vec!["EOrder:Rate limit exceeded".to_string()]);
392
393        assert!(crate::http::error::kraken_http_should_retry(&error));
394        assert_eq!(
395            command_failure_from_spot_cancel_error(error),
396            CommandFailure::VenueRejected("EOrder:Rate limit exceeded".to_string())
397        );
398    }
399}