NautilusTrader
Integrations

Nightly docs

These docs track unreleased changes and may change without notice. Their code examples can use APIs that the latest release lacks, so run them with a development wheel or switch to the latest release docs.

Kraken

The Kraken adapter supports live market data and order execution for Kraken Spot and Kraken Derivatives (Futures).

Overview

The adapter is implemented in Rust with Python bindings and does not require an external Kraken client library. Each data or execution configuration selects a Spot or Futures client through its product_type.

The main Python components are:

  • KrakenDataClientConfig and KrakenExecutionClientConfig: Live client configuration.
  • KrakenDataClientFactory and KrakenExecutionClientFactory: Factories used by the trading node builder.
  • KrakenSpotHttpClient and KrakenFuturesHttpClient: Lower-level HTTP access for direct requests.

The Rust crate also exposes KrakenSpotWebSocketClient and KrakenFuturesWebSocketClient for lower-level WebSocket access.

Configure the adapter through a live trading node, or use the lower-level clients for direct API access.

Examples

Kraken documentation

Products

The adapter supports these product categories:

Product typeSupportedNotes
Spot currency pairs✓Cash trading and margin on eligible pairs.
Spot tokenized assets✓Loaded from Kraken's tokenized_asset asset class.
Futures✓Instruments returned by the Kraken Futures API.

Kraken Futures can return instrument definitions that need more than standard-precision mode's nine decimal places. Keep high-precision mode enabled for Futures. Standard-precision mode continues to support Spot, but Futures clients fail to start or return instruments when any definition cannot be parsed. Futures catalog requests return no partial result and never round, clamp, or omit an unsupported definition.

Single product type per client: Each Kraken data or execution client is configured for a single product_type (SPOT or FUTURES). A single client does not span both markets.

Spot instrument fees

Spot instrument loading does not populate venue maker or taker fee rates and does not call Kraken's TradeVolume endpoint.

A Spot API key without Funds permissions - Query (Query Funds) fails when the execution client requests account state.

Bar streaming

Supported intervals

For Spot, subscribe to EXTERNAL bars to receive Kraken's WebSocket OHLC data. The following intervals are available:

IntervalBarType specification
1 minute1-MINUTE-LAST
5 minutes5-MINUTE-LAST
15 minutes15-MINUTE-LAST
30 minutes30-MINUTE-LAST
1 hour1-HOUR-LAST
4 hours4-HOUR-LAST
1 day1-DAY-LAST
1 week1-WEEK-LAST
15 days15-DAY-LAST

Futures limitation: Kraken Futures does not support bar streaming via WebSocket. Use request_bars() for historical bar data instead.

Bar emission latency

Kraken's Spot WebSocket OHLC channel updates the current, incomplete bar on trade events. It does not provide a field that marks a bar as closed.

During normal streaming, the adapter buffers the current bar and emits it after receiving an update with a new interval_begin. Thus, the delay depends on the first trade in the next interval. For a market with no trades, it is not bounded to one bar period. When the WebSocket message handler stops, the adapter flushes its buffered bars, including a current bar that may still be incomplete.

The adapter uses buffering instead of timer-based emission because:

  • Timer-based emission could miss the final update before the bar closes.
  • Kraken's updates are not guaranteed to arrive at exact interval boundaries.

For lower bar latency, subscribe to trade ticks and use INTERNAL aggregation with BarAggregator. Time bars use local timers, avoiding the wait for Kraken's next-interval trade, and use the same aggregation behavior across venues.

Symbology

Spot symbol normalization

The adapter uses different Bitcoin symbol conventions for Spot and Futures:

MarketSymbol formatExampleNotes
SpotBTCBTC/USD.KRAKENAdapter normalizes XBT to BTC at load time.
FuturesXBTPI_XBTUSD.KRAKENInstrument symbols keep Kraken's native XBT.

Kraken's REST API can return XBT for Bitcoin, while its WebSocket v2 API requires BTC. The adapter normalizes Spot symbols to BTC when loading instruments, whether XBT appears as the base currency (for example, XBT/USD to BTC/USD) or quote currency (for example, ETH/XBT to ETH/BTC). Futures instrument symbols retain Kraken's native XBT format. Futures currency codes do not, and follow the same currency mapping as Spot.

Kraken also uses XDG for Dogecoin in some Spot responses. The adapter normalizes it to DOGE, including in quote currency symbols.

Currency codes

The adapter maps Kraken's legacy asset codes to standard codes consistently across instruments, balances, fees, and currency configuration:

  • XXBT and XBT become BTC.
  • XXDG and XDG become DOGE.
  • ZEUR becomes EUR, and ZUSD becomes USD.

The mapping uses an explicit table, as Kraken's own CLI does, rather than stripping prefixes. XTZ, XRP, XLM, XAUT, ZRX, and ZEC are valid codes. An unlisted code passes through unchanged.

Configuration accepts either spelling. For example, spot_positions_quote_currency="ZEUR" and "EUR" both match a euro-quoted instrument.

Fees use the venue-reported currency when available. Futures fills can carry a fee currency, which on an inverse contract is the base rather than the quote. Spot TradesHistory reports only a fee amount, so those commissions use the instrument's quote currency.

Migration from earlier currency codes

Migrate or rebuild caches and databases written before currency normalization. Stored instruments, fills, positions, and balances can use the earlier codes below.

The earlier mappings differed by source:

  • Instruments retained XXBT, XETH, XXDG, ZUSD, and ZEUR, as did their fills and positions. These become BTC, ETH, DOGE, USD, and EUR.
  • Spot balances and the margin summary asset lost one leading X or Z. This left XBT and XDG instead of BTC and DOGE, and TZ, RX, and AUT instead of XTZ, ZRX, and XAUT. KFEE becomes FEE under the explicit mapping.
  • Futures balances retained the wallet's spelling: cash and margin wallets use xbt, while the flex wallet uses XBT. Both become BTC. usd becomes USD.

Futures wallet aggregation

Futures balances with the same normalized code combine into one entry. Total and locked amounts sum across wallets. Each wallet's locked amount is bounded to [0, total] for a non-negative total. A negative total keeps its reported locked amount. The aggregate is not clamped. Free balance can therefore be negative when reservations exceed the combined holding, preserving the actual shortfall.

Previously, separate wallet entries overwrote each other in the account, leaving only the last entry read.

Money precision

Normalized codes can resolve to built-in currencies with different precision. Previously, unknown codes such as ZEUR and ZUSD registered as crypto currencies with eight decimal places. Built-in EUR and USD use two, and JPY uses none. This affects instrument quote currencies, REST fill commissions, and derived PnL.

Account balances retain eight decimal places because their parsers construct the currency directly rather than use the registry. The Futures flex portfolioValue entry and account-wide USD margin entries also use this eight-decimal currency. They previously used two-decimal USD, so their precision increases without loss.

Spot markets

NautilusTrader uses normalized, slash-separated symbols for Kraken Spot instruments. The adapter translates them to Kraken's native format internally.

Instrument ID format:

from nautilus_trader.model import InstrumentId


InstrumentId.from_str("BTC/USD.KRAKEN")  # Spot BTC/USD
InstrumentId.from_str("ETH/USD.KRAKEN")  # Spot ETH/USD
InstrumentId.from_str("SOL/USD.KRAKEN")  # Spot SOL/USD
InstrumentId.from_str("BTC/USDT.KRAKEN")  # Spot BTC/USDT
InstrumentId.from_str("ETH/BTC.KRAKEN")  # Spot ETH/BTC (normalized from ETH/XBT)

Futures markets

Kraken Futures symbols use contract prefixes:

  • PI_: Perpetual inverse contracts (for example, PI_XBTUSD).
  • PF_: Perpetual linear multi-collateral contracts (for example, PF_XBTUSD).
  • PV_: Perpetual vanilla contracts (for example, PV_XRPXBT).
  • FI_: Fixed-maturity inverse contracts (for example, FI_XBTUSD_230929).
  • FF_: Fixed-maturity linear contracts.

Kraken's ticker symbol reference lists the main contract prefixes. Use the returned instrument catalog to determine which contracts are available. Example symbols can refer to expired or unlisted contracts.

Instrument ID format:

from nautilus_trader.model import InstrumentId


InstrumentId.from_str("PI_XBTUSD.KRAKEN")  # Perpetual inverse BTC
InstrumentId.from_str("PI_ETHUSD.KRAKEN")  # Perpetual inverse ETH
InstrumentId.from_str("PF_XBTUSD.KRAKEN")  # Perpetual linear multi-collateral BTC

Data capabilities

Subscriptions (real-time)

Data typeSpotFuturesNotes
QuoteTick✓✓Spot ticker; Futures L2 book.
TradeTick✓✓
OrderBookDeltas✓✓Spot L2/L3 and Futures L2 updates.
OrderBookDepth--Use OrderBookDeltas with depth 10.
Bar✓-Spot WS OHLC channel. See bar section.
MarkPriceUpdate-✓From futures ticker feed.
IndexPriceUpdate-✓From futures ticker feed.
FundingRateUpdate-✓Perpetuals only.
InstrumentStatus--Live clients do not emit status updates.

Requests (historical)

Data typeSpotFuturesNotes
TradeTick✓✓
Bar✓✓
OrderBook (snapshot)✓✓Via HTTP depth endpoint.
FundingRateUpdate-✓Client-side start/end/limit filtering.

L2 book checksum validation

Kraken's Spot L2 book channel sends a CRC32 checksum for the top ten levels on each side in snapshots and updates. The adapter validates it by default against a local shadow book, using pair_decimals for prices and lot_decimals for quantities from AssetPairs. Some pairs have a wire price scale one digit finer than their tick size. The instrument retains that finer scale in its metadata so checksum rendering does not truncate price digits. Kraken Futures book messages carry no checksum.

Recovery and stream identity

On a checksum mismatch, the adapter emits a Clear delta, drops the shadow book, and unsubscribes and resubscribes the symbol at its configured depth with a snapshot. It ignores updates until that snapshot arrives. Every book unsubscribe includes its depth: Kraken keys subscriptions by symbol and depth, and defaults an omitted unsubscribe depth to 10.

Recovery runs serially with user subscription changes, so stale recovery never cancels a replacement subscription. The subscribe request identifies each stream. The adapter accepts frames only from the symbol's latest stream after Kraken confirms that request, dropping frames from replaced subscriptions and superseded recoveries. A snapshot changes the book only after it parses and applies successfully. A recovery request made before an accepted snapshot or reconnect sends nothing after that event.

The adapter also emits a Clear delta when it drops a shadow book outside frame processing. This occurs on these events:

  • Reconnect.
  • Confirmation of a new stream.
  • Rejection of the latest subscribe request.
  • Detection of an unconfirmed latest request by the snapshot watchdog.

Missing snapshots and rejected subscriptions

The snapshot watchdog is the only retry mechanism for book recovery. It runs even with checksum validation disabled, because it also recovers streams that never receive a snapshot. Each replacement subscription starts a fresh wait rather than inheriting its predecessor's retry count.

If no snapshot arrives within 10 seconds, the data client requests it again. It doubles the wait between requests (10, 20, 40, 80, and 160 seconds), up to five requests. At the cap, it logs an error and stops retrying. The book stays cleared and updates are dropped until a snapshot arrives. A subscription change or reconnect starts recovery again.

Kraken's rejection of the latest subscribe request clears any held book and logs the venue's reason and the next request time at error level. The rejection counts as one failed request, so the next attempt follows after 20 seconds. Four more rejections exhaust the allowance in about five minutes. A transient rejection can therefore recover on the next attempt after 20 seconds. Rejections of superseded requests are ignored.

On reconnect, the adapter retires its recorded subscribes and replays each subscribe with its original request ID. Replay responses match no active request. If Kraken rejects a replay, the watchdog detects the missing snapshot within its base wait of 10 seconds.

Repeated checksum mismatches

Three mismatches on one instrument without a valid update between them disable validation for that instrument and log an error. The adapter keeps its book as received, preventing a resubscription loop when Kraken hashes it differently. A valid snapshot does not reset the mismatch count.

To disable L2 checksum validation:

config = KrakenDataClientConfig(
    validate_l2_checksum=False,
)

L3 order book (market-by-order)

Kraken exposes Spot per-order book data via the WebSocket v2 level3 channel at wss://ws-l3.kraken.com/v2. This gives venue order IDs, per-order quantities, and true incremental events (add, modify, delete). The adapter hashes each venue order ID into the u64 BookOrder.order_id field used by NautilusTrader.

The adapter queues orders at each price level by order timestamp, using arrival order to break ties. When an order joins ahead of resting orders, the adapter can emit synthetic Delete and Add deltas for the affected suffix to preserve downstream queue order.

With queue_position=True, backtest and sandbox execution treat these synthetic deletes as order cancellations. The re-adds do not restore the removed quantity ahead, so simulated orders can fill too early.

Prerequisites

L3 subscriptions require Spot API credentials with WebSocket interface - On permission, which the adapter uses to obtain an authentication token. Pass the credentials to KrakenDataClientConfig:

from nautilus_trader.adapters.kraken import KrakenDataClientConfig

config = KrakenDataClientConfig(
    api_key="YOUR_KEY",
    api_secret="YOUR_SECRET",
)

Then subscribe with book_type=BookType.L3_MBO:

from nautilus_trader.model import BookType

# Inside a registered strategy or data actor:
self.subscribe_book_deltas(
    instrument_id=instrument_id,
    book_type=BookType.L3_MBO,
    depth=1000,  # valid: 10, 100, 1000
)

Valid depths are 10, 100, and 1000. A depth of 0 uses 1000.

CRC32 checksum validation

By default, the adapter validates the CRC32 checksum on each L3 snapshot and update when Kraken provides one. On mismatch, it emits a Clear delta, clears local L3 state, refreshes the auth token, and resubscribes so Kraken sends a fresh snapshot. To disable validation for benchmarking:

config = KrakenDataClientConfig(
    api_key="...",
    api_secret="...",
    validate_l3_checksum=False,
)

Storage recommendations

OrderBookDelta carries order_id: u64 in its Arrow schema, so ParquetDataCatalog stores L3 data with the same schema as L2. L3 produces more events per instrument.

  • Use a smaller query-session chunk_size (for example, 50_000) to target smaller streaming batches. Timestamp-aligned batches can exceed that target. The setting does not control file size or parallel reads.
  • Set compression="zstd" in DataCatalogConfig to compress stored data.
  • The Parquet catalog partitions data by instrument by default.

Order capabilities

Order types

Order typeSpotFuturesNotes
MARKET✓✓Immediate execution at market price.
LIMIT✓✓Execution at specified price or better.
STOP_MARKET✓✓Conditional market order (stop-loss).
MARKET_IF_TOUCHED✓✓Conditional market order (take-profit).
STOP_LIMIT✓✓Conditional limit order (stop-loss-limit).
LIMIT_IF_TOUCHED✓✓Spot: take-profit-limit; Futures: take_profit with limit_price.
TRAILING_STOP_MARKET✓-Trailing stop with trailing_offset.
TRAILING_STOP_LIMIT✓-Trailing stop-limit with limit_offset.

Time in force

Time in forceSpotFuturesNotes
GTC✓✓Good Till Canceled.
GTD✓-Good Till Date (Spot only, requires expire_time).
IOC✓✓Immediate or Cancel.
FOK✓-Spot limit orders only.

Market orders are inherently immediate and do not support time-in-force. IOC only applies to limit-type orders.

Execution instructions

InstructionSpotFuturesNotes
post_only✓✓Available for limit orders.
reduce_only✓✓Spot requires a margin account and resolved leverage.
quote_quantity✓-Spot only. Volume in quote currency (viqc); REST routed.
display_qty✓-Spot only. Iceberg orders (displayvol).

Trigger types

Conditional orders support these trigger price references:

Trigger typeSpotFuturesNotes
LAST_PRICE✓✓Default. Last traded price.
INDEX_PRICE✓✓Broader market index price.
MARK_PRICE-✓Futures only.

The adapter rejects unsupported trigger types (e.g., BID_ASK) at submission time rather than silently coercing them.

Batch operations

OperationSpotFuturesNotes
Batch submit✓✓Spot chunks at 15 orders. Futures chunks at 10.
Batch modify-✓Futures HTTP method only. Execution sends one command.
Batch cancel✓✓Auto-chunks into batches of 50.

Futures batch cancels split repeated venue or client order IDs into separate requests so each reply identifies one command UUID. Other chunks contain up to 50 orders.

Cancel all orders:

  • Spot selects matching open and in-flight orders for the requested instrument, with or without a side filter. It cancels them by explicit order ID. Thus, a request never reaches another instrument. In-flight orders are included because the venue can have accepted an order the cache still records as submitted.
  • Futures uses the venue's symbol-scoped bulk cancellation when no side filter is given, and selects matching cached open and in-flight orders by explicit order ID when one is.
  • Selected IDs go through the batch-cancel endpoint and are auto-chunked into batches of 50. Kraken keys the two identifier kinds separately, so venue order IDs are sent as orders and client order IDs as cl_ord_ids. The batch limit counts both together. Each cancel keeps the owning strategy of the order it targets, and aggregate or ambiguous responses are left to reconciliation rather than producing per-order outcomes.

Order modification

A modify's quantity is the order's new total, fills included, which is how Kraken Spot amends take order_qty. Kraken Futures reads a bare edit size as the open size, so the adapter sends qtyMode=ABSOLUTE with every futures edit that resizes the order, single or batch. Kraken Futures does not document its answer to a total at or below the filled quantity.

Kraken Futures reports each edit's outcome in editStatus.status. edited and filled confirm the edit, and the private feeds carry the update or the fills. These statuses refuse the edit and emit OrderModifyRejected: invalidSize, invalidPrice, insufficientAvailableFunds, makerProtectionOrderLimitExceeded, tooManySmallOrders, outsidePriceCollar, wouldNotReducePosition, orderForEditNotFound, orderForEditNotAStop, editAlreadyHeld, marketIsCancelOnly, and tooManyOrders, Kraken's open-order limit refusal and, until 12 November 2026, its Maker Protection hold-cap refusal, held edits included. The adapter also rejects an edit on statuses from its send-order status set that the edit documentation does not list: notFound, invalidOrderType, wouldCauseLiquidation, reduceOnlyWouldIncreasePosition, and the client order ID statuses. The send-order documentation lists each of them except reduceOnlyWouldIncreasePosition. An error response whose code refuses the request also rejects the edit: invalidArgument, requiredArgumentMissing, Json Parse Error, notFound, accountInactive, marketUnavailable, cancelOnly, authenticationError, nonceBelowThreshold, or nonceDuplicate, since each edit is sent once under a fresh nonce. For orderForEditNotFound, the Maker Protection guide states that "the edit's target is not resting: it had genuinely left the book by the time a held edit released, or its placement is still held." The adapter rejects such an edit as it rejects a cancel answered notFound.

A refusal does not establish that the order is still working. Kraken can refuse an edit by canceling the order, and the open-orders feed then closes it. If that update is missed, the order stays open locally until an open-order check or a restart reconciles it, since the Futures execution client does not reconcile on reconnect. Nor does a refusal establish that nothing applied: a refused reprice in a split amendment leaves the size reduction already applied, which arrives as OrderUpdated.

These outcomes stay unconfirmed, so the adapter logs a warning and emits no event:

  • selfFill: the Maker Protection guide documents that a self-matching edit that is not held removes the order being amended.
  • postWouldExecute: the edit documentation says the edited order would be filled upon placement and is canceled instead. A placement answered with it is still rejected.
  • iocWouldNotExecute: the edit documentation reports an edit applied as immediate-or-cancel with its remainder removed, while the 22 October 2026 changelog says a held order is no longer converted to immediate-or-cancel.
  • Any other status, such as one Kraken does not document.
  • Any other error code, including apiLimitExceeded, or none.

If no private update resolves such an edit, the in-flight check cancels the order locally once its retries run out, about 30 seconds on the default settings, even if the order still rests at Kraken. This classification covers responses served with HTTP 200, the only status Kraken Futures documents. A response with an HTTP error status stays unconfirmed whatever its body.

Position management

FeatureSpotFuturesNotes
Query positions✓✓Spot margin via OpenPositions; spot cash opt-in.
Position mode--Single position per instrument.
Leverage control✓-Spot REST tiers; per-order params={"leverage": N}.
Margin mode✓✓Spot/Futures cross margin; no isolated spot margin.

Order querying

FeatureSpotFuturesNotes
Query open orders✓✓List all active orders.
Query order history✓✓Spot paginates; Futures reads one history page.
Order status updates✓✓Real-time order state changes via WebSocket.
Trade history✓✓Execution and fill reports.

Contingent orders

FeatureSpotFuturesNotes
Linked order lists--Submitted lists contain independent orders.
OCO orders--Not supported.
Bracket orders--Not supported.
Conditional orders✓✓Stop and take-profit orders.

Maker Protection (Futures)

Kraken Futures Maker Protection holds placements and edits that would take liquidity on arrival. This eligibility rule took effect on 29 October 2026 at 08

UTC, as announced in the 22 October 2026 changelog. Before that boundary, eligibility followed order type: non-post-only limit placements were held even when they would rest. The Phase 3 rollout added 51 markets at the same time. The hold applies to every client on selected markets.

  • Window: The raw instrument field makerProtectionMillis gives the market's window, at most 100 ms. Read /instruments or /trading/instruments for the live market set; an absent or zero value means no delay. The adapter exposes no setting for it.
  • Exemptions: Orders and edits that would rest, post-only orders, and stop or take-profit trigger placements are not held. Orders fired by triggers are held unless post-only.
  • Self-trade prevention: A released order cancels any resting order of the same account it would match, overriding the configured strategy. The resting order's cancel reason is CANCELLED_BY_SELF_TRADE.
  • Held edits: A second edit while an earlier edit of the order is held is refused with editAlreadyHeld, and the order stays as it rests until the earlier edit releases.

Split amendments

When an edit both reduces size and reprices a resting order across the book, the size reduction applies immediately and preserves queue priority. Only the reprice waits for the hold to release. The order can fill at its original price during that window, up to the reduced size. Both changes keep the same venue and client order IDs.

The adapter emits OrderUpdated for each tracked open-order update that changes quantity or price. When the venue reports the reduction and reprice separately, the first update carries the reduced quantity at the original price. It restores the order's prior lifecycle status from PENDING_UPDATE, but does not establish that the requested price has taken effect. Read each update's quantity and price, and account for fills during the window. Do not treat the first update as confirmation of the whole edit.

Cancellation

Canceling a held order cannot prevent execution. Cancellations are not held, but the reply waits for the held order's release. The order matches as submitted, then cancellation removes any remainder that would rest. No API exposes a held-order state.

Outcome at releaseCancel reply
Resting remainder, including no fillscancelled
Full executionnotFound
IOC, FOK, or market order with no right to restnotFound
Order refused at releasenotFound

Neither reply establishes the order's terminal state. The adapter emits OrderCancelRejected for notFound; the order can still fill. Placement or amend responses, private updates, fills, and reconciliation establish the order's state and cumulative fills.

  • Order IDs: A held placement has no venue order ID until release. The adapter uses its full client order ID to cancel it.
  • Repeated and batch cancels: A second cancel returns notFound immediately while the first awaits release. Batch cancels apply these rules per instruction.
  • Cancel-all and dead-man switch: Own cancel-all and an externally armed cancelallordersafter apply cancellation at release and cannot prevent execution. Held targets are absent from the cancel-all result. A held amend's original order can remain resting until release, so a sweep reply does not prove every order is gone. The adapter does not arm the Futures dead-man switch.
  • Timeouts: The default timeout_secs is 30 seconds. A delayed or lost mutation response needs private updates or reconciliation to resolve it. The adapter does not automatically replay mutations.

Order-update feed

The fills stream supplies terminal full fills, so the adapter skips full_fill removals. For other tracked cancellations, a full is_cancel=true delta closes the order only after that stream accounts for the delta's cumulative filled quantity. Cancellation cannot overtake those fills.

Untracked cancellations produce status reports, except for skipped partial_fill removals:

Skipped partial_fill removalReason
Cancel-only messageNo cumulative filled quantity.
No tracked identityNo resolvable or registered order.

The adapter skips cancel-only full_fill and partial_fill removals: full fills close through the fills stream; partial-fill remainders need reconciliation unless a full order delta arrives. Other cancel-only reasons close a tracked order immediately; later fills use fill reports for reconciliation.

Reconciliation

Held orders are absent from /openorders. Before treating an order as missing, mass status, open-only report runs, and targeted queries check POST /orders/status. It covers open orders and orders filled or canceled in the last 5 seconds.

  • Identity: Queries use both client order ID forms. Bulk reads match a cached venue order ID directly. Otherwise, exactly one queried cached order and one report with an uncached venue ID must match the echoed ID, instrument, and side. Placement time must be no more than 5 seconds before order creation, allowing clock skew while excluding older reused or shortened IDs.
  • Ambiguity: Two reports echoing different forms of one order's ID are ambiguous. Unmatched or ambiguous reports are withheld with a warning naming the reason. Instrument-scoped runs keep only that instrument.
  • Duplicate reports: The client-ID query returns every order holding that ID. Reports already present in open orders or history receive the cached client ID and appear only once, retaining time-in-force, post-only, and trigger fields absent from the status window. A later window state updates an open report's status, quantities, prices, cancel reason, and update time; window pricing rules then apply. Closed reports keep their state.
  • State precedence: Venue-ID and client-ID queries can return different states of one order. The adapter prefers a closed state, then the later venue update, then the larger filled quantity, regardless of request order. Identity and pricing checks apply to the retained report.
  • Fill prices: The window supplies none. Bulk reads withhold fully executed orders with a warning; targeted queries price them from recent fills or fail so reconciliation defers them. Executions are never inferred at the order price. Canceled orders with executions remain reportable because reconciliation waits for their fills. Mass status marks the set incomplete for any withheld window report.

Order routing (Spot)

The Spot execution client routes order submission, modification, cancellation, and batch cancellation through Kraken's authenticated WebSocket v2 trade channel by default. It falls back to REST when the WebSocket is inactive. Set use_ws_trade=False on KrakenExecutionClientConfig to route these operations through REST.

Order shapes routed via REST

Kraken's Spot WebSocket v2 add_order method supports these shapes, but the adapter routes them through REST:

ShapeAdapter behavior
FOK time in forceThe WebSocket parameter builder does not encode FOK.
Trailing stop / stop-limitThe WebSocket parameter builder does not encode trailing offsets.
Iceberg (display_qty)The WebSocket parameter builder does not encode iceberg orders.
Quote-quantity ordersWS supports non-margin buy market orders; the adapter uses REST.

Mixed-symbol order lists also use REST because Kraken's WebSocket batch_add request requires one shared symbol. Unsupported trigger references fall back to the REST path, which rejects them locally before sending a request to Kraken. For Spot margin orders, use REST as described under Spot margin trading.

The per-call params={"use_ws_trade": False} override forces a single command through REST regardless of the configured default. Set it on SubmitOrder, ModifyOrder, CancelOrder, SubmitOrderList, or BatchCancelOrders.

WebSocket request timeout

When a WebSocket round-trip exceeds ws_request_timeout_secs (default 5), the venue outcome remains unknown. Submit, modify, cancel, and batch-add requests remain in flight without a terminal rejection. The dispatcher retains the request ID so a delayed matching response can still apply the normal success or definitive rejection handling.

Submit and batch-add timeouts also send a best-effort compensating cancel over the same WebSocket for every affected client order ID. This cancel limits exposure if Kraken accepted the order but delayed its response. It does not replace the unknown outcome with local terminal state.

Stream updates and the live execution reconciliation engine resolve orders when no matching response arrives. Targeted status queries can resolve modify or cancel requests that already have a venue order ID. A matching response or execution client shutdown retires the retained request correlation.

Set ws_request_timeout_secs comfortably above your observed round-trip latency. A premature timeout can send a compensating cancel for a submit or batch add that Kraken accepted.

WebSocket order-routing options

KrakenExecutionClientConfig exposes:

OptionDefaultDescription
use_ws_tradeTrueRoute orders via WS when the trade channel is active.
ws_request_timeout_secs5Seconds to wait for a Spot WS order response.

Reconciliation

Both execution clients reconcile local orders, fills, positions, and account state with Kraken at startup and during operation.

Bounded reports

When reconciliation supplies a lookback, both execution clients derive one cutoff for every historical query and record it on the mass status through set_report_window. A moving cutoff could combine reports that never existed together at the venue.

Declaring the cutoff enables the engine's bounded-history rules. An incomplete set still reconciles the reports received, with a warning. The completeness flag qualifies the set rather than blocking reconciliation.

Scope and read failures

An in-scope open order or position that cannot be resolved to an instrument or parsed fails the read on both clients. Omitting it would tell reconciliation that the venue never held that order or position.

Futures makes one exception: an untouched reduce-only stop or take-profit can have no unfilled size until it fires. If its contract has no open position from which to size it, the read skips the order and its history rows with a warning and marks the set incomplete. A failed open-position read fails the order read too. A single-order status lookup for that trigger fails while it is skipped, so reconciliation defers it.

Both clients return no rows for a query scoped to an instrument they do not hold. Spot and Futures share the KRAKEN venue, so either client can receive a query for an order it did not route. Single-order status lookups and query_order inspect only the command's instrument. Unresolved or unparsable records on another instrument cannot fail that scoped read, though a lookup cannot rule out an order such a record may name. A Futures history row of a documented kind that names both its order and a contract resolving to another instrument is outside the read and does not count. See Order history and pricing.

Other gaps mark the set incomplete: closed or historical orders and fills that cannot be parsed, or whose instruments cannot be resolved. Position records do not contribute to the completeness flag. In-scope position failures fail the read.

A venue order ID that is empty, blank, or not ASCII cannot be represented, so a report row carrying one counts as unparsable. A stream order update or fill carrying one is dropped and the order waits for a later frame or reconciliation. A status report can restore a dropped fill's quantity as an inferred fill, with a synthetic trade ID and an inferred price. A fill read supplies the real ones only if it arrives before or with that report. Nothing ties a later real fill to the inferred fill, so it can apply as a second fill and overstate the filled quantity until the mass status at the next startup corrects it.

A successful submit or edit response naming the order only by such an ID leaves the outcome ambiguous: the command is not rejected, and the streams or reconciliation resolve the order. The in-flight check's query_order needs a venue order ID, so if a submitted order's stream frames are lost too and no open check (open_check_interval_secs) reads it before the in-flight retries run out, SubmissionRecoveryPolicy::ResolveLocally closes it locally, even while the venue holds it. The default SubmissionRecoveryPolicy::RetainUnresolved instead leaves it unresolved for later venue evidence.

query_order reads open orders only, so it emits no report for an order the venue has closed. Under RetainUnresolved, a cancel or modify timeout restores the prior order status. When periodic open-order checks are enabled, bulk history in full-history mode or a targeted status query in open-only mode can recover the lost terminal update, subject to the configured lookback.

Single-order lookups

A single-order status lookup that finds no report tells reconciliation that the venue has no such order. Full-history reconciliation can resolve the order on that answer; open-only checks keep it open. The lookup gives that answer only from a read that rules the order out, and otherwise fails, so reconciliation defers the order:

  • A complete read rules out any order it could have returned. A held futures order shows only in the orders-status window, which the Futures lookup reads for a cached order before answering.
  • A read that skipped a row, including one whose instrument the client cannot resolve, rules out an order with a venue order ID that no skipped row carries. A skipped row that names no order, or any row of an undocumented history event kind, rules out none.
  • A lookup on an instrument of the other product reads complete, since the other client answers for its orders. One on an instrument of the client's own product that it does not hold reads nothing and rules out none.
  • A read cut short rules out an order placed after the oldest event it holds, by more than a 60-second clock skew allowance, taking the earlier of the order's creation and acceptance times. Futures history pages are newest first, so a page that hands back a continuation token reaches back to its oldest event. A spot closed-order read stopped at its page cap rules out none.

In full-history mode, an order a read cannot rule out is deferred again on every open-order check. In open-only mode, another targeted attempt requires a fresh missing-check budget. On Futures each such lookup draws one order-history token.

Spot pagination limits

Spot closed-order and fill reads advance an offset until Kraken returns an empty page, with a cap of 500 pages per read. Reaching the cap logs a warning:

  • Startup mass status records the order and fill reads' completeness in its report window, so the engine sees the truncated set as incomplete.
  • generate_order_status_reports and generate_fill_reports return the records read up to the cap without exposing a completeness flag.
  • A single-order status lookup that finds nothing in a closed-order read cut short by the cap fails, so reconciliation defers the order.

Spot reconciliation

Order status reports

  • Open orders: Fetches all currently active orders.

  • Closed orders: Fetches historical orders with pagination support.

  • Time-bounded queries: Supports filtering by start/end timestamps.

  • Startup mass status reads closed orders alongside open ones, so an order that reached a terminal state while the node was down is reconciled. The reconciliation lookback bounds the read, and a closed-order read cut short by the page cap leaves the mass status incomplete.

  • A report carries the order's own prices, not the row's top-level price. That field is the average fill price and reads zero on an unfilled order. The report's avg_px comes from cost and vol_exec.

    The limit comes from descr.price for a limit order and descr.price2 for a stop-loss-limit or take-profit-limit order, or a trailing-stop-limit order once misc marks it stopped. A trailing-stop-limit's limitprice holds the peak price, not its limit. A market, settle-position, stop-loss, take-profit or trailing-stop order carries no limit.

    The trigger comes from stopprice, which a stop-loss, take-profit, stop-loss-limit or take-profit-limit order fills only once triggered, so descr.price, as AddOrder takes it, stands in before. A zero or relative price reads as none.

  • An untriggered trailing-stop-limit order has no absolute limit, so its report carries no price, and an order the cache does not hold cannot be rebuilt from it until it triggers.

  • A take-profit-limit order whose trigger sits above a buy limit or below a sell limit cannot be a LimitIfTouched order, so the row fails naming both prices. An open row fails the read; a closed row is skipped and leaves the set incomplete.

  • An executions frame states the order's price only when it carries limit_price, never at a fill price.

Fill reports

  • Trade history: Fetches execution history with pagination.
  • Time-bounded queries: Supports filtering by start/end timestamps.
  • All fill types: Market, limit, and conditional order fills.

Pair spelling

  • Kraken spells a pair two ways: the AssetPairs key (XXBTZEUR), used as the instrument raw_symbol, and the altname (XBTEUR). OpenPositions returns the key, while OpenOrders and TradesHistory return the altname.
  • The adapter resolves both spellings, so an order or fill on a legacy-named pair is reported.
  • A read scoped to one instrument resolves each row and compares instrument IDs instead of the cached raw_symbol and venue spelling. Thus, it returns that pair's own records whichever way Kraken spells it.
  • A read scoped to an instrument the client does not hold returns nothing. Spot and futures IDs share the KRAKEN venue, so a futures ID can reach the spot client and the reverse. Neither falls back to returning every instrument's records. A single-order lookup on an unheld instrument of the client's own product rules out no order.
  • A spot instrument whose altname differs from its AssetPairs key carries the altname in its info map, so a client whose instruments arrive through cache_instrument or cache_instruments resolves altname-spelled records without refetching AssetPairs.
  • On an unscoped read, an open order whose pair cannot be resolved to a cached instrument fails the read, rather than being omitted from an otherwise successful one. A scoped read skips a record it cannot resolve, which may be another instrument's, and a single-order lookup cannot rule out the order it names.
  • A closed order or fill that cannot be resolved is logged as a warning and skipped, preserving the records that do resolve. Historical records routinely outlive the loaded instrument set.

Account balances

  • Wallet balances: Fetched from POST /0/private/BalanceEx, which reports the total and held (hold_trade) amount per asset. The held amount populates AccountBalance.locked, so free excludes funds Kraken has reserved against resting non-margin Spot orders. For accounts with a credit line, net credit (credit - credit_used) is included in AccountBalance.total, so free matches Kraken's available balance of balance + credit - credit_used - hold_trade.
  • Zero balances: An asset Kraken lists at zero is reported at zero rather than omitted, on both spot and futures. The engine only ever inserts balances, so a currency left out of a snapshot keeps its previous value. On futures the zero joins the per-currency sum, so a funded wallet alongside an empty one of the same asset reports the funded amount. An asset Kraken drops from the response entirely still keeps its last reported value.

Margin position reports

With spot_account_type=AccountType.MARGIN:

  • Open positions: Fetched from POST /0/private/OpenPositions and aggregated by pair into PositionStatusReport entries. Kraken returns one entry per lot, so opposing lots for the same pair net into a single report.
  • Entry average: Each report carries avg_px_open, derived from the lot cost and vol fields and weighted by the volume still open. Long and short lots are averaged separately, so the reported average describes the side that survives netting. Reconciliation needs this value to open a position from a report when the cache holds no order or fill history for it.
  • The average is marked AvgPxReconciliation::OpeningOnly, because Kraken closes margin lots FIFO and drops a fully closed one from OpenPositions. After a partial close the average therefore describes the lots that remain open rather than the opening fills, and would not match a netting position's average. Reconciliation uses it to open a position from flat and never compares it. Futures keeps the default, since that endpoint reports one netted position whose price Kraken documents as the average entry price.
  • No synthetic FLAT cleanup: OpenPositions reports leveraged positions only, so an unleveraged spot holding never appears there and its absence is not evidence that the position is closed. The bulk read reports only what the venue returns.
  • Margin balances: POST /0/private/TradeBalance is called alongside the account-state refresh. Used margin populates MarginBalance.initial, while equity and free margin populate the summary balance (see Spot margin trading).

A position closed while the node was down can recover from explicit closing fills even when reconciliation_lookback_mins excludes its opening trade. A fully closed margin lot is absent from OpenPositions, but a complete bounded history can still close its retained position when the closing order's normal routing resolves to that position. The fills record closing PnL and fees.

This uses the shared engine's retained closing recovery rules. An incomplete mass status withholds recovery. Eligible closing fills apply independently; other skipped or inferred executions do not veto them. Offline additions to a position, re-entry, corrections, and mixed explicit/inferred histories may require manual reconciliation.

When recovery is withheld, the order can reach FILLED while the cached position and its economics remain unchanged. Startup then logs a warning naming the account, the pair, and the position, where one resolves. A periodic position check does not recover that close: margin mode declares no bulk position coverage, so the check skips the instrument and logs at debug level. The mismatch can persist across restarts because the closing order is already in sync, and a restart with the order cached does not repeat the warning. Reconcile such a position manually.

Leaving reconciliation_lookback_mins unset avoids bounded order-only projection. A closing order already in the cache, such as a strategy exit submitted before the outage, then recovers into its position. The fill applies to the cached order and closes its position.

It is not a general remedy, because a closing order absent from the cache is attributed to the EXTERNAL strategy and keys a netting position by instrument and strategy. Unless the cached position is EXTERNAL-owned or the instrument is claimed through external_order_claim, that recovered fill opens a second, opposite position. It does not close the cached one. Net exposure reaches zero, but the stale position and its realized PnL remain.

Cash-mode recovery also depends on position-report coverage:

  • With use_spot_position_reports=False, the default, or for an instrument outside spot_positions_quote_currency, the client declares no bulk position coverage. Eligible explicit closing fills recover retained exposure and economics only when the instrument passes the rules above. Otherwise, its fills remain order-only. The periodic check skips the instrument.
  • For a covered instrument, startup reports a cached open LONG position as FLAT when the wallet shows its base asset as flat (see Spot position reports (cash mode)). A closing fill in the startup reports then closes the position with its PnL and fees when the closing order is cached or claimed by the position's strategy. A closing order that is neither cached nor claimed opens an offsetting EXTERNAL position instead, as above. A closing fill the reports miss, because it predates the lookback window or its row cannot be parsed, is inferred from the order report without a fee.
  • Where startup withholds that FLAT, the instrument carries no position report, so startup projects the closing fill order-only. A periodic position check, when enabled, does not apply the fill either. With generate_missing_orders enabled (the default), it falls back to a synthetic order at the cached average entry price, attributed as above, so the closing PnL and fees are not recorded.

Futures reconciliation

Client order IDs

Futures orders are sent with their full client order ID: Kraken Futures takes up to 100 characters, and an order whose ID is longer is denied before it is sent, with every other open member of its order list. The venue reports a client order ID it already holds, or one too long or otherwise invalid, as a send status that rejects the order.

A cancel or edit names the order by one identifier: its venue order ID when known, else its full client order ID. An edit response reads the order ID under the documented orderId key, and under order_id as well.

Open-order and fill reports read the client order ID under the documented cliOrdId key, and under cli_ord_id as well. An echoed ID that is empty or not a valid client order ID, such as one another tool on the account sent, names no order.

A futures order sent with its ID shortened to O and its last 17 characters, as a spot ID longer than 18 characters is unless it is a UUID, is held under that form. Every REST report and fill of an order the cache indexes by venue order ID carries the cached client order ID, whatever the venue echoes, and the orders-status window is asked about a held order under both forms. A cancel or edit of such an order reaches it only by its venue order ID; one sent before a report carrying that ID reaches the cache names no order at the venue and is rejected.

A targeted single-order query takes the report carrying the order's venue order ID when known. Otherwise a row is the order's when it echoes the client order ID in either form, on the order's instrument and side, placed no more than five seconds before the order's creation; an older row is another order whose ID shortens alike or that reused the ID. A fill carries no placement time, so its fill time stands in, which rules out only a fill executed before the order's creation. A row or fill of a venue order the cache indexes for another order never fits, whatever it echoes, since that order's full ID can be this order's shortened one. With the venue order ID unknown, the query fails when one read holds rows of two venue orders that fit, or a fitting row of a venue order the cache indexes for no order that echoes the full ID of another cached order sent without a venue order ID, on that order's instrument and side and placed no more than five seconds before its creation, or, no row fitting, when the recent fills that fit belong to two venue orders, include such a fill, or fall short of the order's quantity; with it known, the query fails when no row or fill carries it and a fitting row or fill of another venue order appears. Either way reconciliation defers the order rather than taking a row or reporting the order missing.

Order status reports

The adapter returns open orders and, when open_only=False, historical closed and filled orders. Historical reads have the limits below.

Kraken Futures has no time in force or post-only field: apart from a rejection reason, only an order's type states them. It documents the ioc and post types in the send-order response and the order history (IoC and Post), but not in the open-order read (lmt, stop, take_profit) or the order feed (limit, take_profit, stop), and the orders-status window states no time in force or post-only flag (its type is only ORDER or TRIGGER_ORDER). Reports take these values as follows:

  • A read with open_only=False takes an open order's time in force and post-only flag from the newest readable history row of that order on the page, mapped as in Order history and pricing.
  • The HTTP client's submit_order reports from the open-order read when it lists the order, otherwise from the send-order response's first order event, or from history when the response carries no event. If that first event carries an order, orderTrigger, or orderPriorExecution, its type sets the time in force and post-only flag: ioc is IOC, and post is post-only GTC. A snapshot report without such a payload keeps the snapshot's values. A history report uses the mapping in Order history and pricing.
  • An open-only read, an open order with no readable row on the page, and an order feed delta for an order the adapter does not track map an ioc or post type the same way, so every documented value reports as GTC and not post-only.
  • The orders-status window reports GTC and not post-only.

A resting post-only order adopted from a report that does not state it keeps GTC and not post-only: no later report changes an adopted order's time in force or post-only flag.

Order history and pricing

The adapter reads order lifecycle events from /api/history/v3/orders. Each read takes one page of up to 1000 events, the most the venue serves: Kraken /history endpoints share a pool of 100 tokens, replenished at 100 every 10 minutes. An order-history page costs one token, so a page that hands back a continuation token, in the body or the Next-Continuation-Token header, logs a warning and leaves the set incomplete rather than reading further. A single-order status lookup can still report a cached order absent when it was placed after the page's oldest event by more than the clock skew allowance. See Single-order lookups.

The history lists every lifecycle event. The read returns one report per order: the open-order snapshot, its time in force and post-only flag taken as described above, if the venue still lists it. Otherwise, it returns the latest history state. A closed order is not reopened by an open state stamped later, such as a refused edit logged after a cancel.

The contract name is resolved as the venue spells it, exactly first and then case-insensitively. A spelling that matches two contracts case-insensitively resolves to neither. The history carries no trigger price. Thus, a stop order is reported as the limit or market order it executes as once triggered. Venue-initiated orders (liquidation, assignment, hedge assignment, unwind, block, RFQ) are reported as market orders.

The order type is the only place the history states a time in force. IoC and HedgeImmediateOrCancel rows are reported as IOC, FillOrKill rows as FOK, and Post rows as post-only GTC. Other rows are reported as GTC. A FOK row comes from another tool, since the adapter does not submit FOK on Futures.

The adapter skips unrepresentable rows with a warning:

  • An unknown event kind.
  • A documented event kind whose payload does not decode.
  • An order type reported as Unknown or omitted.
  • An unknown direction.
  • A timestamp before the epoch.

A skipped row marks the set incomplete unless it is provably outside the read: the open-order snapshot reports its order, or a scoped read finds it names an order and a contract resolving to another instrument. Any other row whose order or contract cannot be read stays in scope, as does any row of an unknown event kind. A row with an invalid order ID names no order.

A skipped row in scope that is at least as new as the state an order would be reported from withholds that order, whether that state is open or closed, so an unreadable newest row cannot fall back to an older state. The page's other orders are still reported. A later lookup of the withheld order is deferred like any order a read cannot rule out. A row that names no order can withhold nothing, so its order's older state can still be reported in the incomplete set. A canceled or rejected row's state counts from its event. Any other state stamped before its event, such as a refused edit's, counts from the earlier stamp.

A decoded OrderNotFound carries no order state and is skipped without affecting completeness. A venue error returned under an HTTP success status fails the read, as does a body without an elements array or an element without the documented uid, timestamp and event.

A terminal history row with executions carries no average price. The adapter prices it from page fills that cover its filled quantity exactly, or from page fills plus the fills recorded on a cached order, again requiring exact coverage. A failed fills read counts as an empty page. Without exact coverage, a single-order query fails and a bulk read withholds the order, so reconciliation defers it instead of inferring executions at the limit price.

Startup history fallback

Startup mass status reads one history page alongside open orders. This recovers an order that reached a terminal state during downtime when that page contains it. A venue error body under an HTTP success status, regardless of its code, or HTTP 429 triggers a warning and fallback to open orders alone, with the set marked incomplete. Other HTTP errors, transport failures, and unparsable bodies fail mass status, as does a failed open-order read. A documented event whose payload does not decode does not: it is skipped as described in Order history and pricing.

Startup pricing safeguard

Mass status applies the same exact fill-coverage requirement to terminal history orders with executions. It withholds an uncovered order with a warning naming it and marks the set incomplete. Later reads still request only the latest fills page. They cannot page back to recover an older missing execution.

A withheld order's page fills remain when the cache holds the order, because the engine can reconcile those fills against it without a report. An uncached order's fills are withheld with the order, including an order the history read itself left without a report because a skipped row names it. A fill of such an order that echoes a cached order stays, since the engine applies it to that order by its client order ID.

Flat instruments

The position read returns open positions only, so an instrument with no position report is flat at the venue. The fills read is one page. A round trip with an opening fill older than that page leaves only its closing side. Without reconciliation_lookback_mins, the engine applies every kept fill to positions. This can open a position the venue does not hold.

To compensate, an unbounded startup read nets the fills of every order on the read pages that the cache does not hold on a flat instrument, open orders included. When they do not net to zero and a terminal history order is among them, the terminal orders are withheld with their fills, with a warning, and the set is marked incomplete.

Open orders stay, so an open order's fill can still open a position. An instrument with an open venue position is left to its position report. A bounded lookback leaves terminal orders to the engine, which projects fills with no position report onto order state only.

Fill reports

  • Fill history: Reads the latest /fills page, the last 100 fills across all futures contracts. Older executions are not returned.
  • Time filtering: Client-side filtering by start/end timestamps (parses RFC3339 timestamps).
  • All fill types: Maker and taker fills with fee information.

Position status reports

  • Open positions: Fetches all active futures positions.
  • Report fields: Side, average entry price, and position size from the REST snapshot. Kraken also returns unrealized funding, but PositionStatusReport does not expose it.

Account state

  • Balances: One entry per asset across wallets, as described under Currency codes.
  • Margins: One entry per currency, summed across wallets as balances are, at eight decimals. A flex wallet's requirement is in USD, from its initialMargin and maintenanceMargin. A single-collateral wallet's is in its currency, so a fi_xbtusd requirement is reported in BTC, and its available funds bound that currency's balance alone. A wallet without a usable currency contributes no margin entry, reports none of its assets as locked, and logs a warning.

Futures time filtering: The Kraken Futures fills endpoint does not support server-side time range filtering. The adapter implements client-side filtering by parsing fillTime fields and comparing against requested start/end timestamps.

Spot position reports (cash mode)

Set use_spot_position_reports=True in cash mode to report wallet balances as Spot positions. It defaults to False. Margin accounts use OpenPositions independently of this option (see Spot margin trading).

How it works:

  • When enabled, wallet balances are converted to PositionStatusReport objects.
  • Positive balances are reported as LONG positions.
  • Only instruments matching the configured quote currency are reported (default: USDT). The same filter decides which instruments the client declares bulk position coverage for, so an instrument quoted in anything else is never reconciled to flat from a missing report.
  • This prevents duplicate reports when the same asset is available with multiple quote currencies (e.g., BTC/USD, BTC/USDT, BTC/EUR).
  • At startup, the mass status also reports FLAT for each cached open LONG position on a covered instrument whose base asset the POST /0/private/Balance read shows as flat: the base has no row, or its rows sum to an amount that rounds to zero at the instrument's size precision. Every row of the base counts: its code in either spelling (XXBT, XBT), and a dotted code whose part before the last dot names the base, as is or once trailing digits are removed, such as XBT.F, DOT28.S, or EUR.HOLD for BTC, DOT, or EUR.
  • Kraken documents that read as net of pending withdrawals, so a withdrawal reduces it while still pending.
  • The FLAT is withheld, with a warning, when the rows of the base sum to a nonzero amount that no LONG report carries, such as a suffixed (XBT.F), staking (DOT.S), or hold (EUR.HOLD) balance. It is also withheld when an order report shows a SELL on the instrument that is not terminal, when a cached open or in-flight SELL on the instrument has no matching order report, when the instrument is missing from the cache, and for tokenized assets (xStocks), whose Balance key and units are not documented.
  • A row that counts toward the base of a position that can get this FLAT fails the startup mass status when it cannot be parsed or is negative. Other rows that cannot be parsed are skipped.
  • Periodic position checks get no such report, since a missing report there already means flat for a covered instrument.
  • A position reported FLAT with no closing fill in the startup reports, as after a withdrawal or a sale of the base through another pair, reconciles as a discrepancy, with or without a lookback. With generate_missing_orders enabled (the default), a position whose strategy claims the instrument closes at its cached average entry price, with no closing PnL or fee. Otherwise the synthetic order belongs to EXTERNAL and opens an offsetting position next to the strategy's. With generate_missing_orders disabled, startup stops on the unresolved position.

Configuration:

from nautilus_trader.adapters.kraken import KrakenExecutionClientConfig
from nautilus_trader.model import AccountId


exec_config = KrakenExecutionClientConfig(
    account_id=AccountId.from_str("KRAKEN-001"),
    api_key="YOUR_API_KEY",
    api_secret="YOUR_API_SECRET",
    use_spot_position_reports=True,
    spot_positions_quote_currency="USDT",  # Default
)

A strategy that closes reported Spot positions may sell your wallet holdings. Enable wallet-derived position reports only when your strategy handles those holdings.

Spot margin trading

Kraken Spot supports leveraged trading on selected pairs. AssetPairs advertises per-pair tiers in leverage_buy and leverage_sell. The adapter caches these at instrument-load time and validates REST orders against them before submission. Enable margin trading with spot_account_type=AccountType.MARGIN and set leverage through default_leverage or per-order submission parameters.

Use use_ws_trade=False for Spot margin orders. The adapter's WebSocket path forwards numeric leverage without checking the pair's cached tiers. Kraken's WebSocket add_order schema instead specifies a boolean margin field that selects the pair's maximum leverage. REST supports an explicit leverage parameter and the adapter's local tier checks.

Configuration

from nautilus_trader.adapters.kraken import KrakenExecutionClientConfig
from nautilus_trader.model import AccountId
from nautilus_trader.model import AccountType


exec_config = KrakenExecutionClientConfig(
    account_id=AccountId.from_str("KRAKEN-001"),
    api_key="YOUR_API_KEY",
    api_secret="YOUR_API_SECRET",
    spot_account_type=AccountType.MARGIN,
    use_ws_trade=False,
    default_leverage=3,  # Optional config-level default
    margin_balance_asset="ZGBP",  # Optional summary-display asset
)

margin_balance_asset controls only the denomination of the account-summary metrics returned by Kraken's TradeBalance endpoint (equity, free margin, used margin, etc.). Per-position figures from OpenPositions are always in the traded pair's quote currency.

Per-order leverage

Override the configured default on a single order via params:

from nautilus_trader.model import InstrumentId
from nautilus_trader.model import OrderSide
from nautilus_trader.model import Price
from nautilus_trader.model import Quantity


order = strategy.order_factory.limit(
    instrument_id=InstrumentId.from_str("BTC/USD.KRAKEN"),
    order_side=OrderSide.BUY,
    quantity=Quantity.from_str("0.01"),
    price=Price.from_str("50000.00"),
)
strategy.submit_order(order, params={"leverage": 5})

On REST, the adapter validates the tier against the pair's leverage_buy or leverage_sell before sending the order. An unsupported tier produces an OrderRejected event for a single-order submission without reaching Kraken. A malformed per-order leverage parameter, such as a string or a value outside [0, 65535], produces OrderDenied before submission on either route.

Reduce-only

Margin orders can carry reduce_only=True so they reduce an existing position without opening a larger opposite position. Set spot_account_type=AccountType.MARGIN and supply either default_leverage or per-order params={"leverage": N}. The adapter denies cash orders with reduce_only before sending them to Kraken.

Account state

When spot_account_type=AccountType.MARGIN, the execution client calls Kraken's TradeBalance endpoint during account refreshes. The live account state uses:

  • Equity (e) and free margin (mf) for the balance denominated by margin_balance_asset.
  • Used margin (m) for MarginBalance.initial. Maintenance margin is zero because Kraken does not return a separate maintenance-margin amount.

The lower-level KrakenSpotHttpClient methods request_margin_metrics() and request_account_state_with_metrics() return the full TradeBalance metrics dictionary for direct consumers. The live execution client does not attach that dictionary to AccountState.info.

Position reconciliation

Open spot margin positions are surfaced via POST /0/private/OpenPositions on each position_check_interval_secs tick. This path is independent of use_spot_position_reports (which is wallet-derived, cash-mode-only).

The spot client declares bulk position coverage per instrument, and only for instruments the read would actually enumerate: cash mode with use_spot_position_reports=True, and the instrument quoted in spot_positions_quote_currency (see Spot position reports, which applies the same filter). Under spot_account_type=AccountType.MARGIN the source is OpenPositions, which omits unleveraged lots, and cash mode without wallet-derived reports returns nothing at all. Wherever coverage is not declared, an absent report alone leaves the cached position untouched. Startup can still apply eligible explicit closing fills under the retained closing recovery rules.

Funding rates

The adapter receives funding rate data from the Futures ticker WebSocket feed, which provides relative_funding_rate and next_funding_rate_time for perpetual futures.

The adapter leaves FundingRateUpdate.interval as None because the ticker feed does not include a funding interval field. This does not mean the contract has no defined funding period. Kraken's linear multi-collateral contract specification defines hourly funding periods. Accrued funding settles at the end of the hour or when the net position changes.

Rate limiting

Each Kraken HTTP client applies an adapter-side request throttle. The default is five requests per second and max_requests_per_second can override it. This is a request-count throttle, not a complete model of Kraken's endpoint costs or account-tier budgets.

Kraken applies different venue limits to Spot and Futures:

  • Spot REST rate limits use a tier-dependent call counter. Ledger and trade history calls add 2, most other REST calls add 1, and order management uses a separate trading limiter.
  • Derivatives rate limits use endpoint costs and separate budgets for /derivatives and /history paths.

Kraken documents these Spot REST call-counter limits:

Spot tierMaximum counterCounter decay
Starter150.33/second
Intermediate200.5/second
Pro201/second

If the adapter's fixed request rate is too high for the endpoint mix and account tier, Kraken can still reject or throttle requests.

Reconciliation interval guidance

The execution engine's open_check_interval_secs and position_check_interval_secs settings create sustained private REST API load. Short intervals can exhaust Kraken's venue budgets even when the adapter stays below its configured requests-per-second throttle.

Use conservative intervals as a starting point, especially for a Spot Starter account:

from nautilus_trader.config import LiveExecutionEngineConfig


exec_engine = LiveExecutionEngineConfig(
    reconciliation=True,
    open_check_interval_secs=30.0,  # Conservative Spot Starter-tier starting point
    position_check_interval_secs=120.0,
)

Tune these values for the account tier, enabled reconciliation checks, and other clients using the same API key. If Kraken returns EAPI:Rate limit exceeded, increase the intervals or reduce max_requests_per_second.

Configuration

Data client configuration options

OptionDefaultDescription
product_typeSPOTProduct type for this client (SPOT or FUTURES).
environmentLIVETrading environment (LIVE or DEMO); demo only for Futures.
api_keyNoneAPI key for Spot L3 data.
api_secretNoneAPI secret for Spot L3 data.
base_urlNoneOverride for the Kraken REST base URL.
ws_public_urlNoneOverride for the public WebSocket URL.
ws_private_urlNoneOverride for the private WebSocket URL.
ws_l3_urlNoneOverride for the Spot L3 WebSocket URL.
validate_l3_checksumTrueValidate Kraken Spot L3 checksums and resync on mismatch.
validate_l2_checksumTrueValidate Kraken Spot L2 book checksums and resync on mismatch.
proxy_urlNoneOptional proxy URL for HTTP and WebSocket transports.
timeout_secs30HTTP request timeout in seconds.
heartbeat_interval_secs30WebSocket heartbeat interval in seconds.
ws_idle_timeout_ms10,000Data-silence timeout for the Spot v2 WebSocket; 0 disables.
max_requests_per_secondNonePer-client request throttle; default is 5 req/s.
transport_backendSockudoWebSocket transport backend.

Execution client configuration options

OptionDefaultDescription
account_idrequiredAccount ID for the Kraken account.
api_keyrequiredKraken API key.
api_secretrequiredKraken API secret.
product_typeSPOTProduct type for this client (SPOT or FUTURES).
environmentLIVETrading environment (LIVE or DEMO); demo only for Futures.
base_urlNoneOverride for the Kraken REST base URL.
ws_urlNoneOverride for the Kraken WebSocket URL.
proxy_urlNoneOptional proxy URL for HTTP and WebSocket transports.
timeout_secs30HTTP request timeout in seconds.
heartbeat_interval_secs30WebSocket heartbeat interval in seconds.
auth_timeout_secsNoneFutures WebSocket auth timeout; None uses the client default.
max_requests_per_secondNonePer-client request throttle; default is 5 req/s.
max_retries3Maximum retry attempts for retryable REST requests.
spot_account_typeCASHAccount type for spot trading; MARGIN enables leverage and reports.
default_leverageNoneDefault Spot margin leverage; REST sends "N:1" when set.
use_spot_position_reportsFalseReport wallet balances as positions; cash mode only.
spot_positions_quote_currency"USDT"Quote filter for spot wallet position reports and their coverage.
margin_balance_assetNoneSummary asset for TradeBalance; None defaults to ZUSD.
use_ws_tradeTrueUse Spot WebSocket v2 for order operations when active.
ws_request_timeout_secs5Spot WebSocket order response timeout.
transport_backendSockudoWebSocket transport backend.

For Spot margin, default_leverage applies when an order has no per-order leverage parameter. See Spot margin trading for submission and account-state examples.

Demo environment setup

To test with Kraken Futures demo (paper trading):

  1. Sign up at Kraken Futures demo and generate API credentials.
  2. Set environment variables with your demo credentials:
    • KRAKEN_FUTURES_DEMO_API_KEY
    • KRAKEN_FUTURES_DEMO_API_SECRET
  3. Read the credentials and pass them to KrakenExecutionClientConfig, then set environment=KrakenEnvironment.DEMO and product_type=KrakenProductType.FUTURES.

The Python examples show the complete demo and live LiveNode configurations.

Production configuration

Use KrakenDataClientConfig with KrakenDataClientFactory, and use KrakenExecutionClientConfig with KrakenExecutionClientFactory. The Python examples show the complete LiveNode.builder(...) configuration for data and execution clients.

API credentials

Live-node configuration objects do not read credential environment variables automatically. Pass api_key and api_secret explicitly to KrakenExecutionClientConfig and, for Spot L3 data, to KrakenDataClientConfig. Market data other than Spot L3 does not require credentials.

The lower-level Python HTTP clients load the following variables when their credential arguments are omitted. Rust applications can use KrakenCredential::from_env_spot() or KrakenCredential::from_env_futures(demo) to load them before constructing live-node configs.

Environment variableDescription
KRAKEN_SPOT_API_KEYAPI key for Kraken Spot live trading.
KRAKEN_SPOT_API_SECRETAPI secret for Kraken Spot live trading.
KRAKEN_FUTURES_API_KEYKraken Futures live API key.
KRAKEN_FUTURES_API_SECRETKraken Futures live API secret.
KRAKEN_FUTURES_DEMO_API_KEYAPI key for Kraken Futures (demo).
KRAKEN_FUTURES_DEMO_API_SECRETAPI secret for Kraken Futures (demo).

Demo environment: Only Kraken Futures offers a demo environment (https://demo-futures.kraken.com) for testing without real funds. Kraken Spot does not have a demo or testnet environment.

Use environment variables to store credentials, then pass their values into live-node configuration at the application boundary.

Authentication errors are reported when a private client connects or performs a private operation. Required permissions depend on the requested data or trading operation.

Contributing

To contribute to the Kraken adapter, see the contributing guide.

On this page

KrakenOverviewExamplesKraken documentationProductsSpot instrument feesBar streamingSupported intervalsBar emission latencySymbologySpot symbol normalizationCurrency codesMigration from earlier currency codesFutures wallet aggregationMoney precisionSpot marketsFutures marketsData capabilitiesSubscriptions (real-time)Requests (historical)L2 book checksum validationRecovery and stream identityMissing snapshots and rejected subscriptionsRepeated checksum mismatchesL3 order book (market-by-order)PrerequisitesCRC32 checksum validationStorage recommendationsOrder capabilitiesOrder typesTime in forceExecution instructionsTrigger typesBatch operationsOrder modificationPosition managementOrder queryingContingent ordersMaker Protection (Futures)Split amendmentsCancellationOrder-update feedReconciliationOrder routing (Spot)Order shapes routed via RESTWebSocket request timeoutWebSocket order-routing optionsReconciliationBounded reportsScope and read failuresSingle-order lookupsSpot pagination limitsSpot reconciliationOrder status reportsFill reportsPair spellingAccount balancesMargin position reportsFutures reconciliationClient order IDsOrder status reportsOrder history and pricingStartup history fallbackStartup pricing safeguardFlat instrumentsFill reportsPosition status reportsAccount stateSpot position reports (cash mode)Spot margin tradingConfigurationPer-order leverageReduce-onlyAccount statePosition reconciliationFunding ratesRate limitingReconciliation interval guidanceConfigurationData client configuration optionsExecution client configuration optionsDemo environment setupProduction configurationAPI credentialsContributing