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.1.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.1-py3-none-any.whl (316.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: kraken_connector-0.1.1.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.17.0-1008-azure

File hashes

Hashes for kraken_connector-0.1.1.tar.gz
Algorithm Hash digest
SHA256 c9a4b28c6dc4b9f9bf4915e619a3b11e7c8cf8c7bd7800f90f9e3e388392fcd3
MD5 8486ee500e9dd78dd7ce6167ebb81ceb
BLAKE2b-256 7859ef0b352e7994972330f1a1d4a27f56ada02219ed6c709b88f1b5e02373df

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for kraken_connector-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b20b310f119c76ffba69b2f497668a06eacbaafe97bad4a0d3d05fc56d05f364
MD5 abe0dd096a4704eccae5eea0a542b0a7
BLAKE2b-256 e7e8d819da2ea699cf3e36d6f1f261d9e37befd3d7ab93a6a3c88ea0edbd39ab

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