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 v1 and v2 .

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