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# -*- mode: python; coding: utf-8 -*-
  2# !/usr/bin/env python3
  3#
  4# Copyright (C) 2023 Benjamin Thomas Schwertfeger
  5# All rights reserved.
  6# https://github.com/btschwertfeger
  7#
  8
  9"""
 10Module that implements some example usage for the Kraken Futures REST clients.
 11
 12This module may not be maintained on a regular basis, so please refer to the
 13unit tests of this package as they provide a much deeper dive into the usage.
 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 market client usage"""
 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(market.get_ohlc(tick_type='trade', symbol='PI_XBTUSD', resolution='5m', from_='1668989233'))
 42    # print(market.get_fee_schedules())
 43    # # print(market.get_orderbook(symbol='fi_xbtusd_180615')) # this endpoint is broken
 44    # print(market.get_tickers())
 45    # print(market.get_instruments())
 46    # print(market.get_instruments_status())
 47    # print(market.get_instruments_status(instrument='PI_XBTUSD'))
 48    # print(market.get_trade_history(symbol='PI_XBTUSD'))
 49    # print(market.get_historical_funding_rates(symbol='PI_XBTUSD'))
 50    # time.sleep(2)
 51
 52    priv_market = Market(key=key, secret=secret, sandbox=True)
 53    # print(priv_market.get_fee_schedules_vol())
 54    print(priv_market.get_leverage_preference())
 55    # print(priv_market.set_leverage_preference(symbol='PF_XBTUSD', maxLeverage=2)) # set max leverage
 56    # print(priv_market.set_leverage_preference(symbol='PF_XBTUSD')) # reset max leverage
 57    # print(priv_market.set_pnl_preference(symbol='PF_XBTUSD', pnlPreference='BTC'))
 58
 59    # time.sleep(2)
 60    # print(priv_market.get_execution_events())
 61    # print(market.get_public_execution_events(tradeable='PI_XBTUSD'))
 62    # print(market.get_public_order_events(tradeable='PI_XBTUSD'))
 63    # print(market.get_public_mark_price_events(tradeable='PI_XBTUSD'))
 64    # print(priv_market.get_order_events())
 65    # print(priv_market.get_trigger_events())
 66
 67
 68def user_examples() -> None:
 69    """Example User client usage"""
 70    user = User(key=key, secret=secret, sandbox=True)
 71    print(user.get_wallets())
 72
 73    print(user.get_subaccounts())
 74    print(user.get_unwind_queue())
 75    print(user.get_notifications())
 76
 77    print(user.get_open_positions())
 78    print(user.get_open_orders())
 79
 80    print(user.get_account_log(before="1604937694000"))
 81    print(user.get_account_log(info="futures liquidation"))
 82    time.sleep(2)
 83    response = user.get_account_log_csv()
 84    assert response.status_code in {200, "200"}
 85    with Path("account_log.csv").open("wb") as file:
 86        for chunk in response.iter_content(chunk_size=512):
 87            if chunk:
 88                file.write(chunk)
 89
 90
 91def trade_examples() -> None:
 92    """Example Trade client usage"""
 93    raise ValueError(
 94        "Attention: Please check if you really want to execute the trade endpoints!",
 95    )
 96    trade = Trade(key=key, secret=secret, sandbox=True)
 97    print(trade.get_fills())
 98    print(trade.get_fills(lastFillTime="2020-07-21T12:41:52.790Z"))
 99    print(
100        trade.create_batch_order(
101            batchorder_list=[
102                {
103                    "order": "send",
104                    "order_tag": "1",
105                    "orderType": "lmt",
106                    "symbol": "PI_XBTUSD",
107                    "side": "buy",
108                    "size": 1,
109                    "limitPrice": 1.00,
110                },
111                {
112                    "order": "send",
113                    "order_tag": "2",
114                    "orderType": "stp",
115                    "symbol": "PI_XBTUSD",
116                    "side": "buy",
117                    "size": 1,
118                    "limitPrice": 2.00,
119                    "stopPrice": 3.00,
120                },
121                {
122                    "order": "cancel",
123                    "order_id": "e35d61dd-8a30-4d5f-a574-b5593ef0c050",
124                },
125                {
126                    "order": "cancel",
127                    "cliOrdId": 123456789,
128                },
129            ],
130        ),
131    )
132    print(trade.cancel_all_orders())
133    print(trade.cancel_all_orders(symbol="pi_xbtusd"))
134    print(trade.dead_mans_switch(timeout=60))
135    print(trade.dead_mans_switch(timeout=0))  # to deactivate
136    print(trade.cancel_order(order_id="some order id"))
137    print(
138        trade.edit_order(
139            orderId="some order id",
140            size=300,
141            limitPrice=401,
142            stopPrice=350,
143        ),
144    )
145    print(trade.get_orders_status(orderIds=["orderid1", "orderid2"]))
146    print(
147        trade.create_order(
148            orderType="lmt",
149            side="buy",
150            size=1,
151            limitPrice=4,
152            symbol="pf_bchusd",
153        ),
154    )
155    print(
156        trade.create_order(
157            orderType="take_profit",
158            side="buy",
159            size=1,
160            symbol="pf_bchusd",
161            stopPrice=100,
162            triggerSignal="mark",
163        ),
164    )
165
166
167def funding_examples() -> None:
168    """Example Funding client usage"""
169    funding = Funding(key=key, secret=secret, sandbox=True)
170    print(funding.get_historical_funding_rates(symbol="PF_SOLUSD"))
171
172
173def main() -> None:
174    user_examples()
175    market_examples()
176    trade_examples()
177    funding_examples()
178
179
180if __name__ == "__main__":
181    main()