Логотип Spot, xStocks, and Futures REST and Websocket API Python SD…

Spot, xStocks, and Futures REST and Websocket API Python SD…

Сообщество
btschwertfeger

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

Издательbtschwertfeger
Репозиторийpython-kraken-sdk
ЯзыкPython
Форки
32
Звёзды
83
Доступные инструменты
0
Тип транспортаstdio
Категории
ЛицензияApache-2.0
Ссылки
  • Подключайте инструменты к рабочим процессам с ИИ

    Spot, xStocks, and Futures REST and Websocket API Python SD… предоставляет возможности MCP, доступные совместимым ИИ-клиентам и агентам.

  • Доступные инструменты: 0

    Ниже представлены доступные для вызова действия с названиями и описаниями, если сервер их предоставляет.

  • Готовая конфигурация для копирования

    Используйте примеры конфигурации, чтобы настроить этот сервер в предпочитаемом MCP-клиенте.

  • Показатели интереса к открытому проекту

    Звёзды: 83, форки: 32 — в связанном репозитории.

GitHub License Generic badge Downloads

Ruff Typing CI/CD codecov

OpenSSF ScoreCard OpenSSF Best Practices

release release DOI Documentation Status 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 - including xStocks capability
  • Spot Websocket Client (Websocket API v2)
  • Spot Orderbook Client (Websocket API v2)
  • Futures REST Clients
  • Futures Websocket Client

Documentation:

Projects using this SDK:


❗️ 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

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=<api-key> --secret-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=<api-key> --secret-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=<api-key> --secret-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.

📍 MCP Server

The python-kraken-sdk also ships an MCP server exposing the Spot (incl. xStocks — pass "asset_class": "tokenized_asset" inside params where the Kraken API docs require it) and Futures request methods as two tools, spot_request and futures_request.

bash
uv tool install "python-kraken-sdk[mcp]"

# e.g. Claude setup:
claude mcp add kraken --scope user -- kraken-mcp

Credentials are never tool arguments. Configure them as environment variables instead: KRAKEN_SPOT_API_KEY / KRAKEN_SPOT_SECRET_KEY, KRAKEN_FUTURES_API_KEY / KRAKEN_FUTURES_SECRET_KEY, and optionally KRAKEN_FUTURES_SANDBOX=1 to target the Futures demo environment. Example client for Claude Code configuration:

json
// ~/.claude.json
{
  "mcpServers": {
    "kraken": {
      "command": "kraken-mcp",
      "env": {
        // Only public endpoints are available without credentials
        "KRAKEN_SPOT_API_KEY": "<your-api-key>",
        "KRAKEN_SPOT_SECRET_KEY": "<your-secret-key>"
      }
    }
  }
}

📍 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="<your-api-key>", secret="<your-secret-key>")
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="<your-api-key>", secret="<your-secret-key>")
    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="<your-api-key>", secret="<your-secret-key>") 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:

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.active_public_subscriptions) # 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())

📍 xStocks

Kraken recently added support for trading of tokenized stocks (xStocks) on their platform. The python-kraken-sdk fully supports this new feature, allowing users to trade xStocks seamlessly alongside other crypto assets.

For accessing xStocks, you can use the same SpotClient and SpotAsyncClient classes that are used for regular spot trading. The endpoints and methods for xStocks are integrated into these clients, making it easy to manage your xStock trades.

It is important to note that the xStocks feature is not available globally. Please check Kraken's documentation to understand the availability zones and ensure that you can trade xStocks from your location.

For trading or filtering for xStocks assets, the new asset class tokenized_asset must be used, e.g. when creating an order:

python
   from kraken.spot import SpotClient, Trade

   # Option 1: Create an order using the SpotClient directly:
   client = SpotClient(key="api-public-key", secret="api-secret-key")
   client.request(
       method="POST",
       uri="/0/private/AddOrder",
       params={
           "type": "buy",
           "volume": "1",
           "ordertype": "limit",
           "pair": "AAPLxUSD",
           "price": "100.0",
           "validate": True,
           "asset_class": "tokenized_asset", # <- important!
       },
   )
   # Option 2: Create an order using the Trade client:
   trade = Trade(key="api-public-key", secret="api-secret-key")
   trade.create_order(
       pair="AAPLxUSD",
       side="buy",
       ordertype="limit",
       volume="1",
       price="100.0",
       validate=True,
       extra_params={"asset_class": "tokenized_asset"}, # <- important!
   )

📍 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="<your-api-key>", secret="<your-secret-key>")
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="<your-api-key>", secret="<your-secret-key>")
    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="<your-api-key>", secret="<your-secret-key>") 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.

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.
  • The xStocks feature is not available globally. Please checkout Kraken's documentation to get to know the availability zones.

📝 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


Установка

TypingMind
{
  "mcpServers": {
    "python-kraken-sdk": {
      "command": "kraken-mcp",
      "args": []
    }
  }
}

Используйте MCP Spot, xStocks, and Futures REST and Websocket API Python SD… с разными ИИ-моделями

TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому после подключения Spot, xStocks, and Futures REST and Websocket API Python SD… вы можете использовать их с разными моделями ИИ в TypingMind, не настраивая подключение отдельно для каждой модели. Эта интеграция MCP работает локально на вашем устройстве через коннектор MCP TypingMind.

Руководство по настройке локального коннектора

Выберите этот способ, если серверу MCP нужен доступ к локальным файлам, приложениям или закрытым ресурсам на вашем компьютере.

1

Откройте настройки MCP

В TypingMind откройте «Настройки», затем «Расширенные настройки», перейдите в раздел «Протокол контекста модели» и выберите «Настроить коннектор».

  1. Откройте TypingMind в браузере.
  2. Нажмите значок настроек.
  3. Перейдите в «Расширенные настройки».
  4. Откройте раздел «Протокол контекста модели».
  5. Нажмите «Настроить коннектор» и выберите «Это устройство».
Экран настройки коннектора MCP в TypingMind с выбранным вариантом «Это устройство»
2

Выполните команду коннектора

Выберите «Это устройство», скопируйте команду из TypingMind и выполните её в терминале. Не останавливайте процесс, пока используете MCP.

  1. Скопируйте команду настройки, показанную в TypingMind.
  2. Откройте «Терминал» в macOS или Windows Terminal в Windows.
  3. Вставьте и выполните команду.
  4. Подтвердите установку пакета, если терминал запросит разрешение продолжить.
  5. Не закрывайте окно терминала и не останавливайте процесс, пока используете инструменты MCP.
3

Добавьте Spot, xStocks, and Futures REST and Websocket API Python SD… как сервер

Когда статус коннектора сменится на «Готов», нажмите «Изменить серверы» и вставьте конфигурацию сервера MCP.

  1. Дождитесь, пока статус коннектора сменится на «Готов».
  2. Нажмите «Изменить серверы».
  3. Вставьте конфигурацию сервера MCP для Spot, xStocks, and Futures REST and Websocket API Python SD….
  4. Сохраните список серверов.
  5. Обновите статус, если хотите убедиться, что коннектор по-прежнему готов к работе.
Настройки MCP в TypingMind с активным сервером и кнопкой «Изменить серверы»
{
  "mcpServers": {
    "python-kraken-sdk": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Используйте подключение с разными моделями

Сохраните список серверов, откройте раздел «Плагины», включите инструменты MCP для Spot, xStocks, and Futures REST and Websocket API Python SD…, затем выберите любую поддерживаемую модель ИИ в TypingMind и используйте инструменты в чате или назначьте их ИИ-агенту.

  1. Откройте страницу «Плагины» в TypingMind.
  2. Включите инструменты MCP для Spot, xStocks, and Futures REST and Websocket API Python SD….
  3. Начните чат и выберите модель ИИ, которую хотите использовать.
  4. Используйте инструменты MCP в чате или назначьте их ИИ-агенту.
  5. При необходимости переключайтесь на другую модель ИИ без повторного подключения MCP.
Чат TypingMind с включёнными инструментами MCP и выбранной ИИ-моделью
Можете помочь мне с этой задачей с помощью Spot, xStocks, and Futures REST and Websocket API Python SD…?
Spot, xStocks, and Futures REST and Websocket API Python SD…
Конечно. Я всё прочитал.
Вот что я нашёл с помощью Spot, xStocks, and Futures REST and Websocket API Python SD….

Часто задаваемые вопросы

Для чего используется сервер MCP Spot, xStocks, and Futures REST and Websocket API Python SD…?

Spot, xStocks, and Futures REST and Websocket API Python SD… — это сервер MCP, который позволяет совместимым ИИ-клиентам подключаться к внешним инструментам и получать контекст. В TypingMind достаточно один раз добавить этот сервер MCP, чтобы его инструменты стали доступны в вашем рабочем пространстве с ИИ.

Можно ли использовать сервер MCP Spot, xStocks, and Futures REST and Websocket API Python SD… с несколькими ИИ-моделями в TypingMind?

Да. TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому вы можете использовать Spot, xStocks, and Futures REST and Websocket API Python SD… с разными ИИ-моделями, например Claude, ChatGPT, Gemini или другими моделями, настроенными в TypingMind, без отдельной настройки сервера MCP для каждой модели.

Зачем использовать MCP Spot, xStocks, and Futures REST and Websocket API Python SD… с TypingMind?

TypingMind — один из лучших интерфейсов для чата с LLM: он объединяет разные ИИ-модели, промпты, плагины, ИИ-агентов, ключи API и инструменты MCP в одном рабочем пространстве. Подключив Spot, xStocks, and Futures REST and Websocket API Python SD…, вы сможете использовать его инструменты MCP с предпочитаемыми моделями, сохраняя удобную организацию работы с чатами в TypingMind.

Как подключить сервер MCP Spot, xStocks, and Futures REST and Websocket API Python SD… к TypingMind?

Spot, xStocks, and Futures REST and Websocket API Python SD… работает через локальный коннектор MCP TypingMind. Этот вариант лучше всего подходит, когда серверу MCP нужен доступ к локальным файлам, настольным приложениям, инструментам командной строки или закрытым ресурсам на вашем компьютере.

Какие инструменты предоставляет сервер MCP Spot, xStocks, and Futures REST and Websocket API Python SD… в TypingMind?

Spot, xStocks, and Futures REST and Websocket API Python SD… предоставляет возможности MCP, которые можно включить на странице «Плагины» в TypingMind и использовать в чате или назначить ИИ-агентам.

Нужно ли передавать TypingMind свои ключи API для использования сервера MCP Spot, xStocks, and Futures REST and Websocket API Python SD…?

Нет. TypingMind ориентирован прежде всего на локальную работу и позволяет вам контролировать выбор провайдеров моделей, ключи API, промпты и конфигурацию MCP. Если Spot, xStocks, and Futures REST and Websocket API Python SD… требует аутентификации, при создании подключения добавьте необходимые заголовки, настройки OAuth или локальную конфигурацию для этого сервера MCP.

Похожие серверы MCP

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇