Kraken API Trading: Complete Guide for Crypto Developers
Master Kraken API trading with practical code examples covering authentication, spot and futures endpoints, trade history, fees, and paper trading setup.
Master Kraken API trading with practical code examples covering authentication, spot and futures endpoints, trade history, fees, and paper trading setup.
Kraken's REST API is one of the most battle-tested interfaces in crypto. It's been running since 2013 without a major security breach — which is more than most exchanges can say. If you're building a trading bot, connecting a strategy to live markets, or just automating your own order flow, Kraken's API gives you the tools to do it properly. This guide covers everything from API key setup and authentication to placing orders on both the kraken spot trading api and kraken futures trading api, with working Python code you can run today.
Before any code runs, you need API keys. Head to your Kraken account, go to Security > API, and generate a new key. Kraken lets you scope permissions precisely — you can create a read-only key for fetching kraken api trade history without any withdrawal rights. Always use the minimum permissions needed for your use case. Store keys in environment variables, never in code.
Kraken uses HMAC-SHA512 signatures for private endpoints. The signature combines a nonce, the request payload, and your API secret. Unlike Binance which uses a simpler HMAC-SHA256 on query strings, Kraken's auth flow is slightly more involved but straightforward once you see it in code.
import krakenex
import os
from pykrakenapi import KrakenAPI
# Load credentials from environment variables
API_KEY = os.environ.get('KRAKEN_API_KEY')
API_SECRET = os.environ.get('KRAKEN_API_SECRET')
# Initialize the client
api = krakenex.API(key=API_KEY, secret=API_SECRET)
k = KrakenAPI(api)
# Test connection — fetch account balance
try:
balance = k.get_account_balance()
print("Connected successfully!")
print(balance)
except Exception as e:
print(f"Auth error: {e}")
Use pykrakenapi or krakenex for Python — they handle nonce generation and HMAC signing so you don't have to implement it manually. For JavaScript, the official @dominant-strategies/kraken-api package works well.
Kraken has its own naming convention for trading pairs that trips up newcomers. Bitcoin is XBT, not BTC. Ethereum is XETH. Pairs are formatted as XBTUSD, ETHUSD, or with an X/Z prefix for crypto/fiat. Before placing any order, always query the asset pairs endpoint to get the exact symbol name.
import requests
import json
BASE_URL = 'https://api.kraken.com/0/public'
def get_trading_pairs():
"""Fetch all available kraken api trading pairs."""
response = requests.get(f'{BASE_URL}/AssetPairs')
data = response.json()
if data['error']:
raise ValueError(f"API error: {data['error']}")
pairs = data['result']
# Filter to USD pairs only
usd_pairs = {
name: info for name, info in pairs.items()
if info.get('quote') == 'ZUSD'
}
return usd_pairs
def get_ticker(pair: str):
"""Get current price for a specific pair."""
response = requests.get(f'{BASE_URL}/Ticker', params={'pair': pair})
data = response.json()
if data['error']:
raise ValueError(f"Ticker error: {data['error']}")
result = list(data['result'].values())[0]
return {
'ask': float(result['a'][0]),
'bid': float(result['b'][0]),
'last': float(result['c'][0]),
'volume_24h': float(result['v'][1])
}
# Example usage
if __name__ == '__main__':
ticker = get_ticker('XBTUSD')
print(f"BTC/USD - Ask: ${ticker['ask']:,.2f}, Bid: ${ticker['bid']:,.2f}")
Compared to Bybit and OKX which return standardized BTC-USDT symbols, Kraken's legacy naming takes getting used to. But the market data itself is reliable — Kraken's order book data is among the most accurate in the industry, which matters when your strategy depends on precise bid/ask spreads.
The kraken spot trading api lives at api.kraken.com/0/private/AddOrder. You can place market, limit, stop-loss, and take-profit orders. The kraken futures trading api is a completely separate system at futures.kraken.com/derivatives/api/v3 — different authentication, different base URL, different response format. Don't mix them up.
import krakenex
import os
import time
api = krakenex.API(
key=os.environ['KRAKEN_API_KEY'],
secret=os.environ['KRAKEN_API_SECRET']
)
def place_limit_order(pair: str, direction: str, volume: float, price: float):
"""
Place a limit order on Kraken spot.
direction: 'buy' or 'sell'
"""
params = {
'pair': pair,
'type': direction,
'ordertype': 'limit',
'price': str(price),
'volume': str(volume),
# Uncomment to validate without executing:
# 'validate': True
}
response = api.query_private('AddOrder', params)
if response['error']:
raise ValueError(f"Order failed: {response['error']}")
order_id = response['result']['txid'][0]
print(f"Order placed: {order_id}")
return order_id
def cancel_order(order_id: str):
"""Cancel an open order by transaction ID."""
response = api.query_private('CancelOrder', {'txid': order_id})
if response['error']:
raise ValueError(f"Cancel failed: {response['error']}")
return response['result']
def get_open_orders():
"""Fetch all open orders."""
response = api.query_private('OpenOrders')
if response['error']:
raise ValueError(f"Fetch failed: {response['error']}")
return response['result']['open']
# Example: place a BTC limit buy 2% below current market
# place_limit_order('XBTUSD', 'buy', 0.001, 85000.00)
The kraken margin trading api uses the same AddOrder endpoint — just add 'leverage' to your params (e.g., 'leverage': '5'). Kraken supports up to 5x leverage on spot margin, and up to 50x on futures depending on the contract. Always test with the 'validate': True flag before going live — it runs full validation without actually placing the order.
Kraken API trading fees follow a maker/taker model with 30-day volume tiers. You can query your current fee tier programmatically — useful if your bot needs to account for actual costs in P&L calculations. The default taker fee is 0.26%, dropping to 0.10% at high volume. Makers start at 0.16% and can go to zero at high tiers.
| Volume (USD) | Maker Fee | Taker Fee |
|---|---|---|
| $0 – $10,000 | 0.16% | 0.26% |
| $10,001 – $50,000 | 0.14% | 0.24% |
| $50,001 – $100,000 | 0.12% | 0.22% |
| $100,001 – $250,000 | 0.10% | 0.20% |
| $250,001 – $500,000 | 0.08% | 0.18% |
| $500,001+ | 0.00% | 0.10% |
def get_trade_history(start_ts: int = None, end_ts: int = None):
"""
Fetch kraken api trade history.
start_ts / end_ts: Unix timestamps (optional)
"""
params = {'trades': True}
if start_ts:
params['start'] = start_ts
if end_ts:
params['end'] = end_ts
all_trades = {}
offset = 0
while True:
params['ofs'] = offset
response = api.query_private('TradesHistory', params)
if response['error']:
raise ValueError(f"History error: {response['error']}")
trades = response['result']['trades']
count = response['result']['count']
all_trades.update(trades)
offset += len(trades)
if offset >= count:
break
time.sleep(0.5) # Respect rate limits
return all_trades
def get_fee_info(pair: str):
"""Get current fee schedule for a trading pair."""
response = api.query_private('TradeVolume', {
'pair': pair,
'fee-info': True
})
if response['error']:
raise ValueError(f"Fee error: {response['error']}")
result = response['result']
fees = result['fees'].get(pair, {})
return {
'volume_30d': float(result['volume']),
'taker_fee': float(fees.get('fee', 0.26)),
'min_fee': float(fees.get('minfee', 0.10)),
'max_fee': float(fees.get('maxfee', 0.26))
}
Pagination matters for trade history. Kraken returns 50 trades per page by default, max 50 per call with offset support. The loop pattern above handles this automatically. Compare this to Binance which returns up to 1000 records per call — Kraken's pagination is more conservative, so plan accordingly if you're backfilling years of history.
Kraken API TradingView integration works through webhooks. TradingView's alert system can fire a POST request to your server when a strategy condition triggers — your server then calls the Kraken API to execute the trade. This is the most common pattern for algo traders who build strategies in Pine Script but want live execution on Kraken.
For traders who want pre-built signals rather than writing their own Pine Script, platforms like VoiceOfChain deliver real-time trading signals across hundreds of crypto pairs. You can pipe those signals directly into your Kraken execution layer — VoiceOfChain fires the signal, your webhook handler validates it and calls Kraken's AddOrder endpoint. This separates signal generation from execution cleanly.
from flask import Flask, request, jsonify
import krakenex
import os
import hmac
import hashlib
app = Flask(__name__)
api = krakenex.API(
key=os.environ['KRAKEN_API_KEY'],
secret=os.environ['KRAKEN_API_SECRET']
)
# Secret token to validate incoming webhook requests
WEBHOOK_SECRET = os.environ['WEBHOOK_SECRET']
@app.route('/webhook/kraken', methods=['POST'])
def handle_signal():
"""Handle incoming trading signals from TradingView or VoiceOfChain."""
# Validate webhook authenticity
token = request.headers.get('X-Webhook-Token', '')
if token != WEBHOOK_SECRET:
return jsonify({'error': 'Unauthorized'}), 401
data = request.get_json()
# Expected payload: {"pair": "XBTUSD", "action": "buy", "price": 87500, "size": 0.001}
pair = data.get('pair')
action = data.get('action') # 'buy' or 'sell'
price = data.get('price')
size = data.get('size')
if not all([pair, action, price, size]):
return jsonify({'error': 'Missing required fields'}), 400
# Place the order
order_params = {
'pair': pair,
'type': action,
'ordertype': 'limit',
'price': str(price),
'volume': str(size)
}
response = api.query_private('AddOrder', order_params)
if response['error']:
return jsonify({'error': response['error']}), 500
order_id = response['result']['txid'][0]
return jsonify({'success': True, 'order_id': order_id}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
Platforms like Bybit and OKX have native TradingView integrations built into their UI, which is simpler but less flexible. Kraken's webhook approach requires your own server but gives you full control — you can add position sizing logic, risk checks, or filter signals based on market conditions before executing.
Kraken doesn't offer a native paper trading environment in the traditional sense — there's no sandbox API that mirrors live markets. The closest approach is using the 'validate': True parameter on AddOrder, which runs full order validation (checks balance, price, lot size) without actually submitting. It's not full paper trading but catches most configuration errors.
For proper Kraken API paper trading, the practical approach is running your bot against a simulated order book you maintain locally, with live market data from Kraken's public WebSocket feed. You track a virtual balance, apply real fee calculations, and simulate fills at the prices Kraken would actually execute. This is more work than Binance's testnet, but it's also more realistic because you're using actual live market data rather than a sandbox environment that often behaves differently.
Kraken uses a rate limit counter system, not simple per-second limits. Each API call increments a counter that decays over time. Exceeding it returns EAPI:Rate limit error and can temporarily lock your key. Build exponential backoff into any production bot.
The code in this guide covers the fundamentals, but a production bot needs more. Error handling needs to catch not just API errors but network timeouts, partial fills, and unexpected account states. You need a proper state machine — tracking open orders, pending cancellations, and position exposure. Kraken's WebSocket API (wss://ws.kraken.com) is better than polling REST for latency-sensitive strategies — subscribe to the 'ownTrades' and 'openOrders' feeds for real-time order status.
For the signal layer, you have two paths: build your own indicators or consume pre-built signals. VoiceOfChain delivers real-time signals across hundreds of crypto pairs — you can wire those directly into your Kraken execution layer, letting you focus on execution quality rather than signal generation. Exchanges like Coinbase and Gate.io also have solid APIs if you want to run the same strategy across multiple venues simultaneously for better fill rates on larger positions.
Kraken's API has earned its reputation through a decade of reliability. The authentication is a bit more involved than newer exchanges, the symbol naming is quirky, and paper trading requires DIY effort — but the uptime, security track record, and depth of documentation make it one of the best choices for serious algorithmic trading. Start with public endpoints, get comfortable with the data structures, then layer in private order management one endpoint at a time.