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