Overview
Thekalshi_client.py module provides a reusable authenticated client for the Kalshi prediction market API. It handles RSA-PSS request signing, API endpoints, and order placement.
Environment Configuration
Required environment variables:KALSHI_API_KEY_ID- Your API key ID from KalshiKALSHI_PRIVATE_KEY_PATH- Path to RSA private key fileKALSHI_USE_DEMO- “true” for demo API, “false” for production
Helper Functions
get_api_base()
Determine the API base URL based on environment configuration.Returns demo or production API base URL
load_private_key()
Load the RSA private key from the configured file path.Loaded private key object for signing requests
KalshiClient Class
Constructor
Initialize an authenticated Kalshi API client.ValueErrorif required environment variables are missing
_sign_request(method, path, timestamp)
Generate RSA-PSS signature for API authentication.HTTP method (GET, POST, etc.)
API path including query parameters
Unix timestamp in milliseconds as string
Base64-encoded RSA-PSS signature
_request(method, path, **kwargs)
Make an authenticated API request with automatic signing.HTTP method
API endpoint path
Additional arguments passed to requests.request()
Parsed JSON response from API
Public API Methods
get_balance()
Retrieve account balance.Balance object with balance in cents
get_markets(series_ticker=None, status=“open”, limit=200, cursor=None)
Fetch markets with optional filtering.Filter by series (e.g., “KXBTC15M”)
Market status: “open”, “closed”, “settled”
Maximum markets to return
Pagination cursor for next page
API response with markets array and cursor
get_market(ticker)
Get details for a specific market.Market ticker symbol
Market object with all details
get_events(status=“open”, limit=200, cursor=None)
Fetch events (collections of related markets).Event status filter
Maximum events to return
Pagination cursor
API response with events array
place_order(ticker, side, contracts, price_cents, dry_run=False)
Place a limit order on Kalshi.Market ticker to trade
“yes” or “no”
Number of contracts to buy
Limit price per contract in cents (1-99)
If True, simulate order without executing
Order response with order_id and status
Authentication Flow
The client automatically handles authentication for all requests:- Generate timestamp (Unix milliseconds)
- Create signature message:
{timestamp}{method}/trade-api/v2{path} - Sign with RSA-PSS (SHA256, MAX_LENGTH salt)
- Base64 encode signature
- Add headers:
KALSHI-ACCESS-KEY: API key IDKALSHI-ACCESS-SIGNATURE: SignatureKALSHI-ACCESS-TIMESTAMP: Timestamp