python-kraken-sdk

Command-line tool and SDK to access the Kraken Crypto Asset Exchange API (Spot & Futures, REST and Websocket API)

https://github.com/btschwertfeger/python-kraken-sdk

Science Score: 54.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
    Found CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
    Links to: zenodo.org
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (12.3%) to scientific vocabulary

Keywords

bitcoin command-line cryptocurrency exchange futures futures-market futures-trading kraken kraken-exchange market-data python python-trading spot-market trading trading-api trading-bot trading-client websocket

Keywords from Contributors

interactive mesh interpretability profiles sequences generic projection standardization optim embedded
Last synced: 4 months ago · JSON representation ·

Repository

Command-line tool and SDK to access the Kraken Crypto Asset Exchange API (Spot & Futures, REST and Websocket API)

Basic Info
Statistics
  • Stars: 64
  • Watchers: 4
  • Forks: 24
  • Open Issues: 3
  • Releases: 43
Topics
bitcoin command-line cryptocurrency exchange futures futures-market futures-trading kraken kraken-exchange market-data python python-trading spot-market trading trading-api trading-bot trading-client websocket
Created over 3 years ago · Last pushed 5 months ago
Metadata Files
Readme Changelog Contributing License Code of conduct Citation Codeowners Security

README.md

Futures and Spot REST and Websocket API Python SDK for the Kraken Crypto Asset Exchange

[![GitHub](https://badgen.net/badge/icon/github?icon=github&label)](https://github.com/btschwertfeger/python-kraken-sdk) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Generic badge](https://img.shields.io/badge/python-3.11+-blue.svg)](https://shields.io/) [![Downloads](https://static.pepy.tech/personalized-badge/python-kraken-sdk?period=total&units=abbreviation&left_color=grey&right_color=orange&left_text=downloads)](https://pepy.tech/project/python-kraken-sdk) [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) [![Typing](https://img.shields.io/badge/typing-mypy-informational)](https://mypy-lang.org/) [![CI/CD](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/cicd.yaml/badge.svg?branch=master)](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/cicd.yaml) [![codecov](https://codecov.io/gh/btschwertfeger/python-kraken-sdk/branch/master/badge.svg)](https://app.codecov.io/gh/btschwertfeger/python-kraken-sdk) [![OpenSSF ScoreCard](https://img.shields.io/ossf-scorecard/github.com/btschwertfeger/python-kraken-sdk?label=openssf%20scorecard&style=flat)](https://securityscorecards.dev/viewer/?uri=github.com/btschwertfeger/python-kraken-sdk) [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/8673/badge)](https://www.bestpractices.dev/projects/8673) [![release](https://shields.io/github/release-date/btschwertfeger/python-kraken-sdk)](https://github.com/btschwertfeger/python-kraken-sdk/releases) [![release](https://img.shields.io/pypi/v/python-kraken-sdk)](https://pypi.org/project/python-kraken-sdk/) [![DOI](https://zenodo.org/badge/510751854.svg)](https://zenodo.org/badge/latestdoi/510751854) [![Documentation Status Stable](https://readthedocs.org/projects/python-kraken-sdk/badge/?version=stable)](https://python-kraken-sdk.readthedocs.io/en/stable)

This is an unofficial collection of REST and websocket clients for Spot and Futures trading on the Kraken Crypto Asset 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

General:

  • Command-line interface
  • 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

Available Clients:

  • Spot REST Clients (sync and async)
  • Spot Websocket Client (using Websocket API v2)
  • Spot Orderbook Client (using Websocket API v2)
  • Futures REST Clients (sync and async)
  • Futures Websocket Client

Documentation:

Projects using this SDK:

  • https://github.com/btschwertfeger/kraken-infinity-grid
  • https://github.com/btschwertfeger/kraken-rebalance-bot
  • https://github.com/btschwertfeger/python-kraken-sdk/network/dependents

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

bash python3 -m pip install python-kraken-sdk

2. Register at Kraken and generate API keys

  • Spot Trading: https://www.kraken.com/u/security/api
  • Futures Trading: https://futures.kraken.com/trade/settings/api (see help)
  • Futures Sandbox: https://demo-futures.kraken.com/settings/api

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.

Command-line interface

The python-kraken-sdk provides a command-line interface to access the Kraken API using basic instructions while performing authentication tasks in the background. The Spot and Futures API are accessible and follow the pattern kraken {spot,futures} [OPTIONS] URL. See examples below.

```bash

get server time

kraken spot https://api.kraken.com/0/public/Time {'unixtime': 1716707589, 'rfc1123': 'Sun, 26 May 24 07:13:09 +0000'}

get user's balances

kraken spot --api-key= --secret-key= -X POST https://api.kraken.com/0/private/Balance {'ATOM': '17.28229999', 'BCH': '0.0000077100', 'ZUSD': '1000.0000'}

get user's trade balances

kraken spot --api-key= --secret-key= -X POST https://api.kraken.com/0/private/TradeBalance --data '{"asset": "DOT"}' {'eb': '2.8987347115', 'tb': '1.1694303513', 'm': '0.0000000000', 'uv': '0', 'n': '0.0000000000', 'c': '0.0000000000', 'v': '0.0000000000', 'e': '1.1694303513', 'mf': '1.1694303513'}

get 1D candles for a futures instrument

kraken futures https://futures.kraken.com/api/charts/v1/spot/PI_XBTUSD/1d {'candles': [{'time': 1625616000000, 'open': '34557.84000000000', 'high': '34803.20000000000', 'low': '33816.32000000000', 'close': '33880.22000000000', 'volume': '0' ...

get user's open futures positions

kraken futures --api-key= --secret-key= https://futures.kraken.com/derivatives/api/v3/openpositions {'result': 'success', 'openPositions': [], 'serverTime': '2024-05-26T07:15:38.91Z'} ```

... All endpoints of the Kraken Spot and Futurs API can be accessed like that.

Spot Clients

The python-kraken-sdk provides lots of functions to easily access most of the REST and websocket endpoints of the Kraken Crypto Asset Exchange API. Since these endpoints and their parameters may change, all implemented endpoints are tested on a regular basis.

The Kraken Spot API can be accessed by executing requests to the endpoints directly using the request method provided by any client. This is demonstrated below.

See https://docs.kraken.com/api/docs/guides/global-intro for information about the available endpoints and their usage.

SpotClient

The Spot client provides access to all un-and authenticated endpoints of Kraken's Spot API.

```python from kraken.spot import SpotClient

client = SpotClient(key="", secret="") print(client.request("POST", "/0/private/Balance")) ```

SpotAsyncClient

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.

```python import asyncio from kraken.spot import SpotAsyncClient

async def main(): client = SpotAsyncClient(key="", secret="") try: response = await client.request("POST", "/0/private/Balance") print(response) finally: await client.close()

if name == "main": asyncio.run(main()) ```

Using SpotAsyncClient as a context manager; This example demonstrates the use of the context manager, which ensures the client is automatically closed after the request is completed.

```python import asyncio from kraken.spot import SpotAsyncClient

async def main(): async with SpotAsyncClient(key="", secret="") as client: response = await client.request("POST", "/0/private/Balance") print(response)

if name == "main": asyncio.run(main()) ```

SpotWSClient (Websocket API)

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 the never version is supported by this SDK.

The official documentation for can be found at:

  • https://docs.kraken.com/api/docs/guides/global-intro
  • https://docs.kraken.com/websockets-v2

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

```python import asyncio from kraken.spot import SpotWSClient

class Client(SpotWSClient): """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.

async def main(): try: # Public/unauthenticated websocket client client = Client() # only use this one if you don't need private feeds await client.start() 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.activepublicsubscriptions) # to list active subscriptions await client.unsubscribe( params={"channel": "ticker", "symbol": ["BTC/USD", "DOT/USD"]} ) #

    # AS 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="api-key", secret="secret-key", no_public=True)
    await client_auth.start()
    await client_auth.subscribe(params={"channel": "balances"})

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

if name == "main": asyncio.run(main()) ```

Futures Clients

The Kraken Spot API can be accessed by executing requests to the endpoints directly using the request method provided by any client. This is demonstrated below.

See https://docs.kraken.com/api/docs/guides/global-intro for information about the available endpoints and their usage.

FuturesClient

The simple Futures client provides access to all un-and authenticated endpoints.

```python from kraken.futures import FuturesClient

client = FuturesClient(key="", secret="") print(client.request("GET", "/derivatives/api/v3/accounts")) ```

FuturesAsyncClient

The async Futures client allows for asynchronous access to Kraken's Futures endpoints. Below are two examples demonstrating its usage.

Using FuturesAsyncClient without a context manager; In this example, the client is manually closed after the request is made.

```python import asyncio from kraken.futures import FuturesAsyncClient

async def main(): client = FuturesAsyncClient(key="", secret="") try: response = await client.request("GET", "/derivatives/api/v3/accounts") print(response) finally: await client.close()

if name == "main": asyncio.run(main()) ```

Using FuturesAsyncClient as context manager; This example demonstrates the use of the context manager, which ensures the client is automatically closed after the request is completed.

```python import asyncio from kraken.futures import FuturesAsyncClient

async def main(): async with FuturesAsyncClient(key="", secret="") as client: response = await client.request("GET", "/derivatives/api/v3/accounts") print(response)

if name == "main": asyncio.run(main()) ```

FuturesWSClient (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.

  • https://docs.futures.kraken.com/#websocket-api

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

```python import asyncio from kraken.futures import FuturesWSClient

class Client(FuturesWSClient):

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

async def main(): try: # Public/unauthenticated websocket connection client = Client() await client.start()

    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-key", secret="secret-key")
    await client_auth.start()

    # 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 not client.exception_occur and not client_auth.exception_occur:
        await asyncio.sleep(6)
finally:
    await client.close()
    await client_auth.close()

if name == "main": asyncio.run(main()) ```


Contributions

are welcome - but:

  • First check if there is an existing issue or PR that addresses your problem/solution. If not - create one first - before creating a PR.
  • Typo fixes, project configuration, CI, documentation or style/formatting PRs will be rejected. Please create an issue for that.
  • PRs must provide a reasonable, easy to understand and maintain solution for an existing problem. You may want to propose a solution when creating the issue to discuss the approach before creating a PR.
  • 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.
  • Always keep an eye on https://status.kraken.com/ when encountering connectivity problems.

Notes

The versioning scheme follows the pattern v<Major>.<Minor>.<Patch>. Here's what each part signifies:

  • Major: This denotes significant changes that may introduce new features or modify existing ones. It's possible for these changes to be breaking, meaning backward compatibility is not guaranteed. To avoid unexpected behavior, it's advisable to specify at least the major version when pinning dependencies.
  • Minor: This level indicates additions of new features or extensions to existing ones. Typically, these changes do not break existing implementations.
  • Patch: Here, you'll find bug fixes, documentation updates, and changes related to continuous integration (CI). These updates are intended to enhance stability and reliability without altering existing functionality.

Coding standards are not always followed to make arguments and function names as similar as possible to those of the Kraken API documentations.

Considerations

The tool aims to be fast, easy to use and maintain. In the past, lots of clients were implemented, that provided functions for almost all available endpoints of the Kraken API. The effort to maintain this collection grew to a level where it was not possible to check various changelogs to apply new updates on a regular basis. Instead, it was decided to concentrate on the request functions of the SpotClient, SpotAsyncClient, FuturesClient and the FuturesAsyncClient (as well as their websocket client implementations). All those clients named "User", "Trade", "Market", "Funding" and so on will no longer be extended, but maintained to a certain degree.

References

  • https://python-kraken-sdk.readthedocs.io/en/stable
  • https://docs.kraken.com/api/
  • https://docs.kraken.com/api/docs/guides/global-intro
  • https://support.kraken.com/hc/en-us/sections/360012894412-Futures-API

Owner

  • Name: Benjamin T. Schwertfeger
  • Login: btschwertfeger
  • Kind: user
  • Location: Germany
  • Company: CONTACT Software GmbH

Quality Manager in Software Development

Citation (CITATION)

cff-version: 1.2.0
message: "If you use this software, please cite it as below."
authors:
- family-names: "Schwertfeger"
  given-names: "Benjamin Thomas"
  orcid: "https://orcid.org/0000-0001-7664-8434"
title: "python-kraken-sdk"
doi: 10.5281/zenodo.7653259
url: "https://github.com/btschwertfeger/python-kraken-sdk"
keywords: ["Python", "Kraken", "Crypto", "Exchange", "API", "SDK"]

GitHub Events

Total
  • Create event: 74
  • Release event: 10
  • Issues event: 41
  • Watch event: 21
  • Delete event: 68
  • Issue comment event: 43
  • Push event: 159
  • Pull request review comment event: 6
  • Pull request review event: 112
  • Pull request event: 132
  • Fork event: 7
Last Year
  • Create event: 74
  • Release event: 10
  • Issues event: 41
  • Watch event: 21
  • Delete event: 68
  • Issue comment event: 43
  • Push event: 159
  • Pull request review comment event: 6
  • Pull request review event: 112
  • Pull request event: 132
  • Fork event: 7

Committers

Last synced: 8 months ago

All Time
  • Total Commits: 308
  • Total Committers: 5
  • Avg Commits per committer: 61.6
  • Development Distribution Score (DDS): 0.269
Past Year
  • Commits: 107
  • Committers: 4
  • Avg Commits per committer: 26.75
  • Development Distribution Score (DDS): 0.374
Top Committers
Name Email Commits
Benjamin Thomas Schwertfeger d****t@b****e 225
dependabot[bot] 4****] 80
jcr-jeff 1****f 1
Graeme Holliday g****y@p****e 1
Lonzo l****p@g****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 4 months ago

All Time
  • Total issues: 118
  • Total pull requests: 293
  • Average time to close issues: 13 days
  • Average time to close pull requests: 2 days
  • Total issue authors: 13
  • Total pull request authors: 7
  • Average comments per issue: 0.74
  • Average comments per pull request: 0.32
  • Merged pull requests: 263
  • Bot issues: 0
  • Bot pull requests: 108
Past Year
  • Issues: 22
  • Pull requests: 115
  • Average time to close issues: 4 days
  • Average time to close pull requests: 2 days
  • Issue authors: 8
  • Pull request authors: 4
  • Average comments per issue: 1.73
  • Average comments per pull request: 0.23
  • Merged pull requests: 100
  • Bot issues: 0
  • Bot pull requests: 62
Top Authors
Issue Authors
  • btschwertfeger (97)
  • andyDoucette (8)
  • Trevypants (4)
  • flynn1973 (2)
  • dependabot[bot] (2)
  • Graeme22 (1)
  • HFFP (1)
  • nontro (1)
  • silverbald (1)
  • pyantoine (1)
  • emilamaj (1)
  • Skysolderone (1)
  • claudeenriquez (1)
  • OpenCoderX (1)
  • jcr-jeff (1)
Pull Request Authors
  • btschwertfeger (202)
  • dependabot[bot] (155)
  • LeonhardSchwertfeger (2)
  • HFFP (2)
  • pyantoine (2)
  • Graeme22 (1)
  • pre-commit-ci[bot] (1)
  • LeBaronDeCharlus (1)
Top Labels
Issue Labels
Spot (36) Bug (34) enhancement (24) Feature (22) Futures (18) Should (16) Breaking (13) Must (12) Could (10) Documentation (8) Wontfix (7) CI/CD (7) Technical Dept (4) dependencies (2) github_actions (2) Question (2) Duplicate (1) Idea (1) NFT (1)
Pull Request Labels
dependencies (155) github_actions (138) Spot (45) enhancement (36) Bug (24) Futures (23) Breaking (23) Documentation (17) CI/CD (16) Could (10) Technical Dept (9) Feature (9) Should (6) Project setup (5) Release (4) Must (3) NFT (3) Testing (2) Duplicate (1)

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 13,503 last-month
  • Total docker downloads: 46
  • Total dependent packages: 1
  • Total dependent repositories: 1
  • Total versions: 48
  • Total maintainers: 1
pypi.org: python-kraken-sdk

Command-line tool and collection of REST and websocket clients to interact with the Kraken Crypto Asset Exchange.

  • Versions: 48
  • Dependent Packages: 1
  • Dependent Repositories: 1
  • Downloads: 13,503 Last month
  • Docker Downloads: 46
Rankings
Docker downloads count: 3.3%
Dependent packages count: 4.8%
Downloads: 8.2%
Forks count: 9.3%
Average: 10.1%
Stargazers count: 13.4%
Dependent repos count: 21.6%
Maintainers (1)
Last synced: 4 months ago

Dependencies

.github/workflows/codeql.yml actions
  • actions/checkout v3 composite
  • github/codeql-action/analyze v2 composite
  • github/codeql-action/autobuild v2 composite
  • github/codeql-action/init v2 composite
.github/workflows/python-package.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v3 composite
requirements.txt pypi
  • asyncio >=3.4
  • requests *
  • websockets *