For information on changes for our US clients, please visit our Support Center article.

REST API command line client (Python)
The REST API command line client in Python allows full access to the Kraken REST API via the command line (such as Terminal on macOS), hence no programming knowledge or API experience is required.
All REST API features are accessible including:
  • public market data endpoints
  • private account data endpoints
  • private trading endpoints
  • private funding endpoints
  • private earn endpoints
The command line client can be used as a standalone API client, or can be called from other programs (such as other interpreted languages like Bash scripts, or compiled languages like C/C++).

Installation

1. Install Python 3 (if necessary).
  • macOS and Linux possibly already have Python 3 installed.
  • Windows probably does not have Python 3 installed, but it can be installed from https://www.python.org/.
2. Download and save the krakenapi.py file to your computer in the folder (directory) of your choosing.
For example: Macintosh HD > Users > Satoshi > KrakenAPI

3. Open a command prompt (such as macOS's Terminal), and navigate to the folder (directory) chosen in the previous step. You can use the UNIX/Linux "cd" command (change directory) to navigate.
For example:cd /Users/Satoshi/KrakenAPI

4. Make the krakenapi.py file executable.
You can use the UNIX/Linux "chmod 755" command (change mode).
For example: chmod 755 krakenapi.py

5. Add your API key to the same folder where you are keeping the krakenapi.py file.
  • Copy/paste your API public key from account management into a plain text file called "API_Public_Key".
  • Copy/paste your API private (secret) key into a plain text file called "API_Private_Key".
An API key is only needed if you plan to use the private API endpoints to access your Kraken account (such as balance inquiries, placing/cancelling orders, account history exports, etc).

Example Commands

The REST API command line client usage is as follows:
./krakenapi.py endpoint [parameters] [-pretty]
The command line client supports all of the REST API endpoints, so the following are just a few example commands:
python

Python

# Time
./krakenapi.py Time

# Ticker
./krakenapi.py Ticker pair=xbtusd

# Trades
./krakenapi.py Trades pair=etheur since=1574067140000000000

# Balance
./krakenapi.py Balance

# Trade Balance
./krakenapi.py TradeBalance asset=xbt

# Query Orders
./krakenapi.py QueryOrders txid=O7MN22-ZCX7J-TGLQHD

# Add Order
./krakenapi.py AddOrder pair=xbtusd type=buy ordertype=limit price=6500 volume=0.002 leverage=5

# Cancel Order
./krakenapi.py CancelOrder txid=O7MN22-ZCX7J-TGLQHD
By default the command line client will output the original API response (JSON suitable for interpreting via code), but if an additional command line argument -pretty is used:
./krakenapi.py TradeBalance asset=shib -pretty
the client will then output the same API response as human friendly JSON (with line breaks/indents).

Python Code:

python

Python

#!/usr/bin/env python3

# Kraken Rest API
#
# Usage: ./krakenapi endpoint [parameters]
# Example: ./krakenapi Time
# Example: ./krakenapi OHLC pair=xbtusd interval=1440
# Example: ./krakenapi Balance
# Example: ./krakenapi TradeBalance asset=xdg
# Example: ./krakenapi OpenPositions
# Example: ./krakenapi AddOrder pair=xxbtzusd type=buy ordertype=market volume=0.003 leverage=5

import sys
import time
import base64
import hashlib
import hmac
import urllib.request
import json

api_public = {"Time", "Assets", "AssetPairs", "Ticker", "OHLC", "Depth", "Trades", "Spread", "SystemStatus"}
api_private = {"Balance", "BalanceEx", "TradeBalance", "OpenOrders", "ClosedOrders", "QueryOrders", "TradesHistory", "QueryTrades", "OpenPositions", "Ledgers", "QueryLedgers", "TradeVolume", "AddExport", "ExportStatus", "RetrieveExport", "RemoveExport", "GetWebSocketsToken", "CreateSubaccount", "AccountTransfer"}
api_trading = {"AddOrder", "AddOrderBatch", "EditOrder", "CancelOrder", "CancelOrderBatch", "CancelAll", "CancelAllOrdersAfter","OrderAmends","AmendOrder","ListSubaccounts"}
api_funding = {"DepositMethods", "DepositAddresses", "DepositStatus", "WithdrawMethods", "WithdrawAddresses", "WithdrawInfo", "Withdraw", "WithdrawStatus", "WithdrawCancel", "WalletTransfer"}
api_staking = {"Earn/Strategies", "Earn/Allocations", "Earn/Allocate", "Earn/Deallocate", "Earn/AllocateStatus", "Earn/DeallocateStatus", "Staking/Assets", "Staking/Balance", "Stake", "Unstake", "Staking/Pending", "Staking/Transactions"}

api_domain = "https://api.kraken.com"
api_data = ""

output_format = 0

if len(sys.argv) < 2:
	api_method = "Time"
elif len(sys.argv) == 2:
	api_method = sys.argv[1]
else:
	api_method = sys.argv[1]
	for count in range(2, len(sys.argv)):
		if sys.argv[count] == '-pretty':
			output_format = 1
			continue
		if count == 2:
			api_data = sys.argv[count]
		else:
			api_data = api_data + "&" + sys.argv[count]

if api_method in api_private or api_method in api_trading or api_method in api_funding or api_method in api_staking:
	api_path = "/0/private/"
	api_nonce = str(int(time.time()*1000))
	try:
		api_key = open("API_Public_Key").read().strip()
		api_secret = base64.b64decode(open("API_Private_Key").read().strip())
	except:
		print("API public key and API private (secret) key must be in plain text files called API_Public_Key and API_Private_Key")
		sys.exit(1)
	api_postdata = api_data + "&nonce=" + api_nonce
	api_postdata = api_postdata.encode('utf-8')
	api_sha256 = hashlib.sha256(api_nonce.encode('utf-8') + api_postdata).digest()
	api_hmacsha512 = hmac.new(api_secret, api_path.encode('utf-8') + api_method.encode('utf-8') + api_sha256, hashlib.sha512)
	api_request = urllib.request.Request(api_domain + api_path + api_method, api_postdata)
	api_request.add_header("API-Key", api_key)
	api_request.add_header("API-Sign", base64.b64encode(api_hmacsha512.digest()))
	api_request.add_header("User-Agent", "Kraken REST API")
elif api_method in api_public:
	api_path = "/0/public/"
	api_request = urllib.request.Request(api_domain + api_path + api_method + '?' + api_data)
	api_request.add_header("User-Agent", "Kraken REST API")
else:
	print("Usage: %s method [parameters]" % sys.argv[0])
	print("Example: %s OHLC pair=xbtusd interval=1440" % sys.argv[0])
	sys.exit(1)

try:
	api_reply = urllib.request.urlopen(api_request).read()
except Exception as error:
	print("API call failed (%s)" % error)
	sys.exit(1)

try:
	api_reply = api_reply.decode()
except Exception as error:
	if api_method == 'RetrieveExport':
		sys.stdout.buffer.write(api_reply)
		sys.exit(0)
	print("API response invalid (%s)" % error)
	sys.exit(1)

if '"error":[]' in api_reply:
	print(api_reply if output_format == 0 else json.dumps(json.loads(api_reply), indent = 4))
	sys.exit(0)
else:
	print(api_reply if output_format == 0 else json.dumps(json.loads(api_reply), indent = 4))
	sys.exit(1)