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)
 28LOG: logging.Logger = logging.getLogger(__name__)
 29
 30
 31# Custom client
 32class Client(FuturesWSClient):
 33    """Can be used to create a custom trading strategy"""
 34
 35    async def on_message(self: Client, message: list | dict) -> None:
 36        """Receives the websocket messages"""
 37        LOG.info(message)
 38        # … apply your trading strategy in this class
 39        # … you can also combine this with the Futures REST clients
 40
 41
 42async def main() -> None:
 43    """Create a client and subscribe to channels/feeds"""
 44
 45    key = os.getenv("FUTURES_API_KEY")
 46    secret = os.getenv("FUTURES_SECRET_KEY")
 47
 48    # _____Public_Websocket_Feeds___________________
 49    client = Client()
 50    await client.start()
 51    # print(client.get_available_public_subscription_feeds())
 52
 53    products = ["PI_XBTUSD", "PF_SOLUSD"]
 54    # subscribe to a public websocket feed
 55    await client.subscribe(feed="ticker", products=products)
 56    await client.subscribe(feed="book", products=products)
 57    # await client.subscribe(feed='trade', products=products)
 58    # await client.subscribe(feed='ticker_lite', products=products)
 59    # await client.subscribe(feed='heartbeat')
 60    # time.sleep(2)
 61
 62    # unsubscribe from a websocket feed
 63    time.sleep(2)  # in case subscribe is not done yet
 64    # await client.unsubscribe(feed='ticker', products=['PI_XBTUSD'])
 65    await client.unsubscribe(feed="ticker", products=["PF_XBTUSD"])
 66    await client.unsubscribe(feed="book", products=products)
 67    # ...
 68
 69    # _____Private_Websocket_Feeds_________________
 70    if key and secret:
 71        client_auth = Client(key=key, secret=secret)
 72        await client_auth.start()
 73        # print(client_auth.get_available_private_subscription_feeds())
 74
 75        # subscribe to a private/authenticated websocket feed
 76        await client_auth.subscribe(feed="fills")
 77        await client_auth.subscribe(feed="open_positions")
 78        # await client_auth.subscribe(feed='open_orders')
 79        # await client_auth.subscribe(feed='open_orders_verbose')
 80        # await client_auth.subscribe(feed='deposits_withdrawals')
 81        # await client_auth.subscribe(feed='account_balances_and_margins')
 82        # await client_auth.subscribe(feed='balances')
 83        # await client_auth.subscribe(feed='account_log')
 84        # await client_auth.subscribe(feed='notifications_auth')
 85
 86        # authenticated clients can also subscribe to public feeds
 87        # await client_auth.subscribe(feed='ticker', products=['PI_XBTUSD', 'PF_ETHUSD'])
 88
 89        # time.sleep(1)
 90        # unsubscribe from a private/authenticated websocket feed
 91        await client_auth.unsubscribe(feed="fills")
 92        await client_auth.unsubscribe(feed="open_positions")
 93        # ...
 94
 95    while not client.exception_occur:  # and not client_auth.exception_occur:
 96        await asyncio.sleep(6)
 97
 98
 99if __name__ == "__main__":
100    with suppress(KeyboardInterrupt):
101        asyncio.run(main())
102    # the websocket client will send {'event': 'asyncio.CancelledError'} via on_message
103    # so you can handle the behavior/next actions individually within you strategy
104
105# ============================================================
106# Alternative - as ContextManager:
107
108# from kraken.futures import KrakenFuturesWSClient
109# import asyncio
110
111# async def on_message(message):
112#     print(message)
113
114# async def main() -> None:
115#     async with KrakenFuturesWSClient(callback=on_message) as session:
116#         await session.subscribe(feed="ticker", products=["PF_XBTUSD"])
117#     while True:
118#         await asyncio.sleep(6)
119
120# if __name__ == "__main__":
121#     try:
122#         asyncio.run(main())
123#     except KeyboardInterrupt:
124#         pass