↓ Skip to main content

Kalshi API wrapper

stakepd.kalshi_data gets data from the Kalshi prediction market as pandas DataFrames, ready for analysis.
Kalshi Trade API v2 pandas DataFrames Read-only RSA & Ed25519 keys

It wraps the Kalshi Trade API v2 and deals with authentication, pagination, retries and type conversion, so you can work with the data straight away.

from stakepd import kalshi_data as kd

client = kd.KalshiClient()
markets = client.get_markets(status="open", series_ticker="KXHIGHNY")
๐Ÿ”AuthenticationEvery request is signed for you. Market data needs no key at all.
๐Ÿ“„PaginationPages are followed automatically and joined into one DataFrame.
๐Ÿ”RetriesRate-limit and server errors retry with exponential backoff.
๐ŸงฎClean typesPrices in dollars, counts as floats, times as UTC datetime64.

Method index:

โ˜… marks the methods you'll use most. kalshi_data referenceEvery class, method and exception on its own page, with returned columns and examples. โ†’

Installation
#

kalshi_data needs two packages on top of stakepd’s own: requests for HTTP and cryptography for signing requests. Install them with the kalshi extra:

Terminal:

pip install "stakepd[kalshi]"

Jupyter:

%pip install "stakepd[kalshi]"

In a Jupyter notebook, use %pip so the package goes into the notebook’s own Python.

Importing plain stakepd doesn’t load the Kalshi module. It loads only when you import stakepd.kalshi_data.

Quickstart
#

import pandas as pd
from stakepd import kalshi_data as kd

client = kd.KalshiClient()          # market data is public: no API key needed

# 1. Find markets: today's NYC high-temperature brackets
markets = client.get_markets(status="open", series_ticker="KXHIGHNY")
print(markets[["ticker", "yes_sub_title", "yes_bid", "yes_ask", "volume"]])

# 2. Price history for the most-traded bracket
ticker = markets.sort_values("volume", ascending=False).iloc[0]["ticker"]
candles = client.get_candlesticks(ticker, start="2026-11-26", interval="1h")
candles["price_close"].plot(title=ticker)

# 3. Recent trades
trades = client.get_trades(ticker, max_results=500)

# 4. Your own account (needs an API key, see "Authentication")
me = kd.KalshiClient.from_env()
positions = me.get_positions()

Key concepts
#

Series, events and markets
#

Kalshi organises contracts in three levels:

SeriesA recurring template.
"Highest temperature in NYC" (daily)
KXHIGHNY
โ†’
EventOne instance of a series.
"Highest temperature in NYC on Nov 27"
KXHIGHNY-26NOV27
โ†’
MarketOne yes/no contract within an event.
"57ยฐ to 58ยฐ"
KXHIGHNY-26NOV27-B57.5

Each market is a binary contract that pays $1 if it resolves YES and $0 otherwise. In many events, such as temperature brackets, the markets are mutually exclusive: exactly one of them resolves YES.

Typical ways to drill down:

client.get_series_list(category="Climate and Weather")   # find series
client.get_events(series_ticker="KXHIGHNY")              # events in a series
client.get_markets(event_ticker="KXHIGHNY-26NOV27")      # markets in an event

How the data is shaped
#

Every method returns either a DataFrame or a Series, except two that return a plain dict (get_exchange_status, get_balance). The wrapper applies these conventions everywhere:

ConventionDetails
Prices are float dollarsBetween 0.00 and 1.00. Because a contract pays $1, a price is also the market’s implied probability of YES: yes_ask = 0.71 means roughly a 71% chance.
Contract counts are floatKalshi allows fractional contracts, so volume, count, position and similar columns can hold values like 18.46.
Simpler column namesKalshi’s _dollars and _fp suffixes are dropped: yes_bid_dollars becomes yes_bid, and volume_fp becomes volume. If removing a suffix would clash with an existing column, the original name is kept.
Times are UTC datetime64Columns ending in _time, _date, _datetime or _ts become timezone-aware datetime64[ns, UTC]. Use .dt.tz_convert("America/New_York") for local time.
One unit for moneyThe few fields Kalshi sends in cents (balance, portfolio_value, settlement revenue and value) are converted to dollars.
Key columns firstIdentifying columns (ticker, prices, volumeโ€ฆ) come first, followed by every other field Kalshi returns.
Empty results keep their columnsA query with no matches returns an empty DataFrame that still has the main columns, so df["ticker"] works either way.
Nested fields are kept as-isFields like price_ranges or product_metadata stay as Python lists or dicts in a single column.

Time arguments
#

Every time argument (start, end, min_close, โ€ฆ) accepts any of these:

TypeExample
str"2026-11-01", "2026-11-01 14:30", "2026-11-01T14:30:00-05:00"
datetime.datetime / datetime.datedatetime(2026, 11, 1, 14, 30), date(2026, 11, 1)
pandas.Timestamppd.Timestamp("2026-11-01", tz="US/Eastern"), pd.Timestamp.now(tz="UTC") - pd.Timedelta(days=7)
int / floatUnix seconds, e.g. 1793577600

Times without a timezone are treated as UTC.

Kalshi expects seconds, so passing milliseconds (e.g. 1793577600000) raises a ValueError rather than silently asking for the wrong date.

Pagination and max_results
#

Kalshi returns long lists in pages. Every list method follows the pages for you and returns one combined DataFrame.

  • max_results=None (the default) fetches everything that matches.
  • max_results=500 stops after 500 rows, and requests no more pages than it needs.

Some queries match a lot of rows: for example get_markets() with no filters, or get_trades() without a ticker or time window. For those, set max_results or add a filter.

Authentication
#

Market data is public. Portfolio data (balance, positions, fills, orders, settlements) needs a Kalshi API key, which has two parts:

  1. API key ID: a string like a1b2c3d4-....
  2. Private key: a .pem file you download once when you create the key.

Create a key at kalshi.com โ†’ Account & security โ†’ API Keys (Kalshi’s guide). Both RSA and Ed25519 keys are supported.

Keep the .pem file private: never commit it to git or paste it into a notebook you share.

Option A: pass the credentials directly

client = kd.KalshiClient(
    api_key_id="a1b2c3d4-...",
    private_key_path="~/.kalshi/kalshi_private_key.pem",
)

Option B: environment variables (recommended)

Add these to ~/.zshrc (or your shell’s profile):

export KALSHI_API_KEY_ID="a1b2c3d4-..."
export KALSHI_PRIVATE_KEY_PATH="$HOME/.kalshi/kalshi_private_key.pem"

Then, in Python:

client = kd.KalshiClient.from_env()

The client signs every request with your key, as Kalshi requires. You never handle signatures yourself.

Demo environment: Kalshi runs a separate demo exchange with fake money. Demo keys only work on demo, and production keys only work on production.
demo = kd.KalshiClient.from_env(environment="demo")

Client
#

KalshiClient
#

kd.KalshiClient(api_key_id=None, private_key=None, private_key_path=None, *,
                environment="prod", base_url=None, timeout=30.0, max_retries=3, session=None)

Creates a client. Without credentials, the client can fetch every market-data endpoint. With credentials, it can also fetch portfolio data.

Parameters:

  • api_key_id (str, optional): Your Kalshi API key ID.
  • private_key (str or bytes, optional): The private key’s PEM text. Use this or private_key_path, not both.
  • private_key_path (str or os.PathLike, optional): Path to the private key .pem file. ~ is expanded.
  • environment (str, optional): "prod" (default) or "demo".
  • base_url (str, optional): A custom API base URL. Overrides environment.
  • timeout (float, optional): Seconds to wait for each HTTP response. Default 30.0.
  • max_retries (int, optional): How many times to retry a request that gets a rate-limit (429) or server (5xx) error, with exponential backoff. Default 3.
  • session (requests.Session, optional): Use your own HTTP session, for example to add a proxy or for testing. By default, the client builds one with retries.

Returns:

  • KalshiClient

Raises:

  • KalshiAuthError: if only one of api_key_id and a private key is given, or the key file can’t be read or parsed.
  • ValueError: if environment is not "prod" or "demo".

Attributes and other methods:

  • client.is_authenticated (bool): True if the client has credentials.
  • client.base_url (str): The API URL in use.
  • client.close(): Closes the HTTP session. You can also use the client as a context manager:
with kd.KalshiClient() as client:
    markets = client.get_markets(status="open", max_results=100)

Example:

client = kd.KalshiClient()
print(client)
Output:
KalshiClient(base_url='https://external-api.kalshi.com/trade-api/v2', authenticated=False)

KalshiClient.from_env
#

Class methodAPI keyMethod page โ†’
kd.KalshiClient.from_env(**kwargs)

Creates an authenticated client from environment variables. It reads KALSHI_API_KEY_ID, plus either KALSHI_PRIVATE_KEY_PATH (path to the .pem file) or KALSHI_PRIVATE_KEY (the PEM text itself).

Parameters:

  • **kwargs: Passed to the KalshiClient constructor, e.g. environment="demo" or timeout=60.

Returns:

  • KalshiClient: an authenticated client.

Raises:

  • KalshiAuthError: if the environment variables are not set.

Example:

client = kd.KalshiClient.from_env()
print(client.is_authenticated)
Output:
True

Market data
#

These methods work with or without an API key.

get_markets
#

โ˜… Most usedโ†’ DataFrameMethod page โ†’
client.get_markets(*, status=None, event_ticker=None, series_ticker=None, tickers=None,
                   min_close=None, max_close=None, min_settled=None, max_settled=None,
                   max_results=None, **filters)

Lists markets, one row per market. This is the usual starting point for finding contracts to analyse.

Parameters:

  • status (str, optional): "unopened", "open", "paused", "closed" or "settled".
  • event_ticker (str, optional): Only markets in this event, e.g. "KXHIGHNY-26NOV27".
  • series_ticker (str, optional): Only markets in this series, e.g. "KXHIGHNY".
  • tickers (str or list[str], optional): Only these market tickers.
  • min_close, max_close (time, optional): Only markets that close within this window.
  • min_settled, max_settled (time, optional): Only markets that settled within this window.
  • max_results (int, optional): Stop after this many markets. None fetches all of them.
  • **filters: Any other Kalshi query parameter, passed through unchanged. For example, mve_filter="exclude" leaves out multi-leg “combo” markets.

Returns:

  • pandas.DataFrame: one row per market. Main columns:
ColumnTypeDescription
tickerstrMarket ticker
event_tickerstrParent event
statusstractive, closed, determined, finalized, โ€ฆ (Kalshi’s internal status names, which differ from the status filter values)
yes_sub_titlestrWhat YES means, e.g. "57ยฐ to 58ยฐ"
yes_bid, yes_askfloatBest bid and ask for YES, in dollars (= implied probability)
no_bid, no_askfloatBest bid and ask for NO
last_pricefloatPrice of the most recent trade
volume, volume_24hfloatContracts traded, all time and over the last 24 hours
open_interestfloatContracts currently held
open_time, close_timedatetime64[ns, UTC]When trading opens and closes
resultstr"yes" / "no" once settled, empty before

Every other field Kalshi returns is included too, such as rules_primary, previous_price, yes_bid_size, created_time, price_ranges and market_type.

Example:

markets = client.get_markets(status="open", series_ticker="KXHIGHNY")
print(markets[["ticker", "yes_sub_title", "yes_bid", "yes_ask", "volume", "close_time"]].head(4))
Output:
                   ticker yes_sub_title  yes_bid  yes_ask    volume                close_time
0    KXHIGHNY-26NOV27-T64  65ยฐ or above     0.00     0.01    182.00 2026-11-28 06:00:00+00:00
1    KXHIGHNY-26NOV27-T57  56ยฐ or below     0.29     0.31  11083.45 2026-11-28 06:00:00+00:00
2  KXHIGHNY-26NOV27-B63.5    63ยฐ to 64ยฐ     0.00     0.01    502.00 2026-11-28 06:00:00+00:00
3  KXHIGHNY-26NOV27-B61.5    61ยฐ to 62ยฐ     0.00     0.01    753.00 2026-11-28 06:00:00+00:00

More examples:

# Markets closing in the next 24 hours
now = pd.Timestamp.now(tz="UTC")
closing_soon = client.get_markets(status="open", min_close=now, max_close=now + pd.Timedelta(hours=24))

# Specific markets
client.get_markets(tickers=["KXHIGHNY-26NOV27-B57.5", "KXHIGHNY-26NOV27-T57"])

# Everything that settled last week
settled = client.get_markets(status="settled", min_settled="2026-11-16", max_settled="2026-11-23")

get_market
#

โ˜… Most usedโ†’ SeriesMethod page โ†’
client.get_market(ticker)

Gets one market.

Parameters:

  • ticker (str): Market ticker.

Returns:

  • pandas.Series: indexed by field name, with the same fields as a get_markets row. Its .name is the ticker.

Raises:

  • KalshiAPIError: with status_code == 404 if the market doesn’t exist.

Example:

m = client.get_market("KXHIGHNY-26NOV27-B57.5")
print(m[["event_ticker", "status", "yes_sub_title", "yes_bid", "yes_ask", "last_price", "volume", "close_time"]])
Output:
event_ticker              KXHIGHNY-26NOV27
status                              active
yes_sub_title                   57ยฐ to 58ยฐ
yes_bid                                0.7
yes_ask                               0.71
last_price                            0.71
volume                            12849.67
close_time       2026-11-28 06:00:00+00:00
Name: KXHIGHNY-26NOV27-B57.5, dtype: object

get_orderbook
#

โ†’ DataFrameMethod page โ†’
client.get_orderbook(ticker, depth=None)

Gets the current order book for a market, in long format.

Kalshi lists bids only, for both YES and NO. A NO bid at price p is the same as a YES ask at 1 - p, so:

  • best YES ask = 1 - best NO bid
  • best NO ask = 1 - best YES bid

Parameters:

  • ticker (str): Market ticker.
  • depth (int, optional): Return only the best N price levels on each side (1โ€“100). None returns the whole book.

Returns:

  • pandas.DataFrame, with each side sorted best price first:
ColumnTypeDescription
sidestr"yes" or "no"
pricefloatBid price in dollars
quantityfloatContracts bid at that price

Raises:

  • ValueError: if depth is outside 1โ€“100.

Example:

book = client.get_orderbook("KXHIGHNY-26NOV27-B57.5", depth=3)
print(book)
Output:
  side  price  quantity
0  yes   0.70    345.44
1  yes   0.69      2.00
2  yes   0.68     83.81
3   no   0.29    109.00
4   no   0.28     46.80
5   no   0.27     41.00

The best YES bid is 0.70, and the best YES ask is 1 โˆ’ 0.29 = 0.71.

yes = book[book.side == "yes"]
no = book[book.side == "no"]
best_bid, best_ask = yes.price.max(), 1 - no.price.max()
spread = best_ask - best_bid           # 0.01

get_trades
#

โ˜… Most usedโ†’ DataFrameMethod page โ†’
client.get_trades(ticker=None, *, start=None, end=None, max_results=None)

Lists public trades (every matched trade on the exchange, not just yours), newest first.

Parameters:

  • ticker (str, optional): Only trades in this market. None returns trades across all markets.
  • start, end (time, optional): Only trades within this window.
  • max_results (int, optional): Stop after this many trades. Without a ticker or time window, set this: there can be millions of trades.

Returns:

  • pandas.DataFrame: one row per trade.
ColumnTypeDescription
trade_idstrUnique trade ID
tickerstrMarket ticker
created_timedatetime64[ns, UTC]When the trade happened
yes_price, no_pricefloatTrade price for each side (they add up to 1)
countfloatContracts traded
taker_outcome_sidestr"yes" or "no": the side the aggressor (taker) bought
taker_book_sidestr"bid" or "ask"

Example:

trades = client.get_trades("KXHIGHNY-26NOV27-B57.5", max_results=4)
print(trades[["created_time", "yes_price", "no_price", "count", "taker_outcome_side"]])
Output:
                      created_time  yes_price  no_price  count taker_outcome_side
0 2026-11-27 07:09:33.402301+00:00       0.71      0.29   5.00                yes
1 2026-11-27 07:08:36.563541+00:00       0.70      0.30  40.00                 no
2 2026-11-27 07:07:19.752408+00:00       0.70      0.30  18.46                 no
3 2026-11-27 07:06:14.298487+00:00       0.70      0.30  15.38                 no

More examples:

# All trades in a market over one day
day = client.get_trades("KXHIGHNY-26NOV27-B57.5", start="2026-11-26", end="2026-11-27")

# Volume-weighted average price (VWAP)
vwap = (day.yes_price * day["count"]).sum() / day["count"].sum()

# Contracts traded per 15 minutes
day.set_index("created_time")["count"].resample("15min").sum()
count is also the name of a DataFrame method, so write df["count"] rather than df.count.

get_candlesticks
#

โ˜… Most usedโ†’ DataFrameMethod page โ†’
client.get_candlesticks(ticker, start, end=None, *, interval="1h", series_ticker=None)

Gets OHLC price history for a market as a time-indexed DataFrame, ready to plot or resample.

Kalshi allows at most 5,000 candles per request. Longer ranges are split into several requests and joined automatically. For example, a month of 1-minute candles takes about 9 requests.

Parameters:

  • ticker (str): Market ticker.
  • start (time): Start of the range.
  • end (time, optional): End of the range. Defaults to now.
  • interval (str or int, optional): Candle length: "1m", "1h" (default) or "1d". The equivalent minutes 1, 60 and 1440 also work.
  • series_ticker (str, optional): The market’s series ticker. If you leave it out, it’s looked up for you, which costs two extra requests. Pass it when you fetch many markets from the same series.

Returns:

  • pandas.DataFrame, indexed by end_period_ts (a UTC DatetimeIndex, the end of each candle) and sorted oldest first:
ColumnTypeDescription
price_open, price_high, price_low, price_closefloatOHLC of traded prices. NaN in candles with no trades.
price_meanfloatMean traded price within the candle
price_previousfloatLast traded price before this candle
yes_bid_open, yes_bid_high, yes_bid_low, yes_bid_closefloatOHLC of the best YES bid (quoted, so defined even without trades)
yes_ask_open, yes_ask_high, yes_ask_low, yes_ask_closefloatOHLC of the best YES ask
volumefloatContracts traded in the candle
open_interestfloatOpen interest at the end of the candle

Raises:

  • ValueError: if interval isn’t recognised, or start isn’t before end.

Example:

candles = client.get_candlesticks("KXHIGHNY-26NOV27-B57.5", start="2026-11-26",
                                  interval="1h", series_ticker="KXHIGHNY")
print(candles[["price_open", "price_high", "price_low", "price_close", "volume"]].dropna().tail(4))
Output:
                           price_open  price_high  price_low  price_close   volume
end_period_ts
2026-11-27 04:00:00+00:00        0.30        0.69       0.30         0.50  3198.40
2026-11-27 05:00:00+00:00        0.51        0.57       0.51         0.57   594.85
2026-11-27 06:00:00+00:00        0.57        0.77       0.57         0.74  3850.81
2026-11-27 07:00:00+00:00        0.74        0.76       0.70         0.72  2390.41

More examples:

# Plot the probability over time
candles["price_close"].ffill().plot(ylabel="P(YES)")

# Mid-price is defined even when nothing traded
candles["mid"] = (candles.yes_bid_close + candles.yes_ask_close) / 2

# Convert to New York time
candles.index = candles.index.tz_convert("America/New_York")

# Downsample 1-minute candles to 5-minute candles
m1 = client.get_candlesticks(ticker, start="2026-11-26", interval="1m", series_ticker="KXHIGHNY")
m5 = m1.resample("5min").agg({"price_open": "first", "price_high": "max",
                              "price_low": "min", "price_close": "last", "volume": "sum"})

get_events
#

โ†’ DataFrameMethod page โ†’
client.get_events(*, status=None, series_ticker=None, tickers=None, min_close=None,
                  max_results=None, **filters)

Lists events, one row per event.

Parameters:

  • status (str, optional): "unopened", "open", "closed" or "settled".
  • series_ticker (str, optional): Only events in this series.
  • tickers (str or list[str], optional): Only these event tickers.
  • min_close (time, optional): Only events with at least one market closing after this time.
  • max_results (int, optional): Stop after this many events.
  • **filters: Any other Kalshi query parameter, passed through unchanged.

Returns:

  • pandas.DataFrame: one row per event.
ColumnTypeDescription
event_tickerstrEvent ticker
series_tickerstrParent series
titlestrEvent title
sub_titlestrSubtitle (often the date)
mutually_exclusiveboolTrue if at most one market in the event can resolve YES
strike_datedatetime64[ns, UTC]When the event’s outcome is determined

Example:

events = client.get_events(series_ticker="KXHIGHNY", max_results=3)
print(events[["event_ticker", "title", "strike_date"]])
Output:
       event_ticker                                              title               strike_date
0  KXHIGHNY-26NOV27  Highest temperature in New York City on Nov 27... 2026-11-28 06:00:00+00:00
1  KXHIGHNY-26NOV26  Highest temperature in New York City on Nov 26... 2026-11-27 06:00:00+00:00
2  KXHIGHNY-26NOV25  Highest temperature in New York City on Nov 25... 2026-11-26 06:00:00+00:00

get_event
#

โ†’ SeriesMethod page โ†’
client.get_event(event_ticker)

Gets one event. To get its markets, use client.get_markets(event_ticker=...).

Parameters:

  • event_ticker (str): Event ticker.

Returns:

  • pandas.Series: the same fields as a get_events row.

Example:

event = client.get_event("KXHIGHNY-26NOV27")
print(event[["series_ticker", "title", "mutually_exclusive"]])
Output:
series_ticker                                                  KXHIGHNY
title                 Highest temperature in New York City on Nov 27...
mutually_exclusive                                                 True
Name: KXHIGHNY-26NOV27, dtype: object

get_series_list
#

โ†’ DataFrameMethod page โ†’
client.get_series_list(*, category=None, tags=None, include_volume=False)

Lists series. Use it to discover what Kalshi offers. Kalshi returns this list in a single response, with no paging.

Parameters:

  • category (str, optional): Only series in this category. It’s exact and case-sensitive: e.g. "Sports", "Politics", "Elections", "Economics", "Financials", "Crypto", "Climate and Weather", "Entertainment". get_series_list()["category"].unique() lists them all.
  • tags (str or list[str], optional): Only series with these tags.
  • include_volume (bool, optional): Add a volume column with the total contracts traded. Default False.

Returns:

  • pandas.DataFrame: one row per series. Main columns: ticker, title, category, frequency ("daily", "weekly", "monthly", "annual", "one_off", "custom") and tags.

Example:

series = client.get_series_list()
print(series.shape)
print(series["category"].value_counts().head())

weather = client.get_series_list(category="Climate and Weather", include_volume=True)
weather.nlargest(5, "volume")[["ticker", "title", "volume"]]

get_series
#

โ†’ SeriesMethod page โ†’
client.get_series(series_ticker)

Gets one series.

Parameters:

  • series_ticker (str): Series ticker.

Returns:

  • pandas.Series: the same fields as a get_series_list row.

Example:

print(client.get_series("KXHIGHNY")[["title", "category", "frequency"]])
Output:
title        Highest temperature in NYC
category            Climate and Weather
frequency                         daily
Name: KXHIGHNY, dtype: object

get_series_ticker_for_market
#

client.get_series_ticker_for_market(ticker)

Looks up which series a market belongs to. get_candlesticks uses this when you don’t pass series_ticker.

Parameters:

  • ticker (str): Market ticker.

Returns:

  • str: the series ticker, e.g. "KXHIGHNY".

get_exchange_status
#

client.get_exchange_status()

Checks whether the exchange is open and trading.

Returns:

  • dict: includes exchange_active (bool), trading_active (bool) and exchange_estimated_resume_time (str or None).

Example:

status = client.get_exchange_status()
print(status["exchange_active"], status["trading_active"])
Output:
True True

Portfolio data
#

These methods need an authenticated client (see Authentication).

Calling a portfolio method without credentials raises KalshiAuthError before any request is sent.

get_balance
#

API keyโ†’ dictMethod page โ†’
client.get_balance()

Gets your account balance.

Returns:

  • dict:
KeyTypeDescription
balancefloatCash available, in dollars
portfolio_valuefloatCurrent value of your open positions, in dollars
updated_tspandas.TimestampWhen the balance was last updated (UTC)

Example:

client.get_balance()
Output (illustrative values):
{'balance': 123.45, 'portfolio_value': 50.0, 'updated_ts': Timestamp('2026-11-27 10:00:00+0000', tz='UTC')}

get_positions
#

โ˜… Most usedAPI keyโ†’ DataFrameMethod page โ†’
client.get_positions(*, ticker=None, event_ticker=None, settlement_status="unsettled",
                     count_filter=None, max_results=None)

Lists your positions, one row per market.

Parameters:

  • ticker (str, optional): Only this market.
  • event_ticker (str, optional): Only markets in this event.
  • settlement_status (str, optional): "unsettled" (default, i.e. open positions), "settled" or "all".
  • count_filter (str or list[str], optional): "position" and/or "total_traded". Leaves out rows where that value is zero. For example, count_filter="position" hides markets you’ve fully exited.
  • max_results (int, optional): Stop after this many rows.

Returns:

  • pandas.DataFrame: one row per market.
ColumnTypeDescription
tickerstrMarket ticker
positionfloatContracts held. Positive = YES, negative = NO.
market_exposurefloatCost basis of the current position, in dollars
realized_pnlfloatRealised profit or loss, in dollars
fees_paidfloatFees paid, in dollars
total_tradedfloatTotal dollars traded in this market
last_updated_tsdatetime64[ns, UTC]Last change to the position

Example:

pos = client.get_positions(count_filter="position")
pos["side"] = pos.position.gt(0).map({True: "YES", False: "NO"})
print(pos[["ticker", "side", "position", "market_exposure", "realized_pnl"]])

get_event_positions
#

API keyโ†’ DataFrameMethod page โ†’
client.get_event_positions(*, event_ticker=None, settlement_status="unsettled",
                           count_filter=None, max_results=None)

Lists your positions added up per event.

Parameters:

Returns:

  • pandas.DataFrame: one row per event, with columns event_ticker, total_cost, total_cost_shares, event_exposure, realized_pnl and fees_paid (all float dollars except the ticker and total_cost_shares, which is a contract count).

get_fills
#

โ˜… Most usedAPI keyโ†’ DataFrameMethod page โ†’
client.get_fills(*, ticker=None, order_id=None, start=None, end=None, max_results=None)

Lists your fills, newest first. A fill is one execution of one of your orders, and an order can fill in several pieces.

Parameters:

  • ticker (str or list[str], optional): Only these markets (up to 100).
  • order_id (str, optional): Only fills of this order.
  • start, end (time, optional): Only fills within this window.
  • max_results (int, optional): Stop after this many fills.

Returns:

  • pandas.DataFrame: one row per fill.
ColumnTypeDescription
fill_idstrUnique fill ID
order_idstrThe order that filled
tickerstrMarket ticker
created_timedatetime64[ns, UTC]When it filled
outcome_sidestr"yes" or "no"
book_sidestr"bid" (you bought) or "ask" (you sold)
countfloatContracts filled
yes_price, no_pricefloatFill price for each side, in dollars
is_takerboolTrue if your order took liquidity
fee_costfloatFee for this fill, in dollars

Example:

fills = client.get_fills(start="2026-11-01")
fills["notional"] = fills["count"] * fills.yes_price.where(fills.outcome_side == "yes", fills.no_price)
daily = fills.set_index("created_time").resample("D")[["notional", "fee_cost"]].sum()

get_orders
#

API keyโ†’ DataFrameMethod page โ†’
client.get_orders(*, ticker=None, event_ticker=None, status=None, start=None, end=None,
                  max_results=None)

Lists your orders, newest first.

Parameters:

  • ticker (str, optional): Only orders in this market.
  • event_ticker (str or list[str], optional): Only orders in these events (up to 100).
  • status (str, optional): "resting" (still open on the book), "canceled" or "executed".
  • start, end (time, optional): Only orders created within this window.
  • max_results (int, optional): Stop after this many orders.

Returns:

  • pandas.DataFrame: one row per order.
ColumnTypeDescription
order_idstrOrder ID
tickerstrMarket ticker
statusstrresting, canceled or executed
created_timedatetime64[ns, UTC]When the order was placed
outcome_side, book_sidestrWhich side, and buy (bid) or sell (ask)
typestrlimit or market
yes_price, no_pricefloatLimit price for each side
initial_count, fill_count, remaining_countfloatContracts ordered, filled and still open

Other fields include expiration_time, taker_fees, maker_fees and client_order_id.

Example:

open_orders = client.get_orders(status="resting")
open_orders[["ticker", "outcome_side", "yes_price", "remaining_count"]]
This module only reads data. It doesn’t place or cancel orders.

get_settlements
#

API keyโ†’ DataFrameMethod page โ†’
client.get_settlements(*, ticker=None, event_ticker=None, start=None, end=None,
                       max_results=None)

Lists markets you held when they settled, and what they paid out.

Parameters:

  • ticker (str, optional): Only this market.
  • event_ticker (str, optional): Only markets in this event.
  • start, end (time, optional): Only settlements within this window.
  • max_results (int, optional): Stop after this many settlements.

Returns:

  • pandas.DataFrame: one row per settled market.
ColumnTypeDescription
ticker, event_tickerstrMarket and event
settled_timedatetime64[ns, UTC]When it settled
market_resultstr"yes", "no" or "scalar"
yes_count, no_countfloatContracts you held on each side
yes_total_cost, no_total_costfloatWhat you paid for them, in dollars
revenuefloatPayout, in dollars (Kalshi sends cents; converted)
valuefloatSettlement value per contract, in dollars (converted from cents)
fee_costfloatFees, in dollars

Example (profit and loss per settled market):

s = client.get_settlements()
s["pnl"] = s.revenue - s.yes_total_cost - s.no_total_cost - s.fee_cost
print(s[["ticker", "market_result", "pnl"]].sort_values("pnl"))
print("Total P&L:", round(s.pnl.sum(), 2))

Utilities
#

These are also exported from stakepd.kalshi_data:

NameDescription
kd.to_unix_seconds(value, name="value")Converts any time argument to int Unix seconds. Returns None for None.
kd.load_private_key(private_key=None, private_key_path=None, password=None)Loads an RSA or Ed25519 PEM private key. Raises KalshiAuthError if it can’t.
kd.KalshiAuth(api_key_id, private_key)A requests authentication handler that adds Kalshi’s signature headers. Useful for calling endpoints the wrapper doesn’t cover, with plain requests.
kd.BASE_URLS{"prod": ..., "demo": ...}: the API base URLs.

Example:

import requests

auth = kd.KalshiAuth("a1b2c3d4-...", kd.load_private_key(private_key_path="~/.kalshi/key.pem"))
r = requests.get(kd.BASE_URLS["prod"] + "/portfolio/balance", auth=auth)

Errors
#

All exceptions inherit from kd.KalshiError, so except kd.KalshiError catches everything raised by this module.

ExceptionRaised when
kd.KalshiAuthErrorCredentials are missing, incomplete or unreadable, or a portfolio method is called on a client without credentials.
kd.KalshiAPIErrorKalshi returns an HTTP error, e.g. 404 for an unknown market or 401 for a bad key. Has .status_code, .code, .message, .details and .url.
ValueErrorAn argument is invalid, such as an unknown status, a bad interval, a millisecond timestamp, or max_results=0.

Rate-limit (429) and server (5xx) errors are retried automatically with exponential backoff, up to max_retries times, before a KalshiAPIError is raised.

try:
    m = client.get_market("NOT-A-REAL-TICKER")
except kd.KalshiAPIError as e:
    print(e.status_code, e.code, e.message)

Recipes
#

Implied probabilities and stakepd odds functions
#

Kalshi prices are implied probabilities, so they work directly with the rest of stakepd:

import stakepd as spd

m = client.get_markets(event_ticker="KXHIGHNY-26NOV27")
m = m[m.yes_ask > 0]
m["american"] = m.yes_ask.odds(odds_type="american")    # price โ†’ American odds
m["decimal"] = m.yes_ask.odds(odds_type="decimal")      # price โ†’ decimal odds

Overround of a mutually exclusive event
#

If exactly one bracket resolves YES, the YES asks should add up to about 1. Anything above 1 is the market’s overround, and devig gives the fair probabilities:

asks = m.set_index("yes_sub_title").yes_ask
print("Overround:", asks.overround())       # e.g. 0.03 = 3%
fair = asks.devig()                         # probabilities rescaled to sum to 1

Price history for every market in an event
#

markets = client.get_markets(event_ticker="KXHIGHNY-26NOV27")
closes = pd.DataFrame({
    row.yes_sub_title: client.get_candlesticks(row.ticker, start="2026-11-25", interval="1h",
                                               series_ticker="KXHIGHNY")["price_close"]
    for row in markets.itertuples()
}).ffill()
closes.plot(ylabel="P(YES)")

Scan for the most active markets right now
#

open_mkts = client.get_markets(status="open", mve_filter="exclude")
open_mkts["spread"] = open_mkts.yes_ask - open_mkts.yes_bid
top = open_mkts.nlargest(20, "volume_24h")[["ticker", "yes_sub_title", "yes_bid", "yes_ask", "spread", "volume_24h"]]

Calibration: how well do prices predict outcomes?
#

This recipe takes each settled market’s mid-price 12 hours before it closed and compares it with how often markets at that price actually resolved YES. In a well-calibrated market, contracts priced around 0.30 should win about 30% of the time.

settled = client.get_markets(status="settled", series_ticker="KXHIGHNY",
                             min_settled="2026-10-01", max_settled="2026-11-01")

def mid_before_close(row, hours=12):
    t = row.close_time - pd.Timedelta(hours=hours)
    c = client.get_candlesticks(row.ticker, start=t - pd.Timedelta(hours=1), end=t,
                                series_ticker="KXHIGHNY")
    return ((c.yes_bid_close + c.yes_ask_close) / 2).iloc[-1] if len(c) else float("nan")

settled["prob_12h"] = settled.apply(mid_before_close, axis=1)   # one request per market
settled["won"] = (settled.result == "yes").astype(int)
settled["bucket"] = pd.cut(settled.prob_12h, bins=[0, .1, .3, .5, .7, .9, 1])
settled.groupby("bucket", observed=True).won.agg(["mean", "count"])
Don’t use the previous_price column for this. On settled markets it’s usually already close to 0 or 1, because by then the outcome was known.

Save data for later
#

trades = client.get_trades("KXHIGHNY-26NOV27-B57.5")
trades.to_parquet("trades.parquet")          # keeps the dtypes, including UTC times
trades = pd.read_parquet("trades.parquet")

Limits and notes
#

Rate limitsKalshi limits requests per second according to your account tier. The client retries 429 responses with backoff. For bulk downloads (e.g. candles for hundreds of markets), pass series_ticker to get_candlesticks to avoid extra lookups.
Read-onlyThis module fetches data. It doesn't place, amend or cancel orders.
Archived dataKalshi moves very old markets, fills, orders and settlements to separate "historical" endpoints, which this module doesn't cover yet. Recent data is unaffected.
Order bookA snapshot at the moment of the request, bids only (see get_orderbook).
Combo marketsMulti-leg "combo" (multivariate) markets appear in get_markets by default. Use mve_filter="exclude" to leave them out.
API changesKalshi updates its API regularly. Fields Kalshi adds show up as new columns automatically. See Kalshi's changelog for removed or renamed fields.

Contact
#

For any enquiries related to ads, software bugs, or anything else, please email bhatwadekarenterprises@gmail.com.