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.

Example: Spot Client Usage (1)
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.

Example: Spot Client Usage (2)
 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.

Example: Spot Client Usage (3)
 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.

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