Skip to main content

Kalshi Python SDK

Python Version License: MIT CFTC Rule 40.2 AsyncIO Gateway Tests

kalshi-python-sdk is the premier kalshi python sdk and institutional quantitative library for algorithmic trading on Kalshi, the premier CFTC-regulated designated contract market (DCM). Engineered for quantitative hedge funds, prop desks, and systematic prediction market traders, this kalshi trading library delivers high-throughput kalshi client asyncio execution, exact cftc prediction market python fee schedule compliance, and advanced derivatives analytics including Black-Scholes digital option implied volatility inversion, hazard rate term structure modeling, and Kyle's lambda microstructure spread compression.

Whether interfacing with real-time markets through the kalshi api python or routing orders via the institutional NaxosData Gateway (/api/v1/orderbooks/KALSHI/..., /api/v1/markets?venue=KALSHI), this repository provides strong typing (Pydantic v2), sub-millisecond execution modeling, zero-dependency numerical mathematics, and built-in offline failover.


Architecture Overview

flowchart TD
    subgraph DataFeeds["Data Feeds"]
        G["NaxosData API Gateway"]
        K["Kalshi DCM Native API"]
        O["Offline Fallback Mock Cache"]
    end

    subgraph CoreSDK["Core SDK Runtime"]
        C["KalshiClient / AsyncKalshiClient"]
        M["Pydantic v2 Models: Market, OrderBook, Candlestick, Trade, Position"]
    end

    subgraph QuantEngines["Quantitative Engines"]
        F["CFTC Rule 40.2 Fee Engine"]
        Q["Quadratic Execution Solver"]
        IV["Black-Scholes Binary IV Inverter"]
        TS["Probability Term Structure & Hazard Rates"]
        SC["Spread Compression & Micro-Price"]
    end

    subgraph Applications["Applications"]
        CLI["kalshi-cli Console Suite"]
        BOT["Automated Arbitrage & Market Making Bots"]
        EXP["JSON / CSV Institutional Data Exporters"]
    end

    G --> C
    K --> C
    O -.->|Failover| C
    C --> M
    M --> F
    M --> Q
    M --> IV
    M --> TS
    M --> SC
    F --> CLI
    Q --> CLI
    IV --> CLI
    TS --> CLI
    SC --> CLI
    F --> BOT
    Q --> BOT
    IV --> BOT
    TS --> BOT
    SC --> BOT
    C --> EXP

Key Features

  • Asynchronous & Synchronous Clients: Native httpx async event-loop integration for high-frequency market making or simple synchronous scripting with automated connection pooling.
  • CFTC Rule 40.2 Compliance: Exact implementation of the CFTC regulatory fee schedule, taking into account binary variance rounding, ceiling mechanics, maker rebates, and NFA transaction assessments.
  • Quadratic Execution Sizing: Analytically closed-form quadratic solver trading off alpha capture against market impact slippage (Kyle's $\lambda$) and regulatory fee drag under hard capital and exchange order size constraints.
  • Derivatives Analytics:
    • Closed-form and Newton-Raphson inversion of Black-Scholes cash-or-nothing digital options ($C = e^{-rT}\Phi(d_2)$).
    • Piecewise continuous hazard rate ($\lambda(t)$) term structure modeling with log-linear survival probability interpolation.
    • Micro-price estimation, quote depth imbalance, and spread compression ratio tracking.
  • Institutional Telemetry & Offline Fallback: Automated fallback to high-fidelity simulated orderbooks and market states when running in offline backtests, sandboxes, or during gateway network disruptions.
  • Production CLI: Inspect live/mock tickers, stream L2 orderbooks, optimize trade sizing, and export OHLCV/tick data to CSV/JSON.

Installation

# Clone the open-source repository
git clone https://github.com/nexosdata/kalshi-python-sdk.git
cd kalshi-python-sdk

# Install in editable mode with development dependencies
pip install -e ".[dev]"

Requirements: Python 3.10+, httpx >= 0.24.0, and pydantic >= 2.0.0.


Quickstart

1. Synchronous Market Data & Micro-Price Inspection

from kalshi import KalshiClient

# Initialize client (uses NaxosData API Gateway or offline mock mode)
with KalshiClient() as client:
    # Fetch active prediction markets
    markets = client.get_markets(limit=5)
    for m in markets:
        print(f"[{m.ticker}] {m.title} | Bid: ${m.yes_bid:.2f} Ask: ${m.yes_ask:.2f}")

    # Inspect Level 2 orderbook ladder and fair micro-price
    ticker = "KXFEDRATE-26DEC"
    ob = client.get_orderbook(ticker)
    print(f"Spread: ${ob.spread:.4f} | Mid: ${ob.mid_price:.4f} | Micro-Price: ${ob.micro_price:.4f}")

2. High-Throughput Asynchronous Orderbook Streaming

import asyncio
from kalshi import AsyncKalshiClient

async def monitor_markets():
    async with AsyncKalshiClient() as client:
        # Fetch orderbook asynchronously
        orderbook = await client.get_orderbook("KXFEDRATE-26DEC")
        print(f"Best YES Bid: {orderbook.best_yes_bid.quantity} @ ${orderbook.best_yes_bid.price:.2f}")
        print(f"Best YES Ask: {orderbook.best_yes_ask.quantity} @ ${orderbook.best_yes_ask.price:.2f}")

        # Compute spread compression metrics
        metrics = await client.get_spread_compression("KXFEDRATE-26DEC")
        if metrics:
            print(f"Depth Imbalance: {metrics.depth_imbalance:+.2f}")
            print(f"Kyle's Lambda: ${metrics.kyles_lambda:.6f} per contract")

asyncio.run(monitor_markets())

CFTC Rule 40.2 Fee Schedule & Mathematical Derivation

Kalshi operates as a Designated Contract Market (DCM) subject to CFTC regulatory filings. Binary prediction contracts pay $$1.00$ upon affirmative resolution or $$0.00$ otherwise, with prices bounded in $P \in [0.01, 0.99]$.

1. Variance-Dependent Regulatory Fee Formula

The theoretical uncertainty of a Bernoulli event contract at probability $P$ is governed by its variance:

$$\sigma_B^2 = P(1 - P)$$

Under Kalshi's CFTC Rule 40.2 regulatory submission, taker transaction fees are directly proportional to this variance. The fee factor is established at $\gamma = 0.07$ (7%). For an order of $N$ contracts at price $P$, the exchange fee in dollars is:

$$\text{Exchange Fee}(N, P) = \frac{\lceil 100 \times N \times \gamma \times P \times (1 - P) \rceil}{100}$$

where $\lceil \cdot \rceil$ represents the ceiling function rounding upwards to the nearest integer cent per CFTC exchange rules.

Total regulatory transaction costs include the National Futures Association (NFA) assessment fee $c_{\text{nfa}} = $0.0002$ per contract:

$$\text{Total Fee}(N, P) = \text{Exchange Fee}(N, P) + N \times c_{\text{nfa}}$$

2. Analytical Sensitivity & Marginal Fee Derivative

The sensitivity of the fee rate per contract with respect to price $P$ is given by the first derivative:

$$\frac{d}{dP} \left[ \gamma P (1 - P) \right] = \gamma (1 - 2P)$$

  • For out-of-the-money or deep in-the-money contracts ($P < 0.50$ or $P > 0.50$), fee drag is minimized ($P = 0.01 \implies \text{fee} \approx $0.000693$/contract).
  • At maximum uncertainty ($P = 0.50$), $\frac{d\text{Fee}}{dP} = 0$, achieving maximum fee drag of $$0.0175$/contract ($1.75$ cents).
  • Symmetry: $\text{Fee}(P) = \text{Fee}(1 - P)$, ensuring unbiased neutrality between buying YES or NO.

3. Quantitative Quadratic Execution Solver

When deploying an alpha model with fair valuation $V \in (0, 1)$ against best market offer $P_0$, aggressive liquidity consumption causes market impact slippage modeled via linear orderbook depth slope $\lambda$:

$$P(q) = P_0 + \lambda q$$

Total execution cash outflow for $Q$ contracts:

$$C(Q) = \int_0^Q (P_0 + \lambda q) dq + Q \cdot \bar{f}(P_0) = \left(P_0 + \bar{f}(P_0)\right) Q + \frac{1}{2}\lambda Q^2$$

Expected payout: $E[\text{Payout}] = V \cdot Q$. The expected net profit objective function $\Pi(Q)$ is strictly concave quadratic:

$$\Pi(Q) = (V - P_0 - \bar{f}(P_0)) Q - \frac{1}{2}\lambda Q^2$$

Defining net edge $\mathcal{E} = V - P_0 - \bar{f}(P_0)$:

  • If $\mathcal{E} \le 0$, the edge does not exceed regulatory fee drag $\implies Q^* = 0$.
  • If $\mathcal{E} > 0$, the unconstrained First-Order Condition $\frac{d\Pi}{dQ} = 0$ yields:

$$Q^*_{\text{unconstrained}} = \frac{\mathcal{E}}{\lambda} = \frac{V - P_0 - \bar{f}(P_0)}{\lambda}$$

Subject to order limit $Q \le Q_{\max}$ and quadratic capital budget constraint $C(Q) \le B_{\max}$:

$$Q^*{\text{budget}} = \frac{-(P_0 + \bar{f}) + \sqrt{(P_0 + \bar{f})^2 + 2\lambda B{\max}}}{\lambda}$$

$$Q^* = \left\lfloor \min\left( Q^{\text{unconstrained}}, Q{\max}, Q^_{\text{budget}} \right) \right\rfloor$$

from kalshi import solve_optimal_order_size

# Solve optimal trade size balancing alpha, CFTC fees, and Kyle's lambda
solution = solve_optimal_order_size(
    target_valuation=0.72,   # Proprietary model fair probability
    market_price=0.62,       # Current best ask
    depth_liquidity=15000,   # Available book contracts
    max_order_size=2500,     # Risk limit
    capital_budget=1500.0,   # $1,500 cash allocation
)

print(f"Optimal Contracts (Q*): {solution.optimal_contracts}")
print(f"Expected Net Profit:     ${solution.expected_net_profit:.2f}")
print(f"CFTC Fee Drag:          -${solution.estimated_cftc_fees:.2f}")
print(f"Binding Constraint:      {solution.binding_constraint}")

Quantitative Analytics & Derivatives Engine

1. Black-Scholes Digital Option Implied Volatility Inversion

A Kalshi contract paying $$1.00$ when underlying index $S_T \ge K$ represents a European cash-or-nothing binary call option:

$$C_{\text{binary}} = e^{-rT} \Phi(d_2)$$

where:

$$d_2 = \frac{\ln(S / K) + \left(r - \frac{1}{2}\sigma^2\right)T}{\sigma \sqrt{T}}$$

Given observed market price $P$, we solve for annualized implied volatility $\sigma$ by inverting $d_2 = \Phi^{-1}(P e^{rT}) = z$. This reduces to the quadratic equation:

$$\frac{1}{2} T \sigma^2 + z \sqrt{T} \sigma - \left(\ln(S / K) + r T\right) = 0$$

$$\sigma^* = \frac{-z \sqrt{T} + \sqrt{z^2 T + 2 T (\ln(S/K) + rT)}}{T}$$

from kalshi import calculate_implied_volatility

res = calculate_implied_volatility(
    contract_price=0.50,     # Binary call price ($0.50)
    spot=100.0,              # Current index / asset price
    strike=100.0,            # Strike price
    time_to_expiry=0.25,     # 3 months (0.25 years)
    risk_free_rate=0.05,     # 5.0% risk-free yield
)

print(f"Implied Volatility: {res.implied_volatility * 100:.2f}% | d2: {res.d2:.4f}")

2. Probability Term Structure & Hazard Rates

Prediction market contracts with sequential maturities $T_1 < T_2 < \dots < T_n$ define a cumulative probability curve $P(t)$. The survival probability $S(t) = 1 - P(t)$ is parameterized by continuous hazard rates $\lambda(t)$:

$$S(T_{i+1}) = S(T_i) \exp\left( -\bar{\lambda}{i, i+1} (T{i+1} - T_i) \right) \implies \bar{\lambda}{i, i+1} = -\frac{\ln S(T{i+1}) - \ln S(T_i)}{T_{i+1} - T_i}$$

from kalshi import ProbabilityTermStructure

points = [(14.0, 0.22), (30.0, 0.35), (60.0, 0.52), (90.0, 0.65), (180.0, 0.81)]
term_structure = ProbabilityTermStructure(points=points)

# Interpolate probability at an unlisted intermediate horizon (e.g., 45 days)
prob_45d = term_structure.interpolate_probability(45.0)
print(f"Interpolated 45-day Event Probability: {prob_45d * 100:.2f}%")

3. Spread Compression & Micro-Price Fair Value

The volume-weighted micro-price accounts for bid-ask queue imbalance:

$$P_{\text{micro}} = \frac{Q_{\text{bid}} P_{\text{ask}} + Q_{\text{ask}} P_{\text{bid}}}{Q_{\text{bid}} + Q_{\text{ask}}}$$

The Spread Compression Index (SCI) tracks the degree to which maker competition has compressed the spread toward the exchange tick minimum ($$0.01$):

$$\text{SCI} = \frac{$0.01}{\max($0.01, P_{\text{ask}} - P_{\text{bid}})} \in (0, 1.0]$$

from kalshi import analyze_spread_compression, OrderBook, OrderBookLevel

ob = OrderBook(
    ticker="KXFEDRATE-26DEC",
    yes_bids=[OrderBookLevel(price=0.62, quantity=15000)],
    yes_asks=[OrderBookLevel(price=0.63, quantity=5000)],
)
metrics = analyze_spread_compression(ob)
print(f"Micro-Price:        ${metrics.micro_price:.4f}")
print(f"Depth Imbalance:    {metrics.depth_imbalance:+.2f}")
print(f"Compression Index:  {metrics.compression_index:.2f} (1.0 = minimum tick)")

Command Line Interface (CLI)

The SDK provides kalshi-cli (and alias kalshi-sdk):

# List active prediction markets
kalshi-cli markets --limit 5

# View detailed market specifications and quotes
kalshi-cli ticker KXFEDRATE-26DEC

# Inspect Level 2 orderbook ladder and micro-price
kalshi-cli orderbook KXFEDRATE-26DEC --depth 5

# Compute exact CFTC Rule 40.2 fees for an order
kalshi-cli fee --contracts 500 --price 0.62

# Run quantitative quadratic sizing solver
kalshi-cli optimize --target 0.72 --price 0.62 --depth 15000 --max-contracts 2500

# Calculate Black-Scholes binary implied volatility
kalshi-cli analytics --calc-iv --price 0.50 --spot 100 --strike 100 --time 0.25

# Display probability term structure and hazard rates
kalshi-cli analytics --term-structure

# Export market orderbook or candlesticks to JSON or CSV
kalshi-cli export --ticker KXFEDRATE-26DEC --data-type orderbook --format json --output book.json
kalshi-cli export --ticker KXFEDRATE-26DEC --data-type candlesticks --format csv --output ohlcv.csv

NaxosData API Gateway & Telemetry

The SDK integrates seamlessly with the NaxosData API Gateway, providing an institutional aggregation layer for cross-venue prediction market routing:

Endpoint Method Description
/api/v1/markets?venue=KALSHI GET Filterable directory of all active Kalshi event contracts
/api/v1/markets/{ticker}?venue=KALSHI GET Real-time quote, volume, and settlement criteria
/api/v1/orderbooks/KALSHI/{ticker} GET Snapshot of Level 2 bids and asks
/api/v1/candlesticks/KALSHI/{ticker} GET Historical OHLCV aggregation bars (1m, 5m, 1h, 1d)
/api/v1/trades/KALSHI/{ticker} GET Executed trade prints with aggressor side tagging
/api/v1/positions?venue=KALSHI GET Account portfolio positions and unrealized/realized PnL
/api/v1/settlements/KALSHI/{ticker} GET Official determination notices and payout reconciliations

Offline Mode & Graceful Degradation

To enable hermetic offline backtesting and CI/CD validation without network dependencies, instantiate the client with offline_mode=True or rely on automated failover when gateway connections encounter network timeouts.


Running the Automated Test Suite

The test suite covers model validation, HTTP dispatch, CFTC fee math, quadratic solvers, analytics, and CLI commands:

# Execute full unit test suite with 100% pass rate
python3 -m unittest discover tests -v

All 59 unit tests execute in under 0.1 seconds without external mocking dependencies.


License

This project is licensed under the MIT License. See the LICENSE file for complete details.

Copyright (c) 2026 NaxosData Contributors & William Gonda.

Metadata

Release files for kalshi-python-sdk 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kalshi-python-sdk 1.0.0
File Size Uploaded Provenance Actions
kalshi_python_sdk-1.0.0.tar.gz 42.5 kB Without provenance Details for kalshi_python_sdk-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kalshi-python-sdk 1.0.0
File Interpreter ABI Platform Actions
kalshi_python_sdk-1.0.0-py3-none-any.whl Python 3 none any Details for kalshi_python_sdk-1.0.0-py3-none-any.whl

Total release size: 75.3 kB

Release files / kalshi_python_sdk-1.0.0.tar.gz

Download URL kalshi_python_sdk-1.0.0.tar.gz
Size 42.5 kB
Tags Source
SHA-256 checksum
How to use checksums
bcde1038fa65e90fb7211e34564a7f81144d4b2f60b6258a6550eb4916618cb3
BLAKE2b-256 checksum
How to use checksums
b7edbe6d77e550151e9ec8822861e4b642086db9b21f06be6dfcbae57943acba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Release files / kalshi_python_sdk-1.0.0-py3-none-any.whl

Download URL kalshi_python_sdk-1.0.0-py3-none-any.whl
Size 32.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e82429dbf9ea16e86a4cb2bc82ee6b05faee6c88524a075d9f90c664c3249369
BLAKE2b-256 checksum
How to use checksums
4bb4260338c24ee7abddbafb22195788bade90edc2fea4cb8e5830a873e98a6b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Security for kalshi-python-sdk 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page