Spot Websockets
- class kraken.spot.KrakenSpotWSClient(key: str = '', secret: str = '', url: str = '', callback: Callable | None = None, beta: bool = False)
Bases:
KrakenBaseSpotAPIClass to access public and (optional) private/authenticated websocket connection.
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 APIAPI key permission is set in the user’s account.- 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/custom url to access the Kraken API
beta (bool) – Use the beta websocket channels (maybe not supported anymore, default:
False)
HowTo: Create a Bot and integrate the python-kraken-sdk Spot Websocket Client1import asyncio 2from kraken.spot import KrakenSpotWSClient 3 4async def main() -> None: 5 class Bot(KrakenSpotWSClient): 6 7 async def on_message(self, event: dict) -> None: 8 print(event) 9 10 bot = Bot() # unauthenticated 11 auth_bot = Bot( # authenticated 12 key='kraken-api-key', 13 secret='kraken-secret-key' 14 ) 15 16 # subscribe to the desired feeds: 17 await bot.subscribe( 18 subscription={"name": ticker}, 19 pair=["XBTUSD", "DOT/EUR"] 20 ) 21 # from now on the on_message function receives the ticker feed 22 23 while not bot.exception_occur: 24 await asyncio.sleep(6) 25 26if __name__ == '__main__': 27 try: 28 asyncio.run(main()) 29 except KeyboardInterrupt: 30 pass
HowTo: Use the websocket client as context manager1import asyncio 2from kraken.spot import KrakenSpotWSClient 3 4async def on_message(msg): 5 print(msg) 6 7async def main() -> None: 8 async with KrakenSpotWSClient( 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 not bot.exception_occur:: 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:
Union[List[dict], Any]
- Raises:
ConnectionError – If there is no private connection
- property active_public_subscriptions: List[dict] | Any
Returns the active public subscriptions
- Returns:
List of active public subscriptions
- Return type:
Union[List[dict], Any]
- Raises:
ConnectionError – If there is no public connection.
- async cancel_all_orders() None
Cancel all open Spot orders.
Requires the
Access WebSockets APIandCancel/close ordersAPI key permissions.- Raises:
ValueError – If the websocket is not connected or the connection is not authenticated
- Returns:
None
Initialize your client as described in
kraken.spot.KrakenSpotWSClientto run the following example:Spot Websocket: Cancel all Orders1>>> await auth_bot.cancel_all_orders()
- async cancel_all_orders_after(timeout: int = 0) None
Set a Death Man’s Switch
Requires the
Access WebSockets APIandCancel/close ordersAPI key permissions.- Parameters:
timeout (int) – Set the timeout in seconds to cancel the orders after, set to
0to reset.- Raises:
ValueError – If the websocket is not connected or the connection is not authenticated
- Returns:
None
Initialize your client as described in
kraken.spot.KrakenSpotWSClientto run the following example:Spot Websocket: Death Man’s Switch1>>> await auth_bot.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 APIandCancel/close ordersAPI key permissions.- Parameters:
txid (List[str]) – A single or multiple transaction ids as list
- Raises:
ValueError – If the websocket is not connected or the connection is not authenticated
- Returns:
None
Initialize your client as described in
kraken.spot.KrakenSpotWSClientto run the following example:Spot Websocket: Cancel an order1>>> await auth_bot.cancel_order(txid=["OBGFYP-XVQNL-P4GMWF"])
- create_order(ordertype: str, side: str, pair: str, volume: str | int | float, price: str | int | float | None = None, price2: str | int | float | None = None, truncate: bool = False, leverage: str | int | 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, validate: bool = False, close_ordertype: str | None = None, close_price: str | int | float | None = None, close_price2: str | int | float | None = None, timeinforce: str | int | None = None) None
Create an order and submit it.
Requires the
Access WebSockets APIandCreate and modify ordersAPI key permissions.- Parameters:
ordertype (str) – The type of order, one of:
limit,marketstop-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,sellpair (str) – The asset pair to trade
volume (str | int | float) – The volume of the order that is being created
price (str | int | float, optional) – The limit price for
limitorders or the trigger price for orders withordertypeone ofstop-loss,stop-loss-limit,take-profit, andtake-profit-limitprice2 (str | int | float, optional) – The second price for
stop-loss-limitandtake-profit-limitorders (see the referenced Kraken documentation for more information)truncate (bool, optional) – If enabled: round the
priceandvolumeto Kraken’s maximum allowed decimal places. See https://support.kraken.com/hc/en-us/articles/4521313131540 fore more information about decimals.leverage (str | int | 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
validate (bool, optional) – Validate the order without placing on the market (default:
False)close_ordertype (str, optional) – Conditional close order type, one of:
limit,stop-loss,take-profit,stop-loss-limit,take-profit-limitclose_price (str | int | float, optional) – Conditional close price
close_price2 (str | int | 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)
- Raises:
ValueError – If input is not correct
- Return type:
None
Initialize your client as described in
kraken.spot.KrakenSpotWSClientto run the following example:Spot Websocket: Create an order1>>> await auth_bot.create_order( 2... ordertype="market", 3... pair="XBTUSD", 4... side="buy", 5... volume=0.001 6... ) 7>>> await auth_bot.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 | int | float | None = None, price2: str | int | float | None = None, truncate: bool = False, volume: str | int | float | None = None, oflags: str | List[str] | None = None, newuserref: str | int | None = None, validate: bool = False) None
Edit an open order that was placed on the Spot market.
Requires the
Access WebSockets APIandCreate and modify ordersAPI 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
truncate (bool, optional) – If enabled: round the
priceandvolumeto Kraken’s maximum allowed decimal places. See https://support.kraken.com/hc/en-us/articles/4521313131540 fore more information about decimals.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
validate (bool, optional) – Validate the input without applying the changes (default:
False)
- Raises:
ValueError – If input is not correct
- Return type:
None
Initialize your client as described in
kraken.spot.KrakenSpotWSClientto run the following example:Spot Websocket: Edit an order1>>> await auth_bot.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.
- Returns:
The authentication token
- Return type:
dict
- async on_message(msg: dict | list) None
Calls the defined callback function (if defined) or overload this function.
Can be overloaded as described in
kraken.spot.KrakenSpotWSClient- Parameters:
msg (dict | list) – The message received sent by Kraken via the websocket connection
- property private_sub_names: List[str]
Returns the private subscription names
- Returns:
List of private subscription names (
ownTrades,openOrders)- Return type:
List[str]
- property public_sub_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 subscribe(subscription: dict, pair: List[str] = 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 APIAPI key permission is set in the users Kraken account.- Parameters:
subscription (dict) – The subscription message
pair (List[str] | None, optional) – The pair to subscribe to
Initialize your client as described in
kraken.spot.KrakenSpotWSClientto run the following example:Spot Websocket: Subscribe to a websocket feed1>>> await bot.subscribe( 2... subscription={"name": ticker}, 3... pair=["XBTUSD", "DOT/EUR"] 4... )
- async unsubscribe(subscription: dict, pair: List[str] | None = None) None
Unsubscribe from a topic
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 APIAPI 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.KrakenSpotWSClientto run the following example:Spot Websocket: Unsubscribe from a websocket feed1>>> await bot.unsubscribe( 2... subscription={"name": ticker}, 3... pair=["XBTUSD", "DOT/EUR"] 4... )
- class kraken.spot.OrderbookClient(depth: int = 10, callback: Callable | None = None)
Bases:
objectThe 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
OrderbookClient.on_book_update()function or to the specified callback function.The
OrderbookClient.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 class1from typing import Any, Dict, List, Tuple 2from kraken.spot import OrderbookClient 3import asyncio 4 5class OrderBook(OrderbookClient): 6 async def on_book_update(self: "OrderBook", pair: str, message: list) -> None: 7 '''This function must be overloaded to get the recent updates.''' 8 book: Dict[str, Any] = self.get(pair=pair) 9 bid: List[Tuple[str, str]] = list(book["bid"].items()) 10 ask: List[Tuple[str, str]] = list(book["ask"].items()) 11 12 print("Bid Volume Ask Volume") 13 for level in range(self.depth): 14 print( 15 f"{bid[level][0]} ({bid[level][1]}) {ask[level][0]} ({ask[level][1]})" 16 ) 17 18async def main() -> None: 19 orderbook: OrderBook = OrderBook(depth=10) 20 await orderbook.add_book( 21 pairs=["XBT/USD"] # we can also subscribe to more currency pairs 22 ) 23 24 while not orderbook.exception_occur: 25 await asyncio.sleep(10) 26 27if __name__ == "__main__": 28 try: 29 asyncio.run(main()) 30 except KeyboardInterrupt: 31 pass
Example: Create and maintain a Spot orderbook using a callback1from typing import Any, Dict, List, Tuple 2from kraken.spot import OrderbookClient 3import asyncio 4 5async def my_callback(self: "OrderBook", pair: str, message: list) -> 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 pairs 13 ) 14 15 while not orderbook.exception_occur: 16 await asyncio.sleep(10) 17 18if __name__ == "__main__": 19 try: 20 asyncio.run(main()) 21 except KeyboardInterrupt: 22 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
Trueand the client instance is most likely not useable anymore. So this is the switch lets the user know, when to delete the current one and create a new one.- Returns:
Trueif any critical error occurred elseFalse- 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
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
- 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.
- async on_message(msg: list | dict) None
The on_message function is implemented in the KrakenSpotWSClient class and used as callback to receive all messages sent by the Kraken API.
This function should not be overloaded - this would break this client!
- 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