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