Skip to main content

WS and HTTP clients for Kraken exchange API

Project description

kraken-connector

Release Build status codecov Commit activity License

WS and HTTP clients for Kraken exchange API

Installation

pip install kraken-connector

Usage

Basic client

from kraken_connector import HTTPClient, HTTPAuthenticatedClient

# Public endpoints
client = HTTPClient("https://api.kraken.com")

# Authenticated endpoints
auth_client = HTTPAuthenticatedClient(
    "https://api.kraken.com",
    api_key="your-api-key",
    api_secret="your-api-secret",
)

Retry on network errors

Retry is disabled by default. Enable it via ResilienceConfig:

from kraken_connector import HTTPClient, ResilienceConfig

config = ResilienceConfig(
    max_retries=3,        # retry up to 3 times on network errors
    backoff_base=1.0,     # initial backoff delay in seconds
    backoff_max=30.0,     # maximum backoff delay
)
client = HTTPClient("https://api.kraken.com", resilience=config)

Only transient network errors (connection refused, timeouts) are retried. API-level errors (rate limits, validation) are never retried at the transport layer — callers handle those via KrakenAPIError.

Rate limiting

The RateLimiter is a caller-controlled token bucket matching Kraken's tier-based rate limits. It is not automatic — callers opt in explicitly:

from kraken_connector import KrakenTier, RateLimiter
from kraken_connector.api.market_data import get_server_time

limiter = RateLimiter.from_tier(KrakenTier.STARTER)

# Sync — most API calls cost 1 token
with limiter.acquire(cost=1):
    response = get_server_time.sync(client=client)

# Async
async with limiter.async_acquire(cost=1):
    response = await get_server_time.asyncio(client=client)

# Ledger/trade history calls cost 2 tokens
with limiter.acquire(cost=2):
    response = get_trade_history.sync(client=auth_client, form_data=form)

The rate limiter blocks (sleeps) when tokens are depleted, waiting for the bucket to refill. It is thread-safe but not multiprocessing-safe.

Kraken tier parameters:

Tier Max tokens Decay rate
Starter 15 0.33/sec
Intermediate 20 0.5/sec
Pro 20 1.0/sec

Request logging

Enable request/response logging via ResilienceConfig:

import logging
from kraken_connector import HTTPClient, ResilienceConfig

logging.basicConfig(level=logging.DEBUG)

config = ResilienceConfig(enable_logging=True, log_level=logging.DEBUG)
client = HTTPClient("https://api.kraken.com", resilience=config)
# Logs: "HTTP GET https://api.kraken.com/0/public/Time"
# Logs: "HTTP GET https://api.kraken.com/0/public/Time -> 200 (0.12s)"

Logging uses Python's stdlib logging module under the logger name kraken_connector. Consumers can wire any logging framework (e.g., structlog) via its stdlib integration.

WebSocket v2

The ws package provides a full client for Kraken's WebSocket v2 API, with typed models, automatic reconnection, order book management, and trading support.

Public subscription

import asyncio
from kraken_connector.ws import KrakenWSClient
from kraken_connector.ws.subscribe import TickerParams
from kraken_connector.ws.envelopes import WSDataMessage

async def main():
    async with KrakenWSClient() as client:
        await client.subscribe(TickerParams(symbol=["BTC/USD"]))
        async for msg in client:
            if isinstance(msg, WSDataMessage) and msg.channel == "ticker":
                print(msg.data)

asyncio.run(main())

Authenticated subscription

Private channels (executions, balances) require a WebSocket token. TokenManager handles token lifecycle automatically:

from kraken_connector import HTTPAuthenticatedClient
from kraken_connector.ws import KrakenWSClient, TokenManager
from kraken_connector.ws.subscribe import ExecutionsParams

auth_client = HTTPAuthenticatedClient(
    "https://api.kraken.com",
    api_key="your-api-key",
    api_secret="your-api-secret",
)
tm = TokenManager(auth_client=auth_client)

async with KrakenWSClient(token_manager=tm) as client:
    await client.subscribe(ExecutionsParams())
    async for msg in client:
        print(msg.channel, msg.sequence, msg.data)

Trading

All 8 WS v2 trading methods are supported. The token is auto-injected when a TokenManager is configured:

from kraken_connector.ws.trading import AddOrderParams, CancelAllOrdersAfterParams

async with KrakenWSClient(token_manager=tm) as client:
    # Place a limit order.
    resp = await client.add_order(
        AddOrderParams(
            symbol="BTC/USD",
            side="buy",
            order_type="limit",
            order_qty=0.1,
            limit_price=26000.0,
            token="",  # auto-injected by TokenManager
        )
    )
    print("Order placed:", resp.result)

    # Dead man's switch — cancel all orders if no refresh within 60s.
    await client.cancel_all_orders_after(
        CancelAllOrdersAfterParams(token="", timeout=60)
    )

Order book management

Subscribe to the book channel and the client maintains local order book state with CRC32 checksum validation:

from kraken_connector.ws import KrakenWSClient
from kraken_connector.ws.subscribe import BookParams
from kraken_connector.ws.book import BookChecksumEvent

async with KrakenWSClient() as client:
    await client.subscribe(BookParams(symbol=["BTC/USD"], depth=10))
    async for msg in client:
        if isinstance(msg, BookChecksumEvent):
            print("Checksum mismatch — resubscribe:", msg.symbol)
            continue
        book = client.book_manager.get("BTC/USD")
        if book:
            print("Best bid:", book.best_bid, "Best ask:", book.best_ask)

Development

See CONTRIBUTING.md for development setup and guidelines.

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

kraken_connector-0.1.0.tar.gz (151.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kraken_connector-0.1.0-py3-none-any.whl (316.2 kB view details)

Uploaded Python 3

File details

Details for the file kraken_connector-0.1.0.tar.gz.

File metadata

  • Download URL: kraken_connector-0.1.0.tar.gz
  • Upload date:
  • Size: 151.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.26.7 CPython/3.11.15 Linux/6.14.0-1017-azure

File hashes

Hashes for kraken_connector-0.1.0.tar.gz
Algorithm Hash digest
SHA256 79ded8cbbc44d87b65722c7b65de11523aaa6199ffdac9ace606c59e1f403abb
MD5 04c5d2af59333a6c270516cf36ca05ee
BLAKE2b-256 bf2a2603e29f1f2ce8e088b0790c030ee796b945564eef8d6cd797f125191b36

See more details on using hashes here.

File details

Details for the file kraken_connector-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: kraken_connector-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 316.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.26.7 CPython/3.11.15 Linux/6.14.0-1017-azure

File hashes

Hashes for kraken_connector-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 57cec64072ec31b499caa5481c0b883c022e8f7fda13938a62f2be676e5e922a
MD5 6602e17f316f71c47e407606069d6d5a
BLAKE2b-256 30111886e257768c83961722469c743a36271724c8e6e684f6e62849bca784a3

See more details on using hashes here.

Supported by

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