Trading bot for Kraken: nonce, WebSocket, and rate limits

Does the bot lose orders during sharp market moves while positions remain open? We develop turnkey Kraken integration: stable connections, correct handling of access keys, and clear support procedures. We configure it so failures do not recur.

Blockchain Development Services

Frequently Asked Questions

Latest works

  • Development of a web application for FEEDME
    Development of a web application for FEEDME
    1376
  • Development of an online store for the company FURNORO
    Development of an online store for the company FURNORO
    1350
  • B2B Advance company logo design
    B2B Advance company logo design
    796
  • Development of a web application for Enviok
    Development of a web application for Enviok
    1088
  • AIDER company logo development
    AIDER company logo development
    1034
  • CRM development for Chasseurs
    CRM development for Chasseurs
    1130

Kraken API Integration: Where a Trading Bot Breaks

While the bot sends single requests, integration with Kraken API looks like a request–response exchange.

Under load and during sharp market movements, four classes of failures appear: signature and request sequence number mismatch, rate limit triggers, persistent channel disconnection, and divergence of local state from the exchange state.

The most costly is order loss. The response to a sent order did not arrive due to a timeout, the bot repeats the request — and a second order appears on the exchange instead of one.

The reverse scenario: the bot considers the order unexecuted and cancels it, although the trade has already gone through. Position and risk diverge from reality, while a "successful" operation remains in the logs.

An unstable connection with the exchange breaks things more quietly: the persistent channel goes silent without an explicit error, the stream of trades and order book stops updating, and the bot continues trading on outdated data.

Stuck orders — neither canceled nor executed — hang until manual intervention and distort position assessment.

Therefore, we start the audit of the trading loop not with code, but with logs: we reconcile the history of orders and trades, reproduce channel breaks, and examine the handling of failures and retries.

Then we analyze how each class of trading bot failures is closed — at the level of the operating scheme, not spot patches.

What a Managed Integration Delivers: Speed and Resilience

The exchange loop with Kraken has been redesigned so that every failure has a predictable outcome.

We separated market subscriptions and trading operations: a surge of load on the quote stream no longer slows down order sending, and a connection break does not leave the bot in an unknown state. Below are five effects that are measured, not felt.

  • Order execution. The request sequence number (nonce) is maintained strictly sequentially and restored after restart — "invalid signature" and "request expired" responses completely disappear from statistics.
  • Failure response. A channel break is detected within seconds, resubscription and state reconciliation proceed automatically; recovery takes minutes instead of hours of manual log analysis.
  • Eliminated failure class. The request rate is kept below exchange limits with a margin: instead of "too frequent" responses, a queue with smooth rate reduction works.
  • No duplicates. Each order has its own client identifier, so a retry after a timeout does not turn into a second trade — even if the exchange response did not arrive.
  • Position control. The local registry is reconciled with the exchange state after each break and on a schedule: divergence is visible before it becomes a loss.

During sharp market movements, behavior remains the same: the bot does not chase the price with a series of requests and does not open a position twice.

Trading bot resilience here is not a property of the code, but a consequence of each channel, limit, and identifier having an explicit behavior rule.

Connection Modes: Quote Stream, Polling, and Hybrid Scheme

The exchange provides market data and accepts orders through several interfaces, and the choice of connection mode determines how sensitive the strategy is to delays and how quickly it hits rate limits.

The quote stream arrives via subscription: the order book and trade tape update as changes occur, latency is minimal, but the connection breaks during network failures and technical maintenance on the exchange side, so it is always supplemented with a backup communication channel.

Periodic polling is predictable, easy to debug, and does not require maintaining a persistent connection — but each request consumes the shared request counter.

On strategies that recalculate a signal across multiple instruments, this counter is exhausted within seconds, and the bot starts receiving failures instead of data.

The hybrid scheme resolves this contradiction: market data comes as a stream, while requests remain only for placing orders, reconciling positions, and restoring state after a break.

Mode When it fits Limitations
Quote stream Scalping, arbitrage, reaction to price movement Connection break stops data reception; reconnection and state reconciliation needed
Periodic polling Low-frequency strategies, portfolio rebalancing, reports Consume limit on each request; delay between market snapshots
Hybrid Most working bots: data as a stream, actions via requests Harder to debug: two channels, shared event queue, unified limit accounting

We choose the mode based on the strategy's decision frequency, not implementation convenience — then rate limits remain a working resource, not a cause of failures. Next, we analyze how limits are calculated and how reconnection is structured.

Implementation Stages: From Audit to Handover for Management

Implementing a trading bot is not launching a script, but a sequence where each step relies on the result of the previous one.

We start with an audit of the current loop and finish with handover for management with regulations — so that the system remains predictable even after we leave.

  1. Integration audit. We analyze how access to Kraken is structured: where keys are stored, who uses them and how, how errors and request retries are handled.
  2. Exchange scheme. We fix the operating model: quote streams, order sending sequence, nonce handling, request rate limits, and behavior on connection break.
  3. Task-specific setup. Entry and exit rules, position size and daily risk limits, logging of every trade and signal.
  4. Historical data testing. Running the strategy on archived quotes taking into account commissions, slippage, and delays — it shows how the logic behaves in different market regimes.
  5. Test loop. Working on a real account with minimal volume: we verify actual responses, order execution, and recovery after breaks.
  6. Handover for management. Launch and stop regulations, monitoring and alerts, instructions for your team — plus an agreed support period.

Each stage ends with an artifact: exchange scheme, configuration, run report. They show exactly what was tested and on what data — this is the basis for handing the bot over to operation.

Implementation Artifacts: Schemes, Access Keys, Regulations

After the work is delivered, the client retains a set with which the integration can be developed and maintained by their own team without contacting the authors.

Below is a minimal set of artifacts for each Kraken API integration: not presentations, but working documents with versions and owners.

  • Data exchange schemes: sequence of requests and responses, subscription points for market streams, retry logic after a connection break, and stale request flag.
  • Environment configuration: parameters of test and production loops, request rate limits, timeouts, position size limits, and marking of what changes per task and what is fixed.
  • Access policies: role–action matrix, separation of keys for reading and trading, prohibition of fund withdrawal with a trading key, procedure for granting and revoking rights.
  • Key rotation regulation: replacement frequency, who initiates, how switching happens without stopping the bot, and what to do if a leak is suspected.
  • Integration documentation: module descriptions, message formats, exchange error breakdown, known limitations, and adopted workarounds.
  • Logs and instructions for the on-duty shift: which events are logged, how to distinguish a network failure from a logic error, and the procedure for stopping trading.
  • Rollback plan: how to restore the previous configuration, where state snapshots are stored, and within what time the bot returns to operating mode.

Case Study: How the Bot Stopped Losing Orders During Sharp Movements

Case study of a trading bot that placed and canceled orders on Kraken.

During sharp movements, it lost orders: some signed requests were rejected due to nonce counter desynchronization, some cancellations did not complete before the price moved away, and when the quote stream broke, the bot remained without an up-to-date order book for up to two minutes.

Over an 8–10 hour session, up to 14% of orders did not reach the exchange, and recovery after a failure took an average of 90 seconds — on a volatile market, that is enough to enter at an unfavorable price.

We started with accounting: every outgoing action, exchange response, and delay between them is logged. It turned out that the signature counter was incremented locally, and with parallel threads, some requests went out with an already used value.

Rate limit handling was also reactive: the bot received a rejection and retried, instead of distributing requests over time.

What We Changed

We installed a unified outgoing request dispatcher — it maintains a signature queue, issues nonce strictly sequentially, and proactively throttles the rate under exchange limits.

The quote stream was switched to a persistent connection with auto-reconnection and retrieval of missed order book updates, and cancellations were given priority over new entries: first we remove risk, then we look for an entry point.

What Became

The share of orders that did not reach the exchange fell from 14% to 0.3%, recovery time after a break — from 90 to 3–5 seconds, and rate limit rejections decreased approximately 40-fold.

Most importantly: the bot's behavior no longer depends on the market regime — at peaks, the delay of signing and sending stays within fractions of a second.

What to Do If the Bot Already Trades on Kraken and Fails on nonce?

A nonce error is almost always not a strategy error but a counter desynchronization.

Kraken accepts only a monotonically increasing nonce for one key: if a second process or a backup instance lives next to the bot on the same key, the counter diverges and some orders are rejected.

What is dangerous is not the rejection, but the consequence — a rejected request could have executed before the response reached the bot.

Analysis begins with the log, not with stopping trading: we match by time outgoing requests with nonce and client identifier, exchange responses, and our own order list.

Symptom What we check
Persistent nonce rejection how many processes use one key
Stuck order whether the exchange response arrived after sending
Trade duplicates whether the client identifier is sent on retry
State diverges whether the update stream lags behind the snapshot

Resilience is provided by idempotency of operations: each order has its own client identifier, and retry sending goes only with it — a duplicate returns the original result rather than creating a second trade.

The nonce is issued by a single monotonic counter with disk persistence; otherwise, a retry storm quickly hits the request rate limit.

We perform diagnostics without stopping trading: a shadow instance on a separate key, log replay, reconciliation with the exchange snapshot before enabling the main loop.

The bottleneck is usually one — a lost response to a successfully executed order; after closing it, rejections stop and stuck orders cease to accumulate.

Common Technical Doubts Before Starting

The client's technical side before starting checks not the strategy but the loop's resilience: where keys are stored, what the bot does on a connection break, and how it coexists with limits. Below are answers to the most frequently asked questions.

Where are the exchange access keys stored?

They are not in the code or configs — the keys are in a secure secrets storage, and the bot receives them at startup. We limit permissions on the exchange side to trading and balance reading: fund withdrawal is disabled, and a restriction on allowed request addresses is added. When the team composition changes, keys are rotated and old ones are revoked.

What happens on a connection break?

The bot enters reconciliation mode and does not place orders until communication is restored. The market data channel reconnects with increasing delay, then positions and open orders are reconciled with the exchange.

Each order is assigned its own client identifier, so a retry does not create a duplicate. If the break lasts longer than a set threshold, the on-duty person receives a notification.

Can a second exchange be added to the same loop?

The connector to each venue is a separate adapter under a common interface: orders, balance, bringing tickers and price steps to a unified form. The core trading logic does not change.

Request signatures and sequence numbers are exchange-specific — this is resolved inside the adapter, not in the strategy.

How do you stay within request limits?

We count request weight, not their quantity: it differs for private and public methods. We put a rate limiter on each connector, prioritize canceling and placing orders, while analytics and reporting go to a background stream. The data stream goes via WebSocket, not polling — this removes the main load on limits.

Let's Discuss the Task: What to Prepare for an Estimate and Plan

To come back with an estimate and work plan, rather than clarifying questions a week later, initial data on four axes is enough: what is already written, how it trades, under what load, and who provides access.

Below is a minimal set that covers almost all gaps; if something is missing, that is also a useful answer: gaps show which blocks we estimate from scratch and which we reuse.

  • Current code or its description: language, libraries, what works locally and what already runs on the server — this shows whether we are extending or rewriting.
  • Strategy logic in any readable form: entry and exit rules, position size calculation, stop conditions.
  • Separate keys with permission separation: trading, balance reading, withdrawal — as separate pairs, so that withdrawal is not in the code that trades.
  • Logs for a day or two: nonce errors, rejected orders, connection breaks, share of retries.
  • Loop scheme: where the bot lives, where position state is stored, whether there is a backup node, and how the position is restored after a process crash.
  • Load expectations: how many trading pairs, how many signals per minute, whether a real-time quote stream is needed or periodic polling is sufficient.
  • Access for audit: test key, account with limited rights, and sandbox — to an extent sufficient for testing hypotheses without risking funds.
  • Control requirements: position limits, who and how stops the bot, which events should trigger alerts.

Describe the integration task in free form — we will return with a scope estimate and work plan: stages, what we do, what remains on your side, where the acceptance points are, and how we verify the result on the test loop.