Spot Websockets
- class kraken.spot.SpotWSClient(key: str = '', secret: str = '', callback: Callable | None = None, *, no_public: bool = False)
Bases:
SpotWSClientBaseThis client only supports the Kraken Websocket API v2.
Class to access public and private/authenticated websocket connections.
This class holds up to two websocket connections, one private and one public. The core functionalities are un-/subscribing to websocket feeds and sending messages. See
kraken.spot.SpotWSClient.subscribe()andkraken.spot.SpotWSClientV.send_message()for more information.When accessing private endpoints that need authentication make sure, that the
Access WebSockets APIAPI key permission is set in the user’s account. To place or cancel orders, querying ledger information or accessing live portfolio changes (fills, new orders, …) there are separate permissions that must be enabled if required.- Parameters:
key (str, optional) – API Key for the Kraken Spot API (default:
"")secret (str, optional) – Secret API Key for the Kraken Spot API (default:
"")url (str, optional) – Set a specific URL to access the Kraken REST API
no_public – Disables public connection (default:
False). If not set or set toFalse, the client will create a public and a private connection per default. If only a private connection is required, this parameter should be set toTrue.beta (bool) – Use the beta websocket channels (maybe not supported anymore, default:
False)
HowTo: Use the Kraken Spot websocket client1import asyncio 2from kraken.spot import SpotWSClient 3 4 5class Client(SpotWSClient): 6 7 async def on_message(self, message): 8 print(message) 9 10 11async def main(): 12 client = Client() # unauthenticated 13 client_auth = Client( # authenticated 14 key="kraken-api-key", 15 secret="kraken-secret-key" 16 ) 17 # open the websocket connections 18 await client.start() 19 await auth_client.start() 20 21 # subscribe to the desired feeds: 22 await client.subscribe( 23 params={"channel": "ticker", "symbol": ["BTC/USD"]} 24 ) 25 # from now on the on_message function receives the ticker feed 26 27 while not client.exception_occur: 28 await asyncio.sleep(6) 29 30if __name__ == "__main__": 31 try: 32 asyncio.run(main()) 33 except KeyboardInterrupt: 34 pass
HowTo: Use the websocket client as instance1import asyncio 2from kraken.spot import SpotWSClient 3 4 5async def on_message(message): 6 print(message) 7 8async def main(): 9 10 client = SpotWSClient(callback=on_message) 11 await client.start() 12 await client.subscribe( 13 params={"channel": "ticker", "symbol": ["BTC/USD"]} 14 ) 15 16 while not client.exception_occur: 17 await asyncio.sleep(10) 18 19 20if __name__ == "__main__": 21 try: 22 asyncio.run(main()) 23 except KeyboardInterrupt: 24 pass
HowTo: Use the websocket client as context manager1import asyncio 2from kraken.spot import SpotWSClient 3 4async def on_message(message): 5 print(message) 6 7async def main(): 8 async with SpotWSClient( 9 key="api-key", 10 secret="secret-key", 11 callback=on_message 12 ) as session: 13 await session.subscribe( 14 params={"channel": "ticker", "symbol": ["BTC/USD"]} 15 ) 16 17 while True 18 await asyncio.sleep(6) 19 20 21if __name__ == "__main__": 22 try: 23 asyncio.run(main()) 24 except KeyboardInterrupt: 25 pass
- property active_private_subscriptions: list[dict]
Returns the active private subscriptions
- Returns:
List of active private subscriptions
- Return type:
list[dict]
- Raises:
ConnectionError – If there is no active private connection
- property active_public_subscriptions: list[dict]
Returns the active public subscriptions
- Returns:
List of active public subscriptions
- Return type:
list[dict]
- Raises:
ConnectionError – If there is no active public connection.
- async async_close() None
Closes the aiohttp session
- property exception_occur: bool
Returns True if any connection was stopped due to an exception.
- get_nonce() str
Return a new nonce
- async get_ws_token() dict
Get the authentication token to establish the authenticated websocket connection. This is used internally and in most cases not needed outside.
- Returns:
The authentication token
- Return type:
dict
- async on_message(message: dict | list) None
Calls the defined callback function (if defined). In most cases you have to overwrite this function since it will receive all incoming messages that will be sent by Kraken.
See
kraken.spot.SpotWSClientfor examples to use this function.- Parameters:
message (dict | list) – The message received sent by Kraken via the websocket connection
- property private_channel_names: list[str]
Returns the list of valid values for
channelwhen un-/subscribing from/to private feeds that need authentication.Override this property if the exchange supports additional private channels.
- Returns:
List of available private channel names
- Return type:
list[str]
- property private_methods: list[str]
Returns the list of available methods - parameters are similar to the REST API trade methods.
The available methods and their documentation are listed below (as of June 2023):
- Returns:
List of available methods
- Return type:
list[str]
- property public_channel_names: list[str]
Returns the list of valid values for
channelwhen un-/subscribing from/to public feeds without authentication.Override this property if the exchange supports additional public channels.
The available public channels are listed below:
- Returns:
List of available public channel names
- Return type:
list[str]
- async request(method: str, uri: str, params: dict | None = None, timeout: int = 10, *, auth: bool = True, do_json: bool = False, return_raw: bool = False, query_str: str | None = None, extra_params: str | dict | None = None) Coroutine
Handles the requested requests, by sending the request, handling the response, and returning the message or in case of an error the respective Exception.
- Parameters:
method (str) – The request method, e.g.,
GET,POST,PUT, …uri (str) – The endpoint to send the message
auth (bool) – If the requests needs authentication (default:
True)params (dict, optional) – The query or post parameter of the request (default:
None)timeout (int) – Timeout for the request (default:
10)do_json (bool) – If the
paramsmust be “jsonified” - in case of nested dict stylereturn_raw (bool, optional) – If the response should be returned without parsing. This is used for example when requesting an export of the trade history as .zip archive.
query_str (str, optional) – Add custom values to the query /0/public/Nfts?filter%5Bcollection_id%5D=NCQNABO-XYCA7-JMMSDF&page_size=10
- Raises:
kraken.exceptions.KrakenException.* – If the response contains errors
- Returns:
The response
- Return type:
dict | list | aiohttp.ClientResponse
- property return_unique_id: str
Returns a unique uuid string
- Returns:
uuid
- Return type:
str
- async send_message(message: dict, *, raw: bool = False) None
Sends a message via the websocket connection. For private messages the authentication token will be assigned automatically if
raw=False.The user can specify a
req_dwithin the message to identify corresponding responses via websocket feed.- Parameters:
message (dict) – The information to send
raw (bool, optional) – If set to
Truethemessagewill be sent directly.
The following examples demonstrate how to use the
kraken.spot.SpotWSClient.send_message()function. The client must be instantiated as described inkraken.spot.SpotWSClientwhereclientuses public connections (without authentication) andclient_authmust be instantiated using valid credentials since only this way placing or canceling orders can be done.Please note that the send_message function will automatically pass the authentication token (except for the case if
raw=True).Placing orders using an authenticated websocket connection can be easily done as shown in the example below. See https://docs.kraken.com/websockets-v2/#add-order to retrieve more information about the available parameters.
Spot Websocket: Place a new order1>>> await client_auth.send_message( 2... message={ 3... "method": "add_order", 4... "params": { 5... "limit_price": 1234.56, 6... "order_type": "limit", 7... "order_userref": 123456789, 8... "order_qty": 1.0, 9... "side": "buy", 10... "symbol": "BTC/USD", 11... }, 12... } 13... )
Placing orders as batch can be done by passing
batch_addas method. Its parameters and limitations are described in https://docs.kraken.com/websockets-v2/#batch-add.Spot Websocket: Placing orders as batch1>>> await client_auth.send_message( 2... message={ 3... "method": "batch_add", 4... "params": { 5... "orders": [ 6... { 7... "limit_price": 1000.23, 8... "order_qty": 1, 9... "order_type": "limit", 10... "order_userref": 123456789, 11... "side": "buy", 12... }, 13... { 14... "limit_price": 500.21, 15... "order_qty": 2.12345, 16... "order_type": "limit", 17... "order_userref": 212345679, 18... "side": "sell", 19... "stp_type": "cancel_both", 20... }, 21... ], 22... "symbol": "BTC/USD", 23... "validate": True, 24... }, 25... } 26... )
Cancel orders as batch is available using the
batch_cancelmethod as described in https://docs.kraken.com/websockets-v2/#batch-cancel.Spot Websocket: Cancel orders as batch1>>> await client_auth.send_message( 2... message={ 3... "method": "batch_cancel", 4... "params": { 5... "orders": [ 6... "123456789", 7... "212345679", 8... "ORDER-ID123-4567890" 9... ], 10... }, 11... } 12... )
Cancel all orders can be used as the name suggests - to cancel all open orders (see https://docs.kraken.com/websockets-v2/#cancel-all-orders).
Spot Websocket: Cancel all orders1>>> await client_auth.send_message( 2... message={ 3... "method": "cancel_all", 4... } 5... )
Death Man’s Switch is a useful utility to reduce the risk of losses due to network fuck-ups since it will cancel all orders if the call was not received by Kraken within a certain amount of time. See https://docs.kraken.com/websockets-v2/#cancel-all-orders-after for more information.
Spot Websocket: Death Man’s Switch / cancel_all_orders_after1>>> await client_auth.send_message( 2... message={ 3... "method": "cancel_all_orders_after", 4... "params": {"timeout": 60}, 5... } 6... )
Canceling orders is a common task during trading and can be done as described in https://docs.kraken.com/websockets-v2/#cancel-order.
Spot Websocket: Cancel order(s)1>>> await client_auth.send_message( 2... message={ 3... "method": "cancel_order", 4... "params": { 5... "order_id": ["ORDER-ID123-456789", "ORDER-ID123-987654"], 6... }, 7... } 8... )
Editing orders can be done as shown in the example below. See https://docs.kraken.com/websockets-v2/#edit-order for more information.
Spot Websocket: Cancel order(s)1>>> await client_auth.send_message( 2... message={ 3... "method": "edit_order", 4... "params": { 5... "order_id": "ORDER-ID123-456789", 6... "order_qty": 2.5, 7... "symbol": "BTC/USD", 8... }, 9... } 10... )
Subscribing to websocket feeds can be done using the send_message function but it is recommended to use
kraken.spot.SpotWSClient.subscribe()instead.Spot Websocket: Subscribe to a websocket feed1>>> await client.send_message( 2... message={ 3... "method": "subscribe", 4... "params": {"channel": "book", "snapshot": False, "symbol": ["BTC/USD"]}, 5... } 6... )
- async start() None
Method to start the websocket connection.
- async stop() None
Method to stop the websocket connection.
- async subscribe(params: dict, req_id: int | None = None) None
Subscribe to a channel/feed
Success or failures are sent over the websocket connection and can be received via the on_message or callback function.
When accessing private endpoints and subscription feeds that need authentication make sure that the
Access WebSockets APIAPI key permission is set in the users Kraken account.See https://docs.kraken.com/websockets-v2/#channels for all channels.
Please note that this function automatically assigns the
methodkey and sets its value tosubscribe. The authentication token is also assigned automatically, so only theparamsare needed here.- Parameters:
params (dict) – The subscription message
req_id (int, optional) – Identification number that will be added to the response message sent by the websocket feed.
Initialize your client as described in
kraken.spot.SpotWSClientto run the following example:Spot Websocket: Subscribe to a websocket feed1>>> await client.subscribe( 2... params={"channel": "ticker", "symbol": ["BTC/USD"]} 3... )
- async unsubscribe(params: dict, req_id: int | None = None) None
Unsubscribe from a channel/feed
Success or failures are sent via the websocket connection and can be received via the on_message or callback function.
When accessing private endpoints and subscription feeds that need authentication make sure, that the
Access WebSockets APIAPI key permission is set in the users Kraken account.- Parameters:
params (dict) – The un-subscription message (only the params part)
Initialize your client as described in
kraken.spot.SpotWSClientto run the following example:Spot Websocket: Unsubscribe from a websocket feed1>>> await client.unsubscribe( 2... params={"channel": "ticker", "symbol": ["BTC/USD"]} 3... )
- class kraken.spot.SpotOrderBookClient(depth: int = 10, callback: Callable | None = None)
Bases:
SpotWSClientThis client is using the Kraken Websocket API v2
The orderbook client can be used for instantiation and maintaining one or multiple order books for Spot trading on the Kraken cryptocurrency exchange. It uses websockets to subscribe to book feeds and receives book updates, calculates the checksum and will publish the raw message to the
on_book_update()function or to the specified callback function.get()can be used to access a specific book of this client - they will always be up-to date when used from withinon_book_update().The client will resubscribe to the book feed(s) if any errors occur and publish the changes to the mentioned function(s). This is required to compute the correct checksum internally.
This class has a default book depth of 10. Available depths are: 10, 25, 50, 100, 500, 1000. This client can handle multiple books - but only for one depth. When subscribing to books with different depths, please use separate instances of this class.
Example: Create and maintain a Spot orderbook as custom class1from typing import Any 2from kraken.spot import SpotOrderBookClient 3import asyncio 4 5class OrderBook(SpotOrderBookClient): 6 async def on_book_update(self: "OrderBook", pair: str, message: 7 list) -> None: 8 '''This function must be overloaded to get the recent updates.''' 9 book: dict[str, Any] = self.get(pair=pair) bid:s 10 list[tuple[str, str]] = list(book["bid"].items()) ask: 11 list[tuple[str, str]] = list(book["ask"].items()) 12 13 print("Bid Volume Ask Volume") for level in 14 range(self.depth): 15 print( 16 f"{bid[level][0]} ({bid[level][1]}) {ask[level][0]} 17 ({ask[level][1]})" 18 ) 19 20async def main() -> None: 21 orderbook: OrderBook = OrderBook(depth=10) 22 await orderbook.start() 23 24 await orderbook.add_book( 25 pairs=["XBT/USD"] # we can also subscribe to more currency 26 pairs 27 ) 28 29 while not orderbook.exception_occur: 30 await asyncio.sleep(10) 31 32if __name__ == "__main__": 33 try: 34 asyncio.run(main()) 35 except KeyboardInterrupt: 36 pass
Example: Create and maintain a Spot orderbook using a callback1from typing import Any 2from kraken.spot import SpotOrderBookClient 3import asyncio 4 5async def my_callback(self: "OrderBook", pair: str, message: dict) -> None: 6 '''This function do not need to be async.''' 7 print(message) 8 9async def main() -> None: 10 orderbook: OrderBook = OrderBook(depth=100, callback=my_callback) 11 await orderbook.start() 12 13 await orderbook.add_book( 14 pairs=["XBT/USD"] # we can also subscribe to more currency 15 pairs 16 ) 17 18 while not orderbook.exception_occur: 19 await asyncio.sleep(10) 20 21if __name__ == "__main__": 22 try: 23 asyncio.run(main()) 24 except KeyboardInterrupt: 25 pass
- property active_private_subscriptions: list[dict]
Returns the active private subscriptions
- Returns:
List of active private subscriptions
- Return type:
list[dict]
- Raises:
ConnectionError – If there is no active private connection
- property active_public_subscriptions: list[dict]
Returns the active public subscriptions
- Returns:
List of active public subscriptions
- Return type:
list[dict]
- Raises:
ConnectionError – If there is no active public connection.
- async add_book(pairs: list[str]) None
Add an orderbook to this client. The feed will be subscribed and updates will be published to the
on_book_update()function.- Parameters:
pairs (list[str]) – The pair(s) to subscribe to
depth (int) – The book depth
- async async_close() None
Closes the aiohttp session
- property depth: int
Return the fixed depth of this orderbook client.
- property exception_occur: bool
Returns True if any connection was stopped due to an exception.
- get(pair: str) dict | None
Returns the orderbook for a specific
pair.- Parameters:
pair (str) – The pair to get the orderbook from
- Returns:
The orderbook of that
pair.- Return type:
dict
- static get_first(values: tuple) float
This function is used as callback for the
sortedmethod to sort a tuple/list by its first value and while ensuring that the values are floats and comparable.- Parameters:
values (tuple) – A tuple of string values
- Returns:
The first value of
valuesas float.- Return type:
float
- get_nonce() str
Return a new nonce
- async get_ws_token() dict
Get the authentication token to establish the authenticated websocket connection. This is used internally and in most cases not needed outside.
- Returns:
The authentication token
- Return type:
dict
- async on_book_update(pair: str, message: dict) None
This function will be called every time the orderbook gets updated. It needs to be overloaded if no callback function was defined during the instantiation of this class.
- Parameters:
pair (str) – The currency pair of the orderbook that has been updated.
message (dict) – The book message sent by Kraken
- async on_message(message: list | dict) None
This function must not be overloaded - it would break this client!
It receives and processes the book related websocket messages and is only publicly visible for those who understand and are willing to mock it.
- property private_channel_names: list[str]
Returns the list of valid values for
channelwhen un-/subscribing from/to private feeds that need authentication.Override this property if the exchange supports additional private channels.
- Returns:
List of available private channel names
- Return type:
list[str]
- property private_methods: list[str]
Returns the list of available methods - parameters are similar to the REST API trade methods.
The available methods and their documentation are listed below (as of June 2023):
- Returns:
List of available methods
- Return type:
list[str]
- property public_channel_names: list[str]
Returns the list of valid values for
channelwhen un-/subscribing from/to public feeds without authentication.Override this property if the exchange supports additional public channels.
The available public channels are listed below:
- Returns:
List of available public channel names
- Return type:
list[str]
- async remove_book(pairs: list[str]) None
Unsubscribe from a subscribed orderbook.
- Parameters:
pairs (list[str]) – The pair(s) to unsubscribe from
depth (int) – The book depth
- async request(method: str, uri: str, params: dict | None = None, timeout: int = 10, *, auth: bool = True, do_json: bool = False, return_raw: bool = False, query_str: str | None = None, extra_params: str | dict | None = None) Coroutine
Handles the requested requests, by sending the request, handling the response, and returning the message or in case of an error the respective Exception.
- Parameters:
method (str) – The request method, e.g.,
GET,POST,PUT, …uri (str) – The endpoint to send the message
auth (bool) – If the requests needs authentication (default:
True)params (dict, optional) – The query or post parameter of the request (default:
None)timeout (int) – Timeout for the request (default:
10)do_json (bool) – If the
paramsmust be “jsonified” - in case of nested dict stylereturn_raw (bool, optional) – If the response should be returned without parsing. This is used for example when requesting an export of the trade history as .zip archive.
query_str (str, optional) – Add custom values to the query /0/public/Nfts?filter%5Bcollection_id%5D=NCQNABO-XYCA7-JMMSDF&page_size=10
- Raises:
kraken.exceptions.KrakenException.* – If the response contains errors
- Returns:
The response
- Return type:
dict | list | aiohttp.ClientResponse
- property return_unique_id: str
Returns a unique uuid string
- Returns:
uuid
- Return type:
str
- async send_message(message: dict, *, raw: bool = False) None
Sends a message via the websocket connection. For private messages the authentication token will be assigned automatically if
raw=False.The user can specify a
req_dwithin the message to identify corresponding responses via websocket feed.- Parameters:
message (dict) – The information to send
raw (bool, optional) – If set to
Truethemessagewill be sent directly.
The following examples demonstrate how to use the
kraken.spot.SpotWSClient.send_message()function. The client must be instantiated as described inkraken.spot.SpotWSClientwhereclientuses public connections (without authentication) andclient_authmust be instantiated using valid credentials since only this way placing or canceling orders can be done.Please note that the send_message function will automatically pass the authentication token (except for the case if
raw=True).Placing orders using an authenticated websocket connection can be easily done as shown in the example below. See https://docs.kraken.com/websockets-v2/#add-order to retrieve more information about the available parameters.
Spot Websocket: Place a new order1>>> await client_auth.send_message( 2... message={ 3... "method": "add_order", 4... "params": { 5... "limit_price": 1234.56, 6... "order_type": "limit", 7... "order_userref": 123456789, 8... "order_qty": 1.0, 9... "side": "buy", 10... "symbol": "BTC/USD", 11... }, 12... } 13... )
Placing orders as batch can be done by passing
batch_addas method. Its parameters and limitations are described in https://docs.kraken.com/websockets-v2/#batch-add.Spot Websocket: Placing orders as batch1>>> await client_auth.send_message( 2... message={ 3... "method": "batch_add", 4... "params": { 5... "orders": [ 6... { 7... "limit_price": 1000.23, 8... "order_qty": 1, 9... "order_type": "limit", 10... "order_userref": 123456789, 11... "side": "buy", 12... }, 13... { 14... "limit_price": 500.21, 15... "order_qty": 2.12345, 16... "order_type": "limit", 17... "order_userref": 212345679, 18... "side": "sell", 19... "stp_type": "cancel_both", 20... }, 21... ], 22... "symbol": "BTC/USD", 23... "validate": True, 24... }, 25... } 26... )
Cancel orders as batch is available using the
batch_cancelmethod as described in https://docs.kraken.com/websockets-v2/#batch-cancel.Spot Websocket: Cancel orders as batch1>>> await client_auth.send_message( 2... message={ 3... "method": "batch_cancel", 4... "params": { 5... "orders": [ 6... "123456789", 7... "212345679", 8... "ORDER-ID123-4567890" 9... ], 10... }, 11... } 12... )
Cancel all orders can be used as the name suggests - to cancel all open orders (see https://docs.kraken.com/websockets-v2/#cancel-all-orders).
Spot Websocket: Cancel all orders1>>> await client_auth.send_message( 2... message={ 3... "method": "cancel_all", 4... } 5... )
Death Man’s Switch is a useful utility to reduce the risk of losses due to network fuck-ups since it will cancel all orders if the call was not received by Kraken within a certain amount of time. See https://docs.kraken.com/websockets-v2/#cancel-all-orders-after for more information.
Spot Websocket: Death Man’s Switch / cancel_all_orders_after1>>> await client_auth.send_message( 2... message={ 3... "method": "cancel_all_orders_after", 4... "params": {"timeout": 60}, 5... } 6... )
Canceling orders is a common task during trading and can be done as described in https://docs.kraken.com/websockets-v2/#cancel-order.
Spot Websocket: Cancel order(s)1>>> await client_auth.send_message( 2... message={ 3... "method": "cancel_order", 4... "params": { 5... "order_id": ["ORDER-ID123-456789", "ORDER-ID123-987654"], 6... }, 7... } 8... )
Editing orders can be done as shown in the example below. See https://docs.kraken.com/websockets-v2/#edit-order for more information.
Spot Websocket: Cancel order(s)1>>> await client_auth.send_message( 2... message={ 3... "method": "edit_order", 4... "params": { 5... "order_id": "ORDER-ID123-456789", 6... "order_qty": 2.5, 7... "symbol": "BTC/USD", 8... }, 9... } 10... )
Subscribing to websocket feeds can be done using the send_message function but it is recommended to use
kraken.spot.SpotWSClient.subscribe()instead.Spot Websocket: Subscribe to a websocket feed1>>> await client.send_message( 2... message={ 3... "method": "subscribe", 4... "params": {"channel": "book", "snapshot": False, "symbol": ["BTC/USD"]}, 5... } 6... )
- async start() None
Method to start the websocket connection.
- async stop() None
Method to stop the websocket connection.
- async subscribe(params: dict, req_id: int | None = None) None
Subscribe to a channel/feed
Success or failures are sent over the websocket connection and can be received via the on_message or callback function.
When accessing private endpoints and subscription feeds that need authentication make sure that the
Access WebSockets APIAPI key permission is set in the users Kraken account.See https://docs.kraken.com/websockets-v2/#channels for all channels.
Please note that this function automatically assigns the
methodkey and sets its value tosubscribe. The authentication token is also assigned automatically, so only theparamsare needed here.- Parameters:
params (dict) – The subscription message
req_id (int, optional) – Identification number that will be added to the response message sent by the websocket feed.
Initialize your client as described in
kraken.spot.SpotWSClientto run the following example:Spot Websocket: Subscribe to a websocket feed1>>> await client.subscribe( 2... params={"channel": "ticker", "symbol": ["BTC/USD"]} 3... )
- async unsubscribe(params: dict, req_id: int | None = None) None
Unsubscribe from a channel/feed
Success or failures are sent via the websocket connection and can be received via the on_message or callback function.
When accessing private endpoints and subscription feeds that need authentication make sure, that the
Access WebSockets APIAPI key permission is set in the users Kraken account.- Parameters:
params (dict) – The un-subscription message (only the params part)
Initialize your client as described in
kraken.spot.SpotWSClientto run the following example:Spot Websocket: Unsubscribe from a websocket feed1>>> await client.unsubscribe( 2... params={"channel": "ticker", "symbol": ["BTC/USD"]} 3... )