WebSocket API Command Line Client

The following Python 2 code implements a command line API client for our exchange WebSocket API.

The code can be used as a standalone API client, or can be called from other interpreted or compiled programming languages (Bash, C++, etc.).

The standard Python WebSocket library (websocket-client) is required for the WebSocket networking, but no other API libraries/modules are required.

The WebSocket API command line client can also be downloaded as krakenws.py.

 

#!/usr/bin/env python

# Kraken WebSocket API
# 
# Usage: ./krakenws.py feed symbols
# Example: ./krakenws.py trade xbt/usd
# Example: ./krakenws.py ticker xlm/usd
# Example: ./krakenws.py book eth/usd eth/eur
# Example: ./krakenws.py ohlc xbt/eur
# Example: ./krakenws.py spread ltc/usd ltc/eur

import sys
from websocket import create_connection

api_status = {"ping"}
api_public = {"trade", "book", "ticker", "spread", "ohlc"}
api_domain = "wss://ws.kraken.com/"

try:
	ws = create_connection(api_domain)
	print(ws.recv())
except Exception as error:
	print("WebSocket connection failed (%s)" % error)
	sys.exit(1)

if len(sys.argv) < 2:
	api_feed = "ping"
else:
	api_feed = sys.argv[1]

if api_feed in api_status:
	api_data = '{"event":"%(feed)s"}' % {"feed":api_feed}
elif api_feed in api_public:
	if len(sys.argv) < 3:
		print("Usage: %s feed symbols" % sys.argv[0])
		print("Example: %s ticker xbt/usd ltc/eur" % sys.argv[0])
		ws.close()
		sys.exit(1)
	api_symbols = sys.argv[2].upper()
	for count in range(3, len(sys.argv)):
		api_symbols = api_symbols + '","' + sys.argv[count].upper()
	api_data = '{"event":"subscribe", "subscription":{"name":"%(feed)s"}, "pair":["%(symbols)s"]}' % {"feed":api_feed, "symbols":api_symbols}
else:
	print("Usage: %s feed symbols" % sys.argv[0])
	print("Example: %s ticker xbt/usd ltc/eur" % sys.argv[0])
	ws.close()
	sys.exit(1)

try:
	ws.send(api_data)
except Exception as error:
	print("Feed subscription failed (%s)" % error)
	ws.close()
	sys.exit(1)

for count in range(300):
	try:
		api_data = ws.recv()
		print(api_data)
	except KeyboardInterrupt:
		ws.close()
		sys.exit(0)
	except Exception as error:
		print("WebSocket message failed (%s)" % error)
		ws.close()
		sys.exit(1)

ws.close()
sys.exit(0)