Skip to main content

Collection of REST and websocket clients to interact with the Kraken cryptocurrency exchange.

Project description

Futures and Spot - REST and Websocket API Python SDK for the Kraken Cryptocurrency Exchange 🐙

GitHub License Generic badge Downloads

Ruff Typing CodeQL CI/CD codecov

release release DOI Documentation Status stable

⚠️ 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.

📌 Disclaimer

There 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.


Features

Available Clients:

  • Spot REST Clients
  • Spot Websocket Clients (Websocket API v1 and v2)
  • Spot Orderbook Clients (Websocket API v1 and v2)
  • Futures REST Clients
  • Futures Websocket Client

General:

  • access both public and private, REST and websocket endpoints
  • responsive error handling and custom exceptions
  • extensive example scripts (see /examples and /tests)
  • tested using the pytest framework
  • releases are permanently archived at Zenodo
  • releases before v2.0.0 also support Python 3.7+

Documentation:


❗️ Attention

ONLY tagged 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 to pin the used version to avoid unexpected behavior on new releases.


Table of Contents


🛠 Installation and setup

1. Install the package into the desired environment

python3 -m pip install python-kraken-sdk

2. Register at Kraken and generate API keys

3. Start using the provided example scripts

4. Error handling

If any unexpected behavior occurs, please check your API permissions, rate limits, update the python-kraken-sdk, see the Troubleshooting section, and if the error persists please open an issue.


📍 Spot Clients

A template for Spot trading using both websocket and REST clients can be found in examples/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 in examples/spot_orderbook_v2.py.

Spot REST API

The 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 in examples/spot_examples.py.

from kraken.spot import User, Market, Trade, Funding, Staking

def main():
    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 V2

Kraken 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 the examples/spot_ws_examples_v1.py.

The documentation for both API versions can be found here:

Note that authenticated Spot websocket clients can also un-/subscribe from/to public feeds.

The example below can be found in an extended way in examples/spot_ws_examples_v2.py.

import asyncio
from kraken.spot import KrakenSpotWSClientV2

async def main():
    key = "spot-api-key"
    secret = "spot-secret-key"

    class Client(KrakenSpotWSClientV2):
        """Can be used to create a custom trading strategy"""

        async def on_message(self, message):
            """Receives the websocket messages"""
            if message.get("method") == "pong" \
                or message.get("channel") == "heartbeat":
                return

            print(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 client
    client = Client()  # only use this one if you don't need private feeds

    await client.subscribe(
        params={"channel": "ticker", "symbol": ["BTC/USD", "DOT/USD"]}
    )
    await client.subscribe(
        params={"channel": "book", "depth": 25, "symbol": ["BTC/USD"]}
    )
    # wait because unsubscribing is faster than unsubscribing … (just for that example)
    await asyncio.sleep(3)
    # print(client.active_public_subscriptions) # to list active subscriptions
    await client.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)
    await client_auth.subscribe(params={"channel": "executions"})

    while not client.exception_occur and not client_auth.exception_occur:
        await asyncio.sleep(6)
    return


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        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 Clients

Kraken provides a sandbox environment at https://demo-futures.kraken.com for Futures paper trading. When using these API keys you have to set the sandbox parameter to True when instantiating the respective client.

A template for Futures trading using both websocket and REST clients can be found in examples/futures_trading_bot_template.py.

The Kraken Futures API documentation can be found here:

Futures REST API

As the Spot API, Kraken also offers a REST API for Futures. Examples on how to use the python-kraken-sdk fot Futures are shown in examples/futures_examples.py and listed in a shorter ways below.

from kraken.futures import Market, User, Trade, Funding

def main():

    key = "futures-api-key"
    secret = "futures-secret-key"

    # ____USER________________________
    user = User(key=key, secret=secret) # optional: sandbox=True
    print(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 API

Not only REST, also the websocket API for Kraken Futures is available. Examples are shown below and demonstrated in examples/futures_ws_examples.py.

Note: Authenticated Futures websocket clients can also un-/subscribe from/to public feeds.

import asyncio
from kraken.futures import KrakenFuturesWSClient

async def main():

    key = "futures-api-key"
    secret = "futures-secret-key"

    class Client(KrakenFuturesWSClient):

        async def on_message(self, event):
            print(event)

    # Public/unauthenticated websocket connection
    client = Client()

    products = ["PI_XBTUSD", "PF_ETHUSD"]

    # subscribe to a public websocket feed
    await client.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 feed
    await client_auth.subscribe(feed="fills")
    await client_auth.subscribe(feed="open_positions")
    await client_auth.subscribe(feed="open_orders")
    # …

    # unsubscribe from a private/authenticated websocket feed
    await client_auth.unsubscribe(feed="fills")

    while True:
        await asyncio.sleep(6)

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        # do some exception handling …
        pass

🆕 Contributions

… are welcome! - Please have a look at CONTRIBUTION.md.


🚨 Troubleshooting

  • Check if you downloaded and installed the latest version of the python-kraken-sdk.
  • Check the permissions of your API keys and the required permissions on the respective endpoints.
  • If you get some Cloudflare or rate 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.

📝 Notes

  • The version scheme is <Major>.<Minor>.<Service Level> where:

    • Major will affect everything and there will be breaking changes in any case. This could be for example a change to Python 3.11+ only.
    • Minor introduces 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 Level includes 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.

🔭 References


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python-kraken-sdk-2.0.0.tar.gz (434.2 kB view details)

Uploaded Source

Built Distribution

python_kraken_sdk-2.0.0-py3-none-any.whl (93.1 kB view details)

Uploaded Python 3

File details

Details for the file python-kraken-sdk-2.0.0.tar.gz.

File metadata

  • Download URL: python-kraken-sdk-2.0.0.tar.gz
  • Upload date:
  • Size: 434.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.6

File hashes

Hashes for python-kraken-sdk-2.0.0.tar.gz
Algorithm Hash digest
SHA256 072daa79f9c087ec1f2e11ef6dd0f8ed0db3426dc8c62a71796410ad994aaee7
MD5 cecd2497e7d1f9a913fe7aca05ef8970
BLAKE2b-256 7479b5f480037d92d4cf816d12bac99edfe5d9927ff2c2d8b65f4c31eceb0432

See more details on using hashes here.

Provenance

File details

Details for the file python_kraken_sdk-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for python_kraken_sdk-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 43f67053f59647a64795d693d6c9f4790f4721443cbd3f41ceb2ca09e1dbe60a
MD5 26735fc2f1edb2922bfe4ce92b2964b8
BLAKE2b-256 c63fb8eaf129b0661c4d699f79aea4ec23f606bd3e63ac2277263dfa4e3c1fca

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page