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