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