Kraken API Key and Secret: Complete Setup Guide
Learn how to generate and use your Kraken API key and secret for automated trading, bot integration, and portfolio management with real code examples.
Learn how to generate and use your Kraken API key and secret for automated trading, bot integration, and portfolio management with real code examples.
If you're running a trading bot, connecting a portfolio tracker, or pulling live order book data, you need a Kraken API key and secret. Unlike manually logging in through a browser, the API lets your code interact with Kraken's infrastructure directly — placing orders, checking balances, pulling trade history — without ever touching the web interface. Getting this setup right is the difference between a bot that actually trades and one that throws authentication errors at 3am.
A Kraken API key is a unique alphanumeric string that identifies your account to Kraken's servers. The API secret is a longer cryptographic string used to sign your requests — proving they actually came from you and weren't tampered with in transit. Together, they replace your username and password for programmatic access.
Every exchange handles this slightly differently. On Binance, you get an API key and secret in a similar pattern, but the signing algorithm uses HMAC-SHA256 applied differently. Bybit and OKX both use comparable key-secret schemes but with their own endpoint structures. Kraken's implementation uses Base64-encoded secrets and a nonce-based replay attack prevention system — meaning each request must include an incrementing number so old requests can't be replayed by an attacker who captures your traffic.
Never share your API secret with anyone. Kraken shows it only once during creation — if you lose it, you must delete the key and generate a new one. Store it in an environment variable or a secrets manager, never in your source code.
Kraken gives you granular control over what each API key is allowed to do. You can create a read-only key for your portfolio tracker and a separate key with trading permissions for your bot — so if one gets compromised, the blast radius is contained.
The IP whitelist is worth enabling if your bot runs on a fixed-IP server. It means even if someone steals your key and secret, they can't use them from a different IP. If you're running on a cloud instance with a dynamic IP, you can skip it — but you're trading a security layer for convenience.
Kraken's private endpoints (anything involving your account data or order management) require a signed request. The signature combines your API secret, a nonce, and the request parameters into an HMAC-SHA512 hash. This sounds complex, but the official Python library handles it for you — or you can implement it manually if you want full control.
import krakenex
import os
# Load credentials from environment variables — never hardcode these
api = krakenex.API(
key=os.environ['KRAKEN_API_KEY'],
secret=os.environ['KRAKEN_API_SECRET']
)
# Fetch account balance
try:
response = api.query_private('Balance')
if response.get('error'):
print(f"API Error: {response['error']}")
else:
balances = response['result']
for asset, amount in balances.items():
if float(amount) > 0:
print(f"{asset}: {amount}")
except Exception as e:
print(f"Request failed: {e}")
If you prefer to handle authentication manually without the krakenex wrapper — useful when integrating Kraken into an existing framework — here's the raw signing implementation:
import urllib.parse
import hashlib
import hmac
import base64
import time
import requests
import os
API_KEY = os.environ['KRAKEN_API_KEY']
API_SECRET = os.environ['KRAKEN_API_SECRET']
BASE_URL = 'https://api.kraken.com'
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()
def kraken_private_request(endpoint, params=None):
if params is None:
params = {}
urlpath = f'/0/private/{endpoint}'
params['nonce'] = str(int(1000 * time.time()))
headers = {
'API-Key': API_KEY,
'API-Sign': get_kraken_signature(urlpath, params, API_SECRET)
}
response = requests.post(
BASE_URL + urlpath,
headers=headers,
data=params,
timeout=10
)
response.raise_for_status()
return response.json()
# Example: get open orders
result = kraken_private_request('OpenOrders')
if result['error']:
print(f"Errors: {result['error']}")
else:
orders = result['result']['open']
print(f"Open orders: {len(orders)}")
for order_id, order in orders.items():
print(f" {order_id}: {order['descr']['order']}")
Reading data is useful, but the real power comes from placing and managing orders programmatically. Platforms like Bybit and OKX have similar order placement APIs, but Kraken's AddOrder endpoint has a distinctive parameter structure worth knowing. The 'ordertype' field accepts 'market', 'limit', 'stop-loss', 'take-profit', and several others. The 'type' field is simply 'buy' or 'sell'.
def place_limit_order(pair, side, volume, price):
"""
Place a limit order on Kraken.
pair: e.g. 'XBTUSD' for BTC/USD
side: 'buy' or 'sell'
volume: amount in base currency (e.g. 0.001 BTC)
price: limit price in quote currency
"""
params = {
'pair': pair,
'type': side,
'ordertype': 'limit',
'price': str(price),
'volume': str(volume),
# Uncomment to test without actually placing the order:
# 'validate': 'true'
}
result = kraken_private_request('AddOrder', params)
if result['error']:
print(f"Order failed: {result['error']}")
return None
order_ids = result['result']['txid']
description = result['result']['descr']['order']
print(f"Order placed: {description}")
print(f"Transaction IDs: {order_ids}")
return order_ids
# Place a small BTC/USD limit buy
place_limit_order(
pair='XBTUSD',
side='buy',
volume=0.001,
price=60000
)
Always test with the 'validate': 'true' parameter first. This runs the order through Kraken's validation without actually submitting it — catching parameter errors before they cost you real money.
An API key alone is just plumbing. The value comes from what you feed into it. Many traders use tools like VoiceOfChain to receive real-time trading signals — the platform aggregates on-chain data, volume anomalies, and price action into actionable signals. When a signal fires, your bot reads it and translates it into a Kraken API order. That's the loop: signal in, order out.
Compare this to a fully manual workflow: you watch a chart, decide to buy, open the browser, navigate to the order form, type in the parameters, click submit. A bot with a live signal feed collapses that to milliseconds. On Binance and Coinbase this matters for liquid markets; on Kraken, which has deep BTC and ETH books, the latency advantage is real for anything time-sensitive.
VoiceOfChain can serve as the signal layer while your Kraken API integration handles execution. The pattern is simple: poll or subscribe to signals, check if your position criteria are met, call AddOrder if they are. This separation of concerns — signal logic vs. execution logic — makes your system easier to debug and improve over time.
A compromised API key on Kraken — or anywhere else, whether it's Gate.io, KuCoin, or Bitget — can result in your entire balance being transferred or liquidated. Security isn't optional. These are the non-negotiable practices:
| Permission | Use Case | Risk if Leaked |
|---|---|---|
| Query Funds | Portfolio trackers, dashboards | Low — attacker sees balances only |
| Query Open/Closed Orders | Trade history analysis | Low — read-only order data |
| Create & Cancel Orders | Trading bots, auto-rebalancing | High — attacker can place bad trades |
| Access WebSockets | Real-time data feeds | Low — market data only |
| Withdraw Funds | Automated withdrawals | Critical — never enable unless required |
Setting up a Kraken API key and secret is a one-time investment that unlocks a completely different level of trading capability. The process is straightforward: generate the key with minimal required permissions, store the credentials safely in environment variables, implement the HMAC-SHA512 signing logic (or use a library), and start building your automation layer on top.
Whether you're building a simple rebalancing bot, connecting to VoiceOfChain's signal feed for automated execution, or pulling trade history into a custom analytics dashboard, the API is your foundation. Get the security layer right from day one — separate keys for separate purposes, no withdrawal permissions on trading keys, IP whitelisting where possible — and you've eliminated most of the risk before writing a single order.
The code examples above are production-ready starting points. Add your own risk management logic — position sizing, daily loss limits, circuit breakers — before pointing them at real money. The API will do exactly what you tell it to. Make sure you're telling it something sensible.