Spot REST

The examples presented below serve to demonstrate the usage of the Spot 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 Spot client provides access to all un-and authenticated endpoints of Kraken’s Spot and NFT API.

Example: Spot Client Usage (1)
1from kraken.spot import SpotClient
2
3client = SpotClient(key="<your-api-key>", secret="<your-secret-key>")
4print(client.request("POST", "/0/private/Balance"))

The async Spot client allows for asynchronous access to Kraken’s Spot and NFT API endpoints. Below are two examples demonstrating its usage.

Using SpotAsyncClient 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.spot import SpotAsyncClient
 3
 4async def main():
 5   client = SpotAsyncClient(key="<your-api-key>", secret="<your-secret-key>")
 6   try:
 7      response = await client.request("POST", "/0/private/Balance")
 8      print(response)
 9   finally:
10      await client.async_close()
11
12asyncio.run(main())

Using SpotAsyncClient 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.spot import SpotAsyncClient
 3
 4async def main():
 5   async with SpotAsyncClient(
 6      key="<your-api-key>", secret="<your-secret-key>"
 7   ) as client:
 8      response = await client.request("POST", "/0/private/Balance")
 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 Spot REST clients
  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 samples for the Kraken Spot 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 logging.config
 15import os
 16import time
 17from pathlib import Path
 18
 19from kraken.spot import Earn, 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
 29
 30key = os.getenv("API_KEY")
 31secret = os.getenv("SECRET_KEY")
 32
 33
 34def user_examples() -> None:
 35    """Example usage of the User client"""
 36    user = User(key=key, secret=secret)
 37
 38    print(user.get_account_balance())
 39    print(user.get_trade_balance())  # asset='BTC'
 40    print(user.get_open_orders())
 41    print(user.get_closed_orders())
 42    print(
 43        user.get_orders_info(txid="OBQFM7-JNVKS-H3ULEH"),
 44    )  # or txid='id1,id2,id3' or txid=['id1','id2']
 45    print(user.get_trades_history())
 46    time.sleep(3)
 47    print(user.get_trades_info(txid="TCNTTR-QBEVO-E5H5UK"))
 48    print(user.get_open_positions())  # txid='someid'
 49    print(
 50        user.get_ledgers_info(),
 51    )  # asset='BTC' or asset='BTC,EUR' or asset=['BTC','EUR']
 52    print(user.get_ledgers(id_="LIORGR-33NXH-LBUS5Z"))
 53    print(user.get_trade_volume())  # pair='BTC/EUR'
 54
 55    # ____export_report____
 56    response = user.request_export_report(
 57        report="ledgers",
 58        description="myLedgers1",
 59        format="CSV",
 60    )  # report='trades'
 61    print(user.get_export_report_status(report="ledgers"))
 62
 63    # save report to file
 64    response_data = user.retrieve_export(id_=response["id"])
 65    with Path("myExport.zip").open("wb") as file:
 66        for chunk in response_data.iter_content(chunk_size=512):
 67            if chunk:
 68                file.write(chunk)
 69
 70    print(
 71        user.delete_export_report(id_=response["id"], type_="delete"),
 72    )  # alternative: type_=cancel
 73
 74
 75def market_examples() -> None:
 76    """Example usage of the Market client"""
 77    market = Market()
 78
 79    print(market.get_assets(assets=["XBT"]))
 80    print(market.get_asset_pairs(pair=["DOTEUR"]))
 81    print(market.get_ticker(pair="XBTUSD"))
 82    print(market.get_ohlc(pair="XBTUSD", interval=5))
 83    print(market.get_order_book(pair="XBTUSD", count=10))
 84    print(market.get_recent_trades(pair="XBTUSD"))
 85    print(market.get_recent_spreads(pair="XBTUSD"))
 86    print(market.get_system_status())
 87    time.sleep(2)
 88
 89
 90def trade_examples() -> None:
 91    """Example usage of the Trade client"""
 92    raise ValueError(
 93        "Attention: Please check if you really want to execute trade functions.",
 94    )
 95    trade = Trade(key=key, secret=secret)
 96
 97    if False:
 98        print(
 99            trade.create_order(
100                ordertype="limit",
101                side="buy",
102                volume=1,
103                pair="BTC/EUR",
104                price=0.01,
105            ),
106        )
107        print(
108            trade.create_order_batch(
109                orders=[
110                    {
111                        "close": {
112                            "ordertype": "stop-loss-limit",
113                            "price": 120,
114                            "price2": 110,
115                        },
116                        "ordertype": "limit",
117                        "price": 140,
118                        "price2": 130,
119                        "timeinforce": "GTC",
120                        "type": "buy",
121                        "userref": "345dsdfddfgdsgdfgsfdsfsdf",
122                        "volume": 1000,
123                    },
124                    {
125                        "ordertype": "limit",
126                        "price": 150,
127                        "timeinforce": "GTC",
128                        "type": "sell",
129                        "userref": "1dfgesggwe5t3",
130                        "volume": 123,
131                    },
132                ],
133                pair="BTC/USD",
134                validate=True,
135            ),
136        )
137
138        print(
139            trade.edit_order(txid="sometxid", pair="BTC/EUR", volume=4.2, price=17000),
140        )
141        time.sleep(2)
142
143        print(trade.cancel_order(txid="O2JLFP-VYFIW-35ZAAE"))
144        print(trade.cancel_all_orders())
145        print(trade.cancel_all_orders_after_x(timeout=6))
146
147    print(
148        trade.cancel_order_batch(
149            orders=[
150                "O2JLFP-VYFIW-35ZAAE",
151                "O523KJ-DO4M2-KAT243",
152                "OCDIAL-YC66C-DOF7HS",
153                "OVFPZ2-DA2GV-VBFVVI",
154            ],
155        ),
156    )
157
158
159def funding_examples() -> None:
160    """Example usage of the Funding client"""
161    funding = Funding(key=key, secret=secret)
162    print(funding.get_deposit_methods(asset="DOT"))
163    # print(funding.get_deposit_address(asset='DOT', method='Polkadot'))
164    # print(funding.get_recent_deposits_status(asset='DOT'))
165    print(
166        funding.get_withdrawal_info(asset="DOT", key="MyPolkadotWallet", amount="200"),
167    )
168
169    raise ValueError(
170        "Attention: Please check if you really want to execute funding functions.",
171    )
172    if False:
173        time.sleep(2)
174        print(funding.withdraw_funds(asset="DOT", key="MyPolkadotWallet", amount=200))
175        print(funding.get_recent_withdraw_status(asset="DOT"))
176        print(funding.cancel_widthdraw(asset="DOT", refid="12345"))
177        print(
178            funding.wallet_transfer(
179                asset="ETH",
180                amount=0.100,
181                from_="Spot Wallet",
182                to_="Futures Wallet",
183            ),
184        )
185
186
187def earn_examples() -> None:
188    """
189    Example usage of the Funding client; not shown, since special API key
190    permissions must be set.
191    """
192    earn = Earn(key=key, secret=secret)  # noqa: F841
193    # ...
194    # see tests/spot/test_spot_earn.py for examples.
195
196
197def main() -> None:
198    user_examples()
199    market_examples()
200    trade_examples()
201    funding_examples()
202    earn_examples()
203
204
205if __name__ == "__main__":
206    main()