Market Cap: $3.6793T -2.630%
Volume(24h): $210.1238B 27.900%
Fear & Greed Index:

57 - Neutral

  • Market Cap: $3.6793T -2.630%
  • Volume(24h): $210.1238B 27.900%
  • Fear & Greed Index:
  • Market Cap: $3.6793T -2.630%
Cryptos
Topics
Cryptospedia
News
CryptosTopics
Videos
Top Cryptospedia

Select Language

Select Language

Select Currency

Cryptos
Topics
Cryptospedia
News
CryptosTopics
Videos

How to use the Kraken API

The Kraken API enables automated trading and real-time market data access via REST and WebSockets, with public endpoints for data and private ones for account actions.

Aug 02, 2025 at 10:28 am

Understanding the Kraken API and Its Purpose

The Kraken API is a powerful tool that allows developers and traders to interact with the Kraken cryptocurrency exchange programmatically. It enables automated trading, portfolio management, real-time market data retrieval, and account monitoring without relying on the web interface. The API supports both public endpoints, which provide market data such as ticker information, order books, and trade history, and private endpoints, which require authentication and allow users to manage orders, check balances, and withdraw funds.

To use the Kraken API effectively, you must understand its two main components: REST API and WebSockets API. The REST API is ideal for one-off requests like fetching asset prices or placing an order. The WebSockets API is used for real-time data streaming, such as live price updates or order book changes. Both APIs are accessible via HTTPS and WebSocket connections, respectively, and require proper formatting of requests and responses, typically in JSON format.

Setting Up Your Kraken API Credentials

Before making any API calls, you need to generate your API key and secret from your Kraken account. Log in to your Kraken account and navigate to the Settings section. Click on the API tab, then select New API Key. You will be prompted to set permissions for the key. For basic data retrieval, enable Query Public and Query Private options. If you plan to place trades or withdraw funds, also enable Trade and Withdraw permissions. Be cautious with permissions, as compromised keys can lead to fund loss.

Once the key is generated, you will see two strings:

  • API Key: A long alphanumeric string used to identify your account.
  • API Secret: A base64-encoded string used to sign requests.

Store these securely. The API secret should never be exposed in client-side code or public repositories. To use these credentials in API requests, you must sign each private request using HMAC-SHA512 encryption, with the API secret as the key and a message that includes the URI path, nonce, and POST data.

Executing Public API Requests

Public endpoints do not require authentication and can be accessed directly via HTTP GET requests. These are useful for retrieving market data. For example, to get the current ticker information for Bitcoin against the US Dollar (BTC/USD), use the following endpoint:

https://api.kraken.com/0/public/Ticker?pair=XXBTZUSD

The response will include the last traded price, 24-hour volume, high/low prices, and bid/ask rates. Other public endpoints include:

  • AssetPairs: Lists all tradable pairs and their specifications.
  • Depth: Returns the current order book for a given pair.
  • Trades: Retrieves recent trade history.
  • OHLC: Provides candlestick data for charting.

Each public request returns a JSON object with a result field containing the data and an error field that lists any issues. Ensure your application handles errors gracefully by checking the error array before processing the result.

Signing and Sending Private API Requests

Private API calls require authentication using your API key and a cryptographic signature. Every request must include the following headers:

  • API-Key: Your generated API key.
  • API-Sign: The HMAC-SHA512 signature of the message.

The message to be signed consists of:

  • The URI path (e.g., /0/private/Balance).
  • A nonce value—a strictly increasing integer used once.
  • The POST data (e.g., nonce=1234567890).

To construct the signature:

  • Concatenate the message as: path + SHA256(nonce + POST data).
  • Use the decoded API secret as the HMAC key.
  • Apply HMAC-SHA512 to the concatenated message.

In Python, this can be implemented as:

import hashlib
import hmac
import time

def get_kraken_signature(urlpath, data, secret):

postdata = urllib.parse.urlencode(data)
encoded = (str(data['nonce']) + postdata).encode()
message = urlpath.encode() + hashlib.sha256(encoded).digest()
mac = hmac.new(base64.b64decode(secret), message, hashlib.sha512)
return base64.b64encode(mac.digest()).decode()

Use this signature in the API-Sign header when making POST requests to endpoints like /0/private/Balance or /0/private/AddOrder.

Practical Use Cases and Code Examples

A common use case is checking your account balance. To do this:

  • Send a POST request to https://api.kraken.com/0/private/Balance.
  • Include the nonce in the POST body.
  • Set the API-Key and API-Sign headers.

Another example is placing a limit buy order:

  • Use the /0/private/AddOrder endpoint.
  • Include parameters such as pair=XXBTZUSD, type=buy, ordertype=limit, price=30000, and volume=0.01.
  • Ensure the nonce is greater than the previous one.

For real-time data, use the WebSockets API. Connect to wss://ws.kraken.com/v2. Subscribe to channels like ticker, book, or trade for specific pairs. For instance, to get live BTC/USD trades:

{

"method": "subscribe",
"params": {

"channel": "trade",
"symbol": "BTC/USD",
"snapshot": true

}
}

The server will push trade updates as they occur. Handle incoming messages using event listeners in your application.

Security Best Practices and Rate Limiting

Kraken enforces rate limits to prevent abuse. Public endpoints allow up to 10 requests per second per IP. Private endpoints are limited to 15 requests per second per API key. Exceeding these limits results in temporary bans. To avoid this, implement request throttling and exponential backoff in your code.

Enhance security by:

  • Using IP whitelisting for your API keys.
  • Disabling unnecessary permissions.
  • Rotating API keys periodically.
  • Never logging or storing API secrets in plaintext.

Always use HTTPS for REST calls and WSS for WebSockets. Validate SSL certificates in production environments.


Frequently Asked Questions

What is the correct format for the nonce in Kraken API requests?

The nonce must be an integer that increases with each request. Most developers use Unix timestamp in microseconds. For example, int(time.time() * 1000000) in Python ensures uniqueness and monotonic growth. Reusing or decreasing the nonce will cause the API to reject the request.

How can I test the Kraken API without risking real funds?

Kraken does not offer a sandbox environment. However, you can create a new API key with no withdrawal or trading permissions and use it to test balance queries and market data retrieval. For trading simulations, fetch market data and simulate order execution locally without sending real orders.

Why do I get an 'EAPI:Invalid key' error?

This error indicates that the API-Key header is missing, malformed, or not recognized. Double-check that the key is copied exactly from the Kraken dashboard and included in the request headers. Also, ensure no extra spaces or line breaks are present.

Can I use the Kraken API to retrieve historical candlestick data?

Yes. Use the /0/public/OHLC endpoint with the pair and interval parameters. For example, pair=XXBTZUSD&interval=60 returns 1-hour candles. The response includes time, open, high, low, close, and volume data. Note that Kraken limits historical data to a certain number of recent intervals per request.

Disclaimer:info@kdj.com

The information provided is not trading advice. kdj.com does not assume any responsibility for any investments made based on the information provided in this article. Cryptocurrencies are highly volatile and it is highly recommended that you invest with caution after thorough research!

If you believe that the content used on this website infringes your copyright, please contact us immediately (info@kdj.com) and we will delete it promptly.

Related knowledge

See all articles

User not found or password invalid

Your input is correct