Futures REST
The examples presented below serve to demonstrate the usage of the Futures REST clients provided by python-kraken-sdk to access Kraken’s REST API.
For questions, feedback, additions, suggestions for improvement or problems python-kraken-sdk/discussions or python-kraken-sdk/issues may be helpful.
See https://docs.kraken.com/api/docs/guides/global-intro for information about the available endpoints and their usage.
The Futures client provides access to all un-and authenticated endpoints of Kraken’s Futures API.
1from kraken.futures import FuturesClient
2
3client = FuturesClient(key="<your-api-key>", secret="<your-secret-key>")
4print(client.request("GET", "/derivatives/api/v3/accounts"))
The async Futures client allows for asynchronous access to Kraken’s Futures endpoints. Below are two examples demonstrating its usage.
Using FuturesAsyncClient without a context manager; In this example, the client is manually closed after the request is made.
1import asyncio
2from kraken.futures import FuturesAsyncClient
3
4async def main():
5 client = FuturesAsyncClient(key="<your-api-key>", secret="<your-secret-key>")
6 try:
7 response = await client.request("GET", "/derivatives/api/v3/accounts")
8 print(response)
9 finally:
10 await client.async_close()
11
12asyncio.run(main())
Using FuturesAsyncClient as context manager; This example demonstrates the use of the context manager, which ensures the client is automatically closed after the request is completed.
1import asyncio
2from kraken.futures import FuturesAsyncClient
3
4async def main():
5 async with FuturesAsyncClient(
6 key="<your-api-key>", secret="<your-secret-key>"
7 ) as client:
8 response = await client.request("GET", "/derivatives/api/v3/accounts")
9 print(response)
10
11asyncio.run(main())
The following legacy examples are not maintained on a regular basis. They serve only for demonstration purposes - make sure to checkout the documentation of the individual functions.
1#!/usr/bin/env python
2# Copyright (C) 2023 Benjamin Thomas Schwertfeger
3# GitHub: https://github.com/btschwertfeger
4#
5
6"""
7Module that implements some example usage for the Kraken Futures REST clients.
8
9This module may not be maintained on a regular basis, so please refer to the
10unit tests of this package as they provide a much deeper dive into the usage.
11"""
12
13import logging
14import os
15import time
16from pathlib import Path
17
18from kraken.futures import Funding, Market, Trade, User
19
20logging.basicConfig(
21 format="%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s",
22 datefmt="%Y/%m/%d %H:%M:%S",
23 level=logging.INFO,
24)
25logging.getLogger("requests").setLevel(logging.WARNING)
26logging.getLogger("urllib3").setLevel(logging.WARNING)
27
28key = os.getenv("FUTURES_SANDBOX_KEY")
29secret = os.getenv("FUTURES_SANDBOX_SECRET")
30
31
32def market_examples() -> None:
33 """Example market client usage"""
34 # market = Market()
35 # print(market.get_tick_types())
36 # print(market.get_tradeable_products(tick_type='trade'))
37 # print(market.get_resolutions(tick_type='trade', tradeable='PI_XBTUSD'))
38 # print(market.get_ohlc(tick_type='trade', symbol='PI_XBTUSD', resolution='5m', from_='1668989233'))
39 # print(market.get_fee_schedules())
40 # # print(market.get_orderbook(symbol='fi_xbtusd_180615')) # this endpoint is broken
41 # print(market.get_tickers())
42 # print(market.get_instruments())
43 # print(market.get_instruments_status())
44 # print(market.get_instruments_status(instrument='PI_XBTUSD'))
45 # print(market.get_trade_history(symbol='PI_XBTUSD'))
46 # print(market.get_historical_funding_rates(symbol='PI_XBTUSD'))
47 # time.sleep(2)
48
49 priv_market = Market(key=key, secret=secret, sandbox=True)
50 # print(priv_market.get_fee_schedules_vol())
51 print(priv_market.get_leverage_preference())
52 # print(priv_market.set_leverage_preference(symbol='PF_XBTUSD', maxLeverage=2)) # set max leverage
53 # print(priv_market.set_leverage_preference(symbol='PF_XBTUSD')) # reset max leverage
54 # print(priv_market.set_pnl_preference(symbol='PF_XBTUSD', pnlPreference='BTC'))
55
56 # time.sleep(2)
57 # print(priv_market.get_execution_events())
58 # print(market.get_public_execution_events(tradeable='PI_XBTUSD'))
59 # print(market.get_public_order_events(tradeable='PI_XBTUSD'))
60 # print(market.get_public_mark_price_events(tradeable='PI_XBTUSD'))
61 # print(priv_market.get_order_events())
62 # print(priv_market.get_trigger_events())
63
64
65def user_examples() -> None:
66 """Example User client usage"""
67 user = User(key=key, secret=secret, sandbox=True)
68 print(user.get_wallets())
69
70 print(user.get_subaccounts())
71 print(user.get_unwind_queue())
72 print(user.get_notifications())
73
74 print(user.get_open_positions())
75 print(user.get_open_orders())
76
77 print(user.get_account_log(before="1604937694000"))
78 print(user.get_account_log(info="futures liquidation"))
79 time.sleep(2)
80 response = user.get_account_log_csv()
81 assert response.status_code in {200, "200"}
82 with Path("account_log.csv").open("wb") as file:
83 for chunk in response.iter_content(chunk_size=512):
84 if chunk:
85 file.write(chunk)
86
87
88def trade_examples() -> None:
89 """Example Trade client usage"""
90 raise ValueError(
91 "Attention: Please check if you really want to execute the trade endpoints!",
92 )
93 trade = Trade(key=key, secret=secret, sandbox=True)
94 print(trade.get_fills())
95 print(trade.get_fills(lastFillTime="2020-07-21T12:41:52.790Z"))
96 print(
97 trade.create_batch_order(
98 batchorder_list=[
99 {
100 "order": "send",
101 "order_tag": "1",
102 "orderType": "lmt",
103 "symbol": "PI_XBTUSD",
104 "side": "buy",
105 "size": 1,
106 "limitPrice": 1.00,
107 },
108 {
109 "order": "send",
110 "order_tag": "2",
111 "orderType": "stp",
112 "symbol": "PI_XBTUSD",
113 "side": "buy",
114 "size": 1,
115 "limitPrice": 2.00,
116 "stopPrice": 3.00,
117 },
118 {
119 "order": "cancel",
120 "order_id": "e35d61dd-8a30-4d5f-a574-b5593ef0c050",
121 },
122 {
123 "order": "cancel",
124 "cliOrdId": 123456789,
125 },
126 ],
127 ),
128 )
129 print(trade.cancel_all_orders())
130 print(trade.cancel_all_orders(symbol="pi_xbtusd"))
131 print(trade.dead_mans_switch(timeout=60))
132 print(trade.dead_mans_switch(timeout=0)) # to deactivate
133 print(trade.cancel_order(order_id="some order id"))
134 print(
135 trade.edit_order(
136 orderId="some order id",
137 size=300,
138 limitPrice=401,
139 stopPrice=350,
140 ),
141 )
142 print(trade.get_orders_status(orderIds=["orderid1", "orderid2"]))
143 print(
144 trade.create_order(
145 orderType="lmt",
146 side="buy",
147 size=1,
148 limitPrice=4,
149 symbol="pf_bchusd",
150 ),
151 )
152 print(
153 trade.create_order(
154 orderType="take_profit",
155 side="buy",
156 size=1,
157 symbol="pf_bchusd",
158 stopPrice=100,
159 triggerSignal="mark",
160 ),
161 )
162
163
164def funding_examples() -> None:
165 """Example Funding client usage"""
166 funding = Funding(key=key, secret=secret, sandbox=True)
167 print(funding.get_historical_funding_rates(symbol="PF_SOLUSD"))
168
169
170def main() -> None:
171 user_examples()
172 market_examples()
173 trade_examples()
174 funding_examples()
175
176
177if __name__ == "__main__":
178 main()