Spot Websockets

class kraken.spot.KrakenSpotWSClientV2(key: str = '', secret: str = '', callback: Callable | None = None, *, no_public: bool = False, beta: bool = False)

Bases: KrakenSpotWSClientBase

This client only supports the Kraken Websocket API v2.

Class to access public and private/authenticated websocket connections.

… please use kraken.spot.KrakenSpotWSClientV1 for accessing the Kraken’s Websocket API v1.

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.KrakenSpotWSClientV2.subscribe() and kraken.spot.KrakenSpotWSClientV2.send_message() for more information.

When accessing private endpoints that need authentication make sure, that the Access WebSockets API API 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 to False, the client will create a public and a private connection per default. If only a private connection is required, this parameter should be set to True.

  • beta (bool) – Use the beta websocket channels (maybe not supported anymore, default: False)

HowTo: Use the Kraken Spot websocket client (v2)
 1import asyncio
 2from kraken.spot import KrakenSpotWSClientV2
 3
 4
 5class Client(KrakenSpotWSClientV2):
 6
 7    async def on_message(self, message):
 8        print(message)
 9
10
11async def main():
12
13    client = Client()         # unauthenticated
14    client_auth = Client(     # authenticated
15        key="kraken-api-key",
16        secret="kraken-secret-key"
17    )
18
19    # subscribe to the desired feeds:
20    await client.subscribe(
21        params={"channel": "ticker", "symbol": ["BTC/USD"]}
22    )
23    # from now on the on_message function receives the ticker feed
24
25    while not client.exception_occur:
26        await asyncio.sleep(6)
27
28if __name__ == "__main__":
29    try:
30        asyncio.run(main())
31    except KeyboardInterrupt:
32        pass
HowTo: Use the websocket client (v2) as instance
 1import asyncio
 2from kraken.spot import KrakenSpotWSClientV2
 3
 4
 5async def main():
 6    async def on_message(message):
 7        print(message)
 8
 9    client = KrakenSpotWSClientV2(callback=on_message)
10    await client.subscribe(
11        params={"channel": "ticker", "symbol": ["BTC/USD"]}
12    )
13
14    while not client.exception_occur:
15        await asyncio.sleep(10)
16
17
18if __name__ == "__main__":
19    try:
20        asyncio.run(main())
21    except KeyboardInterrupt:
22        pass
HowTo: Use the websocket client (v2) as context manager
 1import asyncio
 2from kraken.spot import KrakenSpotWSClientV2
 3
 4async def on_message(message):
 5    print(message)
 6
 7async def main():
 8    async with KrakenSpotWSClientV2(
 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] | Any

Returns the active private subscriptions

Returns:

List of active private subscriptions

Return type:

list[dict] | Any

Raises:

ConnectionError – If there is no active private connection

property active_public_subscriptions: list[dict] | Any

Returns the active public subscriptions

Returns:

List of active public subscriptions

Return type:

list[dict] | Any

Raises:

ConnectionError – If there is no active public connection.

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.KrakenSpotWSClientV1 and kraken.spot.KrakenSpotWSClientV2 for 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 channel when un-/subscribing from/to private feeds that need authentication.

See https://docs.kraken.com/websockets-v2/#channels for all channels.

Currently there is only one private channel (June 2023):

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 channel when un-/subscribing from/to public feeds without authentication.

See https://docs.kraken.com/websockets-v2/#channels for all channels.

The available public channels are listed below:

Returns:

List of available public channel names

Return type:

list[str]

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_d within the message to identify corresponding responses via websocket feed.

Parameters:
  • message (dict) – The information to send

  • raw (bool, optional) – If set to True the message will be sent directly.

The following examples demonstrate how to use the kraken.spot.KrakenSpotWSClientV2.send_message() function. The client must be instantiated as described in kraken.spot.KrakenSpotWSClientV2 where client uses public connections (without authentication) and client_auth must 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 v2: Place a new order
 1>>> 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_add as method. Its parameters and limitations are described in https://docs.kraken.com/websockets-v2/#batch-add.

Spot Websocket v2: Placing orders as batch
 1>>> 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_cancel method as described in https://docs.kraken.com/websockets-v2/#batch-cancel.

Spot Websocket v2: Cancel orders as batch
 1>>> 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 v2: Cancel all orders
1>>> 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 fuckups 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 v2: Death Man’s Switch / cancel_all_orders_after
1>>> 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 v2: 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 v2: 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.KrakenSpotWSClientV2.subscribe() instead.

Spot Websocket v2: Subscribe to a websocket feed
1>>> await client.send_message(
2...     message={
3...         "method": "subscribe",
4...         "params": {"channel": "book", "snapshot": False, "symbol": ["BTC/USD"]},
5...     }
6... )
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 API API 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 method key and sets its value to subscribe. The authentication token is also assigned automatically, so only the params are 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.KrakenSpotWSClientV2 to run the following example:

Spot Websocket v2: Subscribe to a websocket feed
1>>> 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 API API key permission is set in the users Kraken account.

Parameters:

params (dict) – The unsubscription message (only the params part)

Initialize your client as described in kraken.spot.KrakenSpotWSClientV2 to run the following example:

Spot Websocket v2: Unsubscribe from a websocket feed
1>>> await client.unsubscribe(
2...     params={"channel": "ticker", "symbol": ["BTC/USD"]}
3... )
class kraken.spot.KrakenSpotWSClientV1(key: str = '', secret: str = '', callback: Callable | None = None, *, no_public: bool = False, beta: bool = False)

Bases: KrakenSpotWSClientBase

Deprecated since version v2.2.0.

Class to access public and private/authenticated websocket connections.

This client only supports the Kraken Websocket API v1.

… please use KrakenSpotWSClientV2 for accessing the Kraken Websockets API v2.

This class holds up to two websocket connections, one private and one public.

When accessing private endpoints that need authentication make sure, that the Access WebSockets API API 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 to False, the client will create a public and a private connection per default. If only a private connection is required, this parameter should be set to True.

  • beta (bool) – Use the beta websocket channels (maybe not supported anymore, default: False)

HowTo: Use the Kraken Spot websocket client (v1)
 1import asyncio
 2from kraken.spot import KrakenSpotWSClientV1
 3
 4
 5class Client(KrakenSpotWSClientV1):
 6
 7    async def on_message(self, message):
 8        print(message)
 9
10
11async def main():
12
13    client = Client()         # unauthenticated
14    client_auth = Client(     # authenticated
15        key="kraken-api-key",
16        secret="kraken-secret-key"
17    )
18
19    # subscribe to the desired feeds:
20    await client.subscribe(
21        subscription={"name": ticker},
22        pair=["XBTUSD", "DOT/EUR"]
23    )
24    # from now on the on_message function receives the ticker feed
25
26    while not client.exception_occur:
27        await asyncio.sleep(6)
28
29if __name__ == "__main__":
30    try:
31        asyncio.run(main())
32    except KeyboardInterrupt:
33        pass
HowTo: Use the websocket client (v1) as instance
 1import asyncio
 2from kraken.spot import KrakenSpotWSClientV1
 3
 4
 5async def main() -> None:
 6    async def on_message(message) -> None:
 7        print(message)
 8
 9    client = KrakenSpotWSClientV1(callback=on_message)
10    await client.subscribe(
11        subscription={"name": "ticker"},
12        pair=["XBT/USD"]
13    )
14
15    while not client.exception_occur:
16        await asyncio.sleep(10)
17
18
19if __name__ == "__main__":
20    try:
21        asyncio.run(main())
22    except KeyboardInterrupt:
23        pass
HowTo: Use the websocket client (v1) as context manager
 1import asyncio
 2from kraken.spot import KrakenSpotWSClientV1
 3
 4async def on_message(message):
 5    print(message)
 6
 7async def main() -> None:
 8    async with KrakenSpotWSClientV1(
 9        key="api-key",
10        secret="secret-key",
11        callback=on_message
12    ) as session:
13        await session.subscribe(
14            subscription={"name": "ticker"},
15            pair=["XBT/USD"]
16        )
17
18    while True
19        await asyncio.sleep(6)
20
21
22if __name__ == "__main__":
23    try:
24        asyncio.run(main())
25    except KeyboardInterrupt:
26        pass
property active_private_subscriptions: list[dict] | Any

Returns the active private subscriptions

Returns:

List of active private subscriptions

Return type:

list[dict] | Any

Raises:

ConnectionError – If there is no active private connection

property active_public_subscriptions: list[dict] | Any

Returns the active public subscriptions

Returns:

List of active public subscriptions

Return type:

list[dict] | Any

Raises:

ConnectionError – If there is no active public connection.

async cancel_all_orders() None

Cancel all open Spot orders.

Requires the Access WebSockets API and Cancel/close orders API key permissions.

Raises:

KrakenAuthenticationError – If the websocket is not connected or the connection is not authenticated

Returns:

None

Initialize your client as described in kraken.spot.KrakenSpotWSClientV1 to run the following example:

Spot Websocket: Cancel all Orders
1>>> await client_auth.cancel_all_orders()
async cancel_all_orders_after(timeout: int = 0) None

Set a Death Man’s Switch

Requires the Access WebSockets API and Cancel/close orders API key permissions.

Parameters:

timeout (int) – Set the timeout in seconds to cancel the orders after, set to 0 to reset.

Raises:

KrakenAuthenticationError – If the websocket is not connected or the connection is not authenticated

Returns:

None

Initialize your client as described in kraken.spot.KrakenSpotWSClientV1 to run the following example:

Spot Websocket: Death Man’s Switch
1>>> await client_auth.cancel_all_orders_after(timeout=60)
async cancel_order(txid: list[str]) None

Cancel a specific order or a list of orders.

Requires the Access WebSockets API and Cancel/close orders API key permissions.

Parameters:

txid (list[str]) – A single or multiple transaction ids as list

Raises:

KrakenAuthenticationError – If the websocket is not connected or the connection is not authenticated

Returns:

None

Initialize your client as described in kraken.spot.KrakenSpotWSClientV1 to run the following example:

Spot Websocket: Cancel an order
1>>> await client_auth.cancel_order(txid=["OBGFYP-XVQNL-P4GMWF"])
create_order(ordertype: str, side: str, pair: str, volume: str | float, price: str | float | None = None, price2: str | float | None = None, leverage: str | float | None = None, oflags: str | list[str] | None = None, starttm: str | int | None = None, expiretm: str | int | None = None, deadline: str | None = None, userref: str | int | None = None, close_ordertype: str | None = None, close_price: str | float | None = None, close_price2: str | float | None = None, timeinforce: str | int | None = None, *, truncate: bool = False, validate: bool = False) None

Create an order and submit it.

Requires the Access WebSockets API and Create and modify orders API key permissions.

Parameters:
  • ordertype (str) – The type of order, one of: limit, market, stop-loss, take-profit, stop-loss-limit, settle-position, take-profit-limit (see: https://support.kraken.com/hc/en-us/sections/200577136-Order-types)

  • side (str) – The side - one of buy, sell

  • pair (str) – The asset pair to trade

  • volume (str | float) – The volume of the order that is being created

  • price (str | float, optional) – The limit price for limit orders or the trigger price for orders with ordertype one of stop-loss, stop-loss-limit, take-profit, and take-profit-limit

  • price2 (str | float, optional) – The second price for stop-loss-limit and take-profit-limit orders (see the referenced Kraken documentation for more information)

  • leverage (str | float, optional) – The leverage

  • oflags (str | list[str], optional) – Order flags like post, fcib, fciq, nomp, viqc (see the referenced Kraken documentation for more information)

  • starttm (str | int, optional) – Unix timestamp or seconds defining the start time (default: "0")

  • expiretim (str) – Unix timestamp or time in seconds defining the expiration of the order (default: "0" - i.e., no expiration)

  • deadline (str) – RFC3339 timestamp + {0..60} seconds that defines when the matching engine should reject the order.

  • userref (int) – User reference id for example to group orders

  • close_ordertype (str, optional) – Conditional close order type, one of: limit, stop-loss, take-profit, stop-loss-limit, take-profit-limit

  • close_price (str | float, optional) – Conditional close price

  • close_price2 (str | float, optional) – Second conditional close price

  • timeinforce (str, optional) – How long the order remains in the orderbook, one of: GTC, IOC, GTD (see the referenced Kraken documentation for more information)

  • truncate (bool, optional) – If enabled: round the price and volume to Kraken’s maximum allowed decimal places. See https://support.kraken.com/hc/en-us/articles/4521313131540 fore more information about decimals.

  • validate (bool, optional) – Validate the order without placing on the market (default: False)

Raises:
  • KrakenAuthenticationError – If the websocket is not connected or the connection is not authenticated

  • ValueError – If input is not correct

Return type:

None

Initialize your client as described in kraken.spot.KrakenSpotWSClientV1 to run the following example:

Spot Websocket: Create an order
 1>>> await client_auth.create_order(
 2...     ordertype="market",
 3...     pair="XBTUSD",
 4...     side="buy",
 5...     volume=0.001
 6... )
 7>>> await client_auth.create_order(
 8...     ordertype="limit",
 9...     side="buy",
10...     pair="XBTUSD",
11...     volume=0.02,
12...     price=23000,
13...     expiretm=120,
14...     oflags=["post", "fcib"]
15... )
edit_order(orderid: str, reqid: str | int | None = None, pair: str | None = None, price: str | float | None = None, price2: str | float | None = None, volume: str | float | None = None, oflags: str | list[str] | None = None, newuserref: str | int | None = None, *, truncate: bool = False, validate: bool = False) None

Edit an open order that was placed on the Spot market.

Requires the Access WebSockets API and Create and modify orders API key permissions.

Parameters:
  • orderId (str) – The orderId of the order to edit

  • reqid (str | int, optional) – Filter by reqid

  • pair (str, optional) – Filter by pair

  • price (str | int | float, optional) – Set a new price

  • price2 (str | int | float, optional) – Set a new second price

  • volume (str | int | float, optional) – Set a new volume

  • oflags (str | list[str], optional) – Set new oflags (overwrite old ones)

  • newuserref (str | int, optional) – Set a new user reference id

  • truncate (bool, optional) – If enabled: round the price and volume to Kraken’s maximum allowed decimal places. See https://support.kraken.com/hc/en-us/articles/4521313131540 fore more information about decimals.

  • validate (bool, optional) – Validate the input without applying the changes (default: False)

Raises:
  • KrakenAuthenticationError – If the websocket is not connected or the connection is not authenticated

  • ValueError – If input is not correct

Return type:

None

Initialize your client as described in kraken.spot.KrakenSpotWSClientV1 to run the following example:

Spot Websocket: Edit an order
1>>> await client_auth.edit_order(
2...     orderId="OBGFYP-XVQNL-P4GMWF",
3...     volume=0.75,
4...     pair="XBTUSD",
5...     price=20000
6... )
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.KrakenSpotWSClientV1 and kraken.spot.KrakenSpotWSClientV2 for 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 private subscription names

Returns:

List of private subscription names (ownTrades, openOrders)

Return type:

list[str]

property public_channel_names: list[str]

Returns the public subscription names

Returns:

List of public subscription names (ticker, spread, book, ohlc, trade, *)

Return type:

list[str]

property return_unique_id: str

Returns a unique uuid string

Returns:

uuid

Return type:

str

async send_message(message: dict, *, private: bool = False, 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 reqid within the message to identify corresponding responses via websocket feed.

Parameters:
  • message (dict) – The content to send

  • private (bool, optional) – Use authentication (default: False)

  • raw (bool, optional) – If set to True the message will be sent directly.

async subscribe(subscription: dict, pair: list[str] | None = None) None

Subscribe to a channel

Success or failures are sent over the websocket connection and can be received via the on_message callback function.

When accessing private endpoints and subscription feeds that need authentication make sure, that the Access WebSockets API API key permission is set in the users Kraken account.

Parameters:
  • subscription (dict) – The subscription message

  • pair (list[str], optional) – The pair to subscribe to

Initialize your client as described in kraken.spot.KrakenSpotWSClientV1 to run the following example:

Spot Websocket v1: Subscribe to a websocket feed
1>>> await client.subscribe(
2...     subscription={"name": ticker},
3...     pair=["XBTUSD", "DOT/EUR"]
4... )
async unsubscribe(subscription: dict, pair: list[str] | None = None) None

Unsubscribe from a 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 API API key permission is set in the users Kraken account.

Parameters:
  • subscription (dict) – The subscription to unsubscribe from

  • pair (list[str], optional) – The pair or list of pairs to unsubscribe

Initialize your client as described in kraken.spot.KrakenSpotWSClientV1 to run the following example:

Spot Websocket v1: Unsubscribe from a websocket feed
1>>> await client.unsubscribe(
2...     subscription={"name": ticker},
3...     pair=["XBTUSD", "DOT/EUR"]
4... )
class kraken.spot.OrderbookClientV2(depth: int = 10, callback: Callable | None = None)

Bases: object

This 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 within on_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 class
 1from typing import Any
 2from kraken.spot import OrderbookClientV2
 3import asyncio
 4
 5class OrderBook(OrderbookClientV2):
 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) await orderbook.add_book(
22        pairs=["XBT/USD"]  # we can also subscribe to more currency
23        pairs
24    )
25
26    while not orderbook.exception_occur:
27        await asyncio.sleep(10)
28
29if __name__ == "__main__":
30    try:
31        asyncio.run(main())
32    except KeyboardInterrupt:
33        pass
Example: Create and maintain a Spot orderbook using a callback
 1from typing import Any
 2from kraken.spot import OrderbookClientV2
 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.add_book(
12        pairs=["XBT/USD"]  # we can also subscribe to more currency
13        pairs
14    )
15
16    while not orderbook.exception_occur:
17        await asyncio.sleep(10)
18
19if __name__ == "__main__":
20    try:
21        asyncio.run(main())
22    except KeyboardInterrupt:
23        pass
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

property depth: int

Return the fixed depth of this orderbook client.

property exception_occur: bool

Can be used to determine if any critical error occurred within the websocket connection. If so, the function will return True and the client instance is most likely not usable anymore. So this is the switch lets the user know, when to delete the current one and create a new one.

Returns:

True if any critical error occurred else False

Return type:

bool

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 sorted method 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 values as float.

Return type:

float

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.

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

class kraken.spot.OrderbookClientV1(depth: int = 10, callback: Callable | None = None)

Bases: object

This client is using the Kraken Websocket API v1

Please use kraken.spot.OrderbookClientV2 to access the Kraken Websocket API v2.

The orderbook client can be used for instantiation and maintaining one or multiple orderbooks for Spot trading on the Kraken cryptocurrency exchange. It connects to the websocket feed(s) and receives the book updates, calculates the checksum and will publish the changes to the on_book_update() function or to the specified callback function.

The get() function can be used to access a specific book of this client.

The client will resubscribe to the book feed(s) if any errors occur and publish the changes to the mentioned function(s).

This class has a fixed book depth. Available depths are: {10, 25, 50, 100}

Example: Create and maintain a Spot orderbook as custom class
 1from typing import Any
 2from kraken.spot import OrderbookClientV1
 3import asyncio
 4
 5class OrderBook(OrderbookClientV1):
 6    async def on_book_update(self: "OrderBook", pair: str, message: list) -> None:
 7        '''This function must be overloaded to get the recent
 8        updates.''' book: Dict[str, Any] = self.get(pair=pair) bid:
 9        list[tuple[str, str]] = list(book["bid"].items()) ask:
10        list[tuple[str, str]] = list(book["ask"].items())
11
12        print("Bid         Volume                Ask         Volume") for level in
13        range(self.depth):
14            print(
15                f"{bid[level][0]} ({bid[level][1]})      {ask[level][0]}
16                ({ask[level][1]})"
17            )
18
19async def main() -> None:
20    orderbook: OrderBook = OrderBook(depth=10) await orderbook.add_book(
21        pairs=["XBT/USD"]  # we can also subscribe to more currency
22        pairs
23    )
24
25    while not orderbook.exception_occur:
26        await asyncio.sleep(10)
27
28if __name__ == "__main__":
29    try:
30        asyncio.run(main())
31    except KeyboardInterrupt:
32        pass
Example: Create and maintain a Spot orderbook using a callback
 1from typing import Any
 2from kraken.spot import OrderbookClientV1
 3import asyncio
 4
 5# … use the Orderbook class defined in the example before
 6async def my_callback(self: "OrderBook", pair: str, message: list) -> None:
 7    '''This function do not need to be async.''' print(message)
 8
 9async def main() -> None:
10    orderbook: OrderBook = OrderBook(depth=100, callback=my_callback)
11    await orderbook.add_book(
12        pairs=["XBT/USD"]  # we can also subscribe to more currency
13        pairs
14    )
15
16    while not orderbook.exception_occur:
17        await asyncio.sleep(10)
18
19if __name__ == "__main__":
20    try:
21        asyncio.run(main())
22    except KeyboardInterrupt:
23        pass
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

property depth: int

Return the fixed depth of this orderbook client.

property exception_occur: bool

Can be used to determine if any critical error occurred within the websocket connection. If so, the function will return True and the client instance is most likely not usable anymore. So this is the switch lets the user know, when to delete the current one and create a new one.

Returns:

True if any critical error occurred else False

Return type:

bool

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

OrderbookClientV1: Get ask and bid
 1# …
 2class Orderbook(OrderbookClientV1):
 3
 4    async def on_book_update(
 5        self: "Orderbook",
 6        pair: str,
 7        message: list
 8    ) -> None:
 9        book: dict[str, Any] = self.get(pair="XBT/USD")
10        ask: list[tuple[str, str]] = list(book["ask"].items())
11        bid: list[tuple[str, str]] = list(book["bid"].items())
12        # ask and bid are now in format [price, (volume, timestamp)]
13        # … and include the whole orderbook
static get_first(values: tuple) float

This function is used as callback for the sorted method 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 values as float.

Return type:

float

async on_book_update(pair: str, message: list) 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 (str) – The message sent by Kraken causing the orderbook to update.

async on_message(message: list | dict) None

This function should not be overloaded - this 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.

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