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