Package: python-kraken-sdk
Futures and Spot - REST and Websocket API Python SDK for the Kraken Cryptocurrency Exchange 🐙⚠️ This is an unofficial collection of REST and websocket clients for Spot and
Futures trading on the Kraken cryptocurrency exchange using Python. Payward
Ltd. and Kraken are in no way associated with the authors of this package and
documentation.Please note that this project is independent and not endorsed by Kraken or
Payward Ltd. Users should be aware that they are using third-party software,
and the authors of this project are not responsible for any issues, losses, or
risks associated with its usage.📌 DisclaimerThere is no guarantee that this software will work flawlessly at this or later
times. Of course, no responsibility is taken for possible profits or losses.
This software probably has some errors in it, so use it at your own risk. Also
no one should be motivated or tempted to invest assets in speculative forms of
investment. By using this software you release the author(s) from any liability
regarding the use of this software.FeaturesAvailable Clients:Spot REST ClientsSpot Websocket Clients (Websocket API v1 and v2)Spot Orderbook Clients (Websocket API v1 and v2)Futures REST ClientsFutures Websocket ClientGeneral:access both public and private, REST and websocket endpointsresponsive error handling and custom exceptionsextensive example scripts (see/examplesand/tests)tested using thepytestframeworkreleases are permanently archived atZenodoreleases before v2.0.0 also support Python 3.7+Documentation:https://python-kraken-sdk.readthedocs.io/en/stablehttps://python-kraken-sdk.readthedocs.io/en/latest❗️ AttentionONLYtagged releases are available at PyPI. So the content of the master may
not match with the content of the latest release. - Please have a look at the
release specific READMEs and changelogs.It is also recommended topin the used versionto avoid unexpected behavior on
new releases.Table of ContentsInstallation and setupSpot ClientsREST APIWebsocket API V2Futures ClientsREST APIWebsocket APITroubleshootingContributionsNotesReferences🛠 Installation and setup1. Install the package into the desired environmentpython3-mpipinstallpython-kraken-sdk2. Register atKrakenand generate API keysSpot Trading:https://www.kraken.com/u/security/apiFutures Trading:https://futures.kraken.com/trade/settings/api(seehelp)Futures Sandbox:https://demo-futures.kraken.com/settings/api3. Start using the provided example scripts4. Error handlingIf any unexpected behavior occurs, please checkyour
API permissions,rate limits, update the
python-kraken-sdk, see theTroubleshootingsection, and if the error
persists please open an issue.📍 Spot ClientsA template for Spot trading using both websocket and REST clients can be found
inexamples/spot_trading_bot_template_v2.py.For those who need a realtime order book - a script that demonstrates how to
maintain a valid order book using the Orderbook client can be found inexamples/spot_orderbook_v2.py.Spot REST APIThe Kraken Spot REST API offers many endpoints for almost every use-case. The
python-kraken-sdk aims to provide all of them - split in User, Market, Trade,
Funding and Staking related clients.The following code block demonstrates how to use some of them. More examples
can be found inexamples/spot_examples.py.fromkraken.spotimportUser,Market,Trade,Funding,Stakingdefmain():key="kraken-public-key"secret="kraken-secret-key"# ____USER________________________user=User(key=key,secret=secret)print(user.get_account_balance())print(user.get_open_orders())# …# ____MARKET____market=Market()print(market.get_ticker(pair="BTCUSD"))# …# ____TRADE_________________________trade=Trade(key=key,secret=secret)print(trade.create_order(ordertype="limit",side="buy",volume=1,pair="BTC/EUR",price=20000))# …# ____FUNDING___________________________funding=Funding(key=key,secret=secret)print(funding.withdraw_funds(asset="DOT",key="MyPolkadotWallet",amount=200))print(funding.cancel_withdraw(asset="DOT",refid="<some id>"))# …# ____STAKING___________________________staking=Staking(key=key,secret=secret)print(staking.list_stakeable_assets())print(staking.stake_asset(asset="DOT",amount=20,method="polkadot-staked"))# …if__name__=="__main__":main()Spot Websocket API V2Kraken offers two versions of their websocket API (V1 and V2). Since V2 is
offers more possibilities, is way faster and easier to use, only those examples
are shown below. For using the websocket API V1 please have a look into theexamples/spot_ws_examples_v1.py.The documentation for both API versions can be found here:https://docs.kraken.com/websocketshttps://docs.kraken.com/websockets-v2Note that authenticated Spot websocket clients can also un-/subscribe from/to
public feeds.The example below can be found in an extended way inexamples/spot_ws_examples_v2.py.importasynciofromkraken.spotimportKrakenSpotWSClientV2asyncdefmain():key="spot-api-key"secret="spot-secret-key"classClient(KrakenSpotWSClientV2):"""Can be used to create a custom trading strategy"""asyncdefon_message(self,message):"""Receives the websocket messages"""ifmessage.get("method")=="pong"\ormessage.get("channel")=="heartbeat":returnprint(message)# here we can access lots of methods, for example to create an order:# if self.is_auth:  # only if the client is authenticated …#     await self.send_message(#         message={#             "method": "add_order",#             "params": {#                 "limit_price": 1234.56,#                 "order_type": "limit",#                 "order_userref": 123456789,#                 "order_qty": 1.0,#                 "side": "buy",#                 "symbol": "BTC/USD",#                 "validate": True,#             },#         }#     )# … it is also possible to call regular REST endpoints# but using the websocket messages is more efficient.# You can also un-/subscribe here using self.subscribe/self.unsubscribe.# Public/unauthenticated websocket clientclient=Client()# only use this one if you don't need private feedsawaitclient.subscribe(params={"channel":"ticker","symbol":["BTC/USD","DOT/USD"]})awaitclient.subscribe(params={"channel":"book","depth":25,"symbol":["BTC/USD"]})# wait because unsubscribing is faster than unsubscribing … (just for that example)awaitasyncio.sleep(3)# print(client.active_public_subscriptions) # to list active subscriptionsawaitclient.unsubscribe(params={"channel":"ticker","symbol":["BTC/USD","DOT/USD"]})# …# Per default, the authenticated client starts two websocket connections,# one for authenticated and one for public messages. If there is no need# for a public connection, it can be disabled using the ``no_public``# parameter.client_auth=Client(key=key,secret=secret,no_public=True)awaitclient_auth.subscribe(params={"channel":"executions"})whilenotclient.exception_occurandnotclient_auth.exception_occur:awaitasyncio.sleep(6)returnif__name__=="__main__":try:asyncio.run(main())exceptKeyboardInterrupt:pass# The websocket client will send {'event': 'asyncio.CancelledError'}# via on_message so you can handle the behavior/next actions# individually within your strategy.📍 Futures ClientsKraken provides a sandbox environment athttps://demo-futures.kraken.comfor
Futures paper trading. When using these API keys you have to set thesandboxparameter toTruewhen instantiating the respective client.A template for Futures trading using both websocket and REST clients can be
found inexamples/futures_trading_bot_template.py.The Kraken Futures API documentation can be found here:https://docs.futures.kraken.comhttps://support.kraken.com/hc/en-us/sections/360012894412-Futures-APIFutures REST APIAs the Spot API, Kraken also offers a REST API for Futures. Examples on how to
use the python-kraken-sdk fot Futures are shown inexamples/futures_examples.pyand listed in a shorter ways below.fromkraken.futuresimportMarket,User,Trade,Fundingdefmain():key="futures-api-key"secret="futures-secret-key"# ____USER________________________user=User(key=key,secret=secret)# optional: sandbox=Trueprint(user.get_wallets())print(user.get_open_orders())print(user.get_open_positions())print(user.get_subaccounts())# …# ____MARKET____market=Market()print(market.get_ohlc(tick_type="trade",symbol="PI_XBTUSD",resolution="5m"))priv_market=Market(key=key,secret=secret)print(priv_market.get_fee_schedules_vol())print(priv_market.get_execution_events())# …# ____TRADE_________________________trade=Trade(key=key,secret=secret)print(trade.get_fills())print(trade.create_batch_order(batchorder_list=[{"order":"send","order_tag":"1","orderType":"lmt","symbol":"PI_XBTUSD","side":"buy","size":1,"limitPrice":12000,"cliOrdId":"some-client-id"},{"order":"send","order_tag":"2","orderType":"stp","symbol":"PI_XBTUSD","side":"buy","size":1,"limitPrice":10000,"stopPrice":11000,},{"order":"cancel","order_id":"e35dsdfsdfsddd-8a30-4d5f-a574-b5593esdf0",},{"order":"cancel","cliOrdId":"another-client-id",}],))print(trade.cancel_all_orders())print(trade.create_order(orderType="lmt",side="buy",size=1,limitPrice=4,symbol="pf_bchusd"))# …# ____FUNDING___________________________funding=Funding(key=key,secret=secret)# …if__name__=="__main__":main()Futures Websocket APINot only REST, also the websocket API for Kraken Futures is available. Examples
are shown below and demonstrated inexamples/futures_ws_examples.py.https://docs.futures.kraken.com/#websocket-apiNote: Authenticated Futures websocket clients can also un-/subscribe from/to
public feeds.importasynciofromkraken.futuresimportKrakenFuturesWSClientasyncdefmain():key="futures-api-key"secret="futures-secret-key"classClient(KrakenFuturesWSClient):asyncdefon_message(self,event):print(event)# Public/unauthenticated websocket connectionclient=Client()products=["PI_XBTUSD","PF_ETHUSD"]# subscribe to a public websocket feedawaitclient.subscribe(feed="ticker",products=products)# await client.subscribe(feed="book", products=products)# …# unsubscribe from a public websocket feed# await client.unsubscribe(feed="ticker", products=products)# Private/authenticated websocket connection (+public)client_auth=Client(key=key,secret=secret)# print(client_auth.get_available_private_subscription_feeds())# subscribe to a private/authenticated websocket feedawaitclient_auth.subscribe(feed="fills")awaitclient_auth.subscribe(feed="open_positions")awaitclient_auth.subscribe(feed="open_orders")# …# unsubscribe from a private/authenticated websocket feedawaitclient_auth.unsubscribe(feed="fills")whileTrue:awaitasyncio.sleep(6)if__name__=="__main__":try:asyncio.run(main())exceptKeyboardInterrupt:# do some exception handling …pass🆕 Contributions… are welcome! - Please have a look atCONTRIBUTION.md.🚨 TroubleshootingCheck if you downloaded and installed thelatest versionof the
python-kraken-sdk.Check thepermissions of your API keysand the required permissions on the
respective endpoints.If you get some Cloudflare orrate limit errors, please check your Kraken
Tier level and maybe apply for a higher rank if required.Use different API keys for different algorithms, because the nonce
calculation is based on timestamps and a sent nonce must always be the highest
nonce ever sent of that API key. Having multiple algorithms using the same
keys will result in invalid nonce errors.📝 NotesThe version scheme is<Major>.<Minor>.<Service Level>where:Majorwill affect everything and there will be breaking changes in any
case. This could be for example a change to Python 3.11+ only.Minorintroduces features and enhancements which may bring breaking
changes in some cases. These breaking changes could be renaming or addition
of parameters, change in order of parameters or even renaming a function.Service Levelincludes bug fixes, documentation or CI related changes.Coding standards are not always followed to make arguments and function names
as similar as possible to those of the Kraken API documentations.🔭 Referenceshttps://python-kraken-sdk.readthedocs.io/en/stablehttps://docs.kraken.com/resthttps://docs.kraken.com/websocketshttps://docs.kraken.com/websockets-v2https://docs.futures.kraken.comhttps://support.kraken.com/hc/en-us/sections/360012894412-Futures-API