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 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 implements *some* examples for the Kraken Futures REST clients
13usage.
14"""
15
16import logging
17import os
18import time
19from pathlib import Path
20
21from kraken.futures import Funding, Market, Trade, User
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
31key = os.getenv("FUTURES_SANDBOX_KEY")
32secret = os.getenv("FUTURES_SANDBOX_SECRET")
33
34
35def market_examples() -> None:
36 """Example Futures Market client usage"""
37
38 # Usage of the Market client to access public endpoints:
39 market = Market()
40 print(market.get_tick_types())
41 print(market.get_tradeable_products(tick_type="trade"))
42 print(market.get_resolutions(tick_type="trade", tradeable="PI_XBTUSD"))
43 print(
44 market.get_ohlc(
45 tick_type="trade",
46 symbol="PI_XBTUSD",
47 resolution="5m",
48 from_="1668989233",
49 ),
50 )
51 print(market.get_fee_schedules())
52 print(
53 market.get_orderbook(symbol="fi_xbtusd_180615"),
54 ) # might need adjustment of the symbol
55 print(market.get_tickers())
56 print(market.get_instruments())
57 print(market.get_instruments_status())
58 print(market.get_instruments_status(instrument="PI_XBTUSD"))
59 print(market.get_trade_history(symbol="PI_XBTUSD"))
60 print(market.get_historical_funding_rates(symbol="PI_XBTUSD"))
61 time.sleep(2) # Just to avoid rate limits
62
63 # Usage of the Market client to access private endpoints:
64 # (commented out to avoid accidental usage)
65 priv_market = Market(key=key, secret=secret, sandbox=True)
66 # print(priv_market.get_fee_schedules_vol())
67 print(priv_market.get_leverage_preference())
68 # print(priv_market.set_leverage_preference(symbol='PF_XBTUSD', maxLeverage=2)) # set max leverage
69 # print(priv_market.set_leverage_preference(symbol='PF_XBTUSD')) # reset max leverage
70 # print(priv_market.set_pnl_preference(symbol='PF_XBTUSD', pnlPreference='BTC'))
71
72 # time.sleep(2)
73 # print(priv_market.get_execution_events())
74 # print(market.get_public_execution_events(tradeable='PI_XBTUSD'))
75 # print(market.get_public_order_events(tradeable='PI_XBTUSD'))
76 # print(market.get_public_mark_price_events(tradeable='PI_XBTUSD'))
77 # print(priv_market.get_order_events())
78 # print(priv_market.get_trigger_events())
79
80
81def user_examples() -> None:
82 """Example Futures User client usage"""
83 # NOTE: This only works if you have set valid credentials for the the
84 # Futures demo environment. Remove the `sandbox=True` argument to use
85 # the production environment.
86 #
87 # Usage of the User client to access private endpoints:
88 user = User(key=key, secret=secret, sandbox=True)
89 print(user.get_wallets())
90 print(user.get_subaccounts())
91 print(user.get_unwind_queue())
92 print(user.get_notifications())
93 print(user.get_open_positions())
94 print(user.get_open_orders())
95
96 # You can retrieve the account log like so:
97 print(user.get_account_log(before="1604937694000"))
98 print(user.get_account_log(info="futures liquidation"))
99 time.sleep(2) # Just to avoid rate limits
100
101 response = user.get_account_log_csv()
102 assert response.status_code in {200, "200"}
103 with Path("account_log.csv").open("wb") as file:
104 for chunk in response.iter_content(chunk_size=512):
105 if chunk:
106 file.write(chunk)
107
108
109def trade_examples() -> None:
110 """Example Futures Trade client usage"""
111 print(
112 "Attention: Please check if you want to execute the trade endpoints!"
113 " Check the script manually before running this example.",
114 )
115 return
116 # return
117 # NOTE: This only works if you have set valid credentials for the the
118 # Futures demo environment. Remove the `sandbox=True` argument to use
119 # the production environment.
120 trade = Trade(key=key, secret=secret, sandbox=True)
121 print(trade.get_fills())
122 print(trade.get_fills(lastFillTime="2020-07-21T12:41:52.790Z"))
123 print(
124 trade.create_batch_order(
125 batchorder_list=[
126 {
127 "order": "send",
128 "order_tag": "1",
129 "orderType": "lmt",
130 "symbol": "PI_XBTUSD",
131 "side": "buy",
132 "size": 1,
133 "limitPrice": 1.00,
134 },
135 {
136 "order": "send",
137 "order_tag": "2",
138 "orderType": "stp",
139 "symbol": "PI_XBTUSD",
140 "side": "buy",
141 "size": 1,
142 "limitPrice": 2.00,
143 "stopPrice": 3.00,
144 },
145 {
146 "order": "cancel",
147 "order_id": "e35d61dd-8a30-4d5f-a574-b5593ef0c050",
148 },
149 {
150 "order": "cancel",
151 "cliOrdId": 123456789,
152 },
153 ],
154 ),
155 )
156 print(trade.cancel_all_orders())
157 print(trade.cancel_all_orders(symbol="pi_xbtusd"))
158 print(trade.dead_mans_switch(timeout=60))
159 print(trade.dead_mans_switch(timeout=0)) # to deactivate
160 print(trade.cancel_order(order_id="some order id"))
161 print(
162 trade.edit_order(
163 orderId="some order id",
164 size=300,
165 limitPrice=401,
166 stopPrice=350,
167 ),
168 )
169 print(trade.get_orders_status(orderIds=["orderid1", "orderid2"]))
170 print(
171 trade.create_order(
172 orderType="lmt",
173 side="buy",
174 size=1,
175 limitPrice=4,
176 symbol="pf_bchusd",
177 ),
178 )
179 print(
180 trade.create_order(
181 orderType="take_profit",
182 side="buy",
183 size=1,
184 symbol="pf_bchusd",
185 stopPrice=100,
186 triggerSignal="mark",
187 ),
188 )
189
190
191def funding_examples() -> None:
192 """Example Funding client usage"""
193 funding = Funding(key=key, secret=secret, sandbox=True)
194 print(funding.get_historical_funding_rates(symbol="PF_SOLUSD"))
195
196
197def main() -> None:
198 """Uncomment the examples you want to run:"""
199 # user_examples()
200 # market_examples()
201 # trade_examples()
202 # funding_examples()
203
204
205if __name__ == "__main__":
206 main()