Skip to main content

Add your description here

Project description

dtr-kalshi

A lightweight Python client for the Kalshi Trade API.

Quickstart

Installation

pip install dtr-kalshi

Authentication

Kalshi uses RSA key-pair authentication. You'll need:

  1. API Key ID — found in your Kalshi account settings.
  2. RSA private key file — a .key file in PEM format, downloaded when you create an API key.

Export both as environment variables so you don't hardcode credentials:

export KALSHI_API_KEY_ID="your-api-key-id"
export KALSHI_API_KEY_SECRET="/path/to/your/private_key.key"

Alternatively, pass them directly to the client constructor.

Sync usage

KalshiSyncClient is a straightforward blocking client suitable for scripts and simple applications.

from dtr_kalshi import KalshiSyncClient

# credentials are read from environment variables by default
client = KalshiSyncClient()

# use use_sandbox=True to hit the demo environment instead
# client = KalshiSyncClient(use_sandbox=True)

# GET /portfolio/balance
balance = client.get('/portfolio/balance')
print(balance)

# POST /portfolio/orders
order = client.post('/portfolio/orders', data={
    'ticker': 'INXD-23DEC31-B4000',
    'side': 'yes',
    'count': 10,
    'type': 'limit',
    'yes_price': 55,
})
print(order)

# DELETE /portfolio/orders/{order_id}
client.delete(f"/portfolio/orders/{order['order']['order_id']}")

Async usage

KalshiAsyncClient uses a shared httpx.AsyncClient for connection pooling. Use it as an async context manager so the underlying connection is closed cleanly on exit.

import asyncio
from dtr_kalshi import KalshiAsyncClient

async def main():
    async with KalshiAsyncClient() as client:
        balance = await client.get('/portfolio/balance')
        print(balance)

        # fan out multiple requests concurrently
        btc, eth = await asyncio.gather(
            client.get('/markets/KXBTC-25DEC31'),
            client.get('/markets/KXETH-25DEC31'),
        )
        print(btc, eth)

asyncio.run(main())

WebSocket usage

KalshiWebSocketConnection streams real-time market data. Use it as an async context manager.

Send commands with .send_message(cmd, params), which maps directly to the Kalshi WebSocket protocol.

Callback-based (recommended for multiple channels)

Register handlers with .on(channel, handler), then call .listen() to process messages indefinitely.

import asyncio
from dtr_kalshi import KalshiWebSocketConnection

async def main():
    async with KalshiWebSocketConnection() as ws:
        ws.on("ticker", lambda msg: print("ticker:", msg))
        ws.on("trade", lambda msg: print("trade:", msg))

        await ws.send_message("subscribe", {
            "channels": ["ticker", "trade"],
            "market_ticker": ["INXD-23DEC31-B4000"],
        })
        await ws.listen()

asyncio.run(main())

Iterator-based (for custom message handling)

Iterate directly over the connection with async for to handle all messages yourself.

import asyncio
from dtr_kalshi import KalshiWebSocketConnection

async def main():
    async with KalshiWebSocketConnection() as ws:
        await ws.send_message("subscribe", {
            "channels": ["orderbook_delta"],
            "market_ticker": ["INXD-23DEC31-B4000"],
        })
        async for msg in ws:
            print(msg)

asyncio.run(main())

Concurrent REST and WebSocket

Wrap .listen() in a task to run alongside REST calls.

import asyncio
from dtr_kalshi import KalshiAsyncClient, KalshiWebSocketConnection

async def main():
    async with KalshiAsyncClient() as client, KalshiWebSocketConnection() as ws:
        await ws.send_message("subscribe", {
            "channels": ["ticker"],
            "market_ticker": ["INXD-23DEC31-B4000"],
        })
        listen_task = asyncio.create_task(ws.listen())

        balance = await client.get('/portfolio/balance')
        print(balance)

        listen_task.cancel()

asyncio.run(main())

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

dtr_kalshi-0.1.0.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

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

dtr_kalshi-0.1.0-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: dtr_kalshi-0.1.0.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.7 {"installer":{"name":"uv","version":"0.11.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for dtr_kalshi-0.1.0.tar.gz
Algorithm Hash digest
SHA256 52ff1d62a201be9c9602b2e4e7c28140af1970f44e35ecd9de9f1bf6a6c0d658
MD5 d47d16c74feb367781a9b5e231ad807c
BLAKE2b-256 dbf6cbd9c97cabef696cd01c2086d675f5930aa6ddbcf910c27591164e5b0b7c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: dtr_kalshi-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.7 {"installer":{"name":"uv","version":"0.11.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for dtr_kalshi-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 addffbdeae5f479fe9cb4283fed322e3d56a0570684b130ca8f653fa594a5020
MD5 056561db1d2959bf5f305d8ea4007163
BLAKE2b-256 c26553c3466b7d0d8a39ee0127bc99bd5aeffd9db93d6235be19ae3413307d49

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