Futures Websocket

The examples presented below serve to demonstrate the usage of the Futures websocket clients provided by python-kraken-sdk to access Kraken’s Websocket API.

For questions, feedback, additions, suggestions for improvement or problems python-kraken-sdk/discussions or python-kraken-sdk/issues may be helpful.

Example access and usage for Kraken Futures Websocket API
  1#!/usr/bin/env python
  2# Copyright (C) 2023 Benjamin Thomas Schwertfeger
  3# GitHub: https://github.com/btschwertfeger
  4#
  5
  6"""
  7Module that provides an example usage for the Kraken Futures websocket client.
  8"""
  9
 10from __future__ import annotations
 11
 12import asyncio
 13import logging
 14import logging.config
 15import os
 16import time
 17from contextlib import suppress
 18
 19from kraken.futures import FuturesWSClient
 20
 21logging.basicConfig(
 22    format="%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s",
 23    datefmt="%Y/%m/%d %H:%M:%S",
 24    level=logging.INFO,
 25)
 26logging.getLogger("requests").setLevel(logging.WARNING)
 27logging.getLogger("urllib3").setLevel(logging.WARNING)
 28
 29
 30# Custom client
 31class Client(FuturesWSClient):
 32    """Can be used to create a custom trading strategy"""
 33
 34    async def on_message(self: Client, message: list | dict) -> None:
 35        """Receives the websocket messages"""
 36        logging.info(message)
 37        # … apply your trading strategy in this class
 38        # … you can also combine this with the Futures REST clients
 39
 40
 41async def main() -> None:
 42    """Create a client and subscribe to channels/feeds"""
 43
 44    key = os.getenv("FUTURES_API_KEY")
 45    secret = os.getenv("FUTURES_SECRET_KEY")
 46
 47    # _____Public_Websocket_Feeds___________________
 48    client = Client()
 49    await client.start()
 50    # print(client.get_available_public_subscription_feeds())
 51
 52    products = ["PI_XBTUSD", "PF_SOLUSD"]
 53    # subscribe to a public websocket feed
 54    await client.subscribe(feed="ticker", products=products)
 55    await client.subscribe(feed="book", products=products)
 56    # await client.subscribe(feed='trade', products=products)
 57    # await client.subscribe(feed='ticker_lite', products=products)
 58    # await client.subscribe(feed='heartbeat')
 59    # time.sleep(2)
 60
 61    # unsubscribe from a websocket feed
 62    time.sleep(2)  # in case subscribe is not done yet
 63    # await client.unsubscribe(feed='ticker', products=['PI_XBTUSD'])
 64    await client.unsubscribe(feed="ticker", products=["PF_XBTUSD"])
 65    await client.unsubscribe(feed="book", products=products)
 66    # ...
 67
 68    # _____Private_Websocket_Feeds_________________
 69    if key and secret:
 70        client_auth = Client(key=key, secret=secret)
 71        await client_auth.start()
 72        # print(client_auth.get_available_private_subscription_feeds())
 73
 74        # subscribe to a private/authenticated websocket feed
 75        await client_auth.subscribe(feed="fills")
 76        await client_auth.subscribe(feed="open_positions")
 77        # await client_auth.subscribe(feed='open_orders')
 78        # await client_auth.subscribe(feed='open_orders_verbose')
 79        # await client_auth.subscribe(feed='deposits_withdrawals')
 80        # await client_auth.subscribe(feed='account_balances_and_margins')
 81        # await client_auth.subscribe(feed='balances')
 82        # await client_auth.subscribe(feed='account_log')
 83        # await client_auth.subscribe(feed='notifications_auth')
 84
 85        # authenticated clients can also subscribe to public feeds
 86        # await client_auth.subscribe(feed='ticker', products=['PI_XBTUSD', 'PF_ETHUSD'])
 87
 88        # time.sleep(1)
 89        # unsubscribe from a private/authenticated websocket feed
 90        await client_auth.unsubscribe(feed="fills")
 91        await client_auth.unsubscribe(feed="open_positions")
 92        # ...
 93
 94    while not client.exception_occur:  # and not client_auth.exception_occur:
 95        await asyncio.sleep(6)
 96
 97
 98if __name__ == "__main__":
 99    with suppress(KeyboardInterrupt):
100        asyncio.run(main())
101    # the websocket client will send {'event': 'asyncio.CancelledError'} via on_message
102    # so you can handle the behavior/next actions individually within you strategy
103
104# ============================================================
105# Alternative - as ContextManager:
106
107# from kraken.futures import KrakenFuturesWSClient
108# import asyncio
109
110# async def on_message(message):
111#     print(message)
112
113# async def main() -> None:
114#     async with KrakenFuturesWSClient(callback=on_message) as session:
115#         await session.subscribe(feed="ticker", products=["PF_XBTUSD"])
116#     while True:
117#         await asyncio.sleep(6)
118
119# if __name__ == "__main__":
120#     try:
121#         asyncio.run(main())
122#     except KeyboardInterrupt:
123#         pass