Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,51 @@

All notable changes to kalshi-sdk will be documented in this file.

## 22.17.0 — 2026-11-26

Reconciles nightly spec drift (#590). Additive only. No breaking changes.

### Added

- Perps **`margin.corporate_action_payment_history(*, start_date, end_date,
ticker=, subaccount=)`** (sync + async) —
`GET /margin/corporate_action_payment_history`. Auth required. Returns
cash received or paid for corporate actions (cash dividends, special
dividends, cash spin-offs) over an inclusive UTC date range.
`start_date` / `end_date` are required YYYY-MM-DD (`datetime.date` or
`str`). Optional `ticker` and `subaccount` are sent only when set.
Stock split adjustments are not included. (Closes #590).
- Perps **`MarginMarketStatus` / `MarginMarketStatusLiteral`** gain
`"finalized"`. The spec renamed `"closed"` to `"finalized"`; `"closed"`
is kept for compatibility.
- Optional **`sort_by="event_ticker"`** on core `portfolio.positions` and
`positions_all` (sync and async). Orders event groups by ticker
ascending; omit for the default ordering. Sent only when set. Keep
filters and `sort_by` unchanged while paginating.
- Perps WebSocket **`exchange_status`** channel and
**`subscribe_exchange_status()`**. Payload
`MarginExchangeStatusMessage`: trading messages carry `trading_active`,
exchange status messages carry `exchange_active`. Trading is open
exchange-wide only while both are true.

### Changed

- Perps **`MarginMarketStatus`** spec enum is now `inactive` / `active` /
`finalized`. SDK still accepts `"closed"`.

### Docs

- Core `MarketPosition` / `EventPosition` `realized_pnl` and perps
`MarginPosition.unrealized_pnl` / `MarginFill.realized_pnl` are before
fees (`fees_paid` / `fees` reported separately).
- Perps subaccount numbers 64–4095 are a market's isolated subaccount.
`portfolio.positions(subaccount=0)` returns only primary cross-margin
positions; omit `subaccount` to include isolated.
- Perps `MarginMarket.bid` is `0` when none; `ask` is a placeholder
(`922337203685477.5807` or `0`) when none — check size first.
`contract_size` / `underlying_multiplier` meanings; order `price` is
per contract; exit-trigger `count` fractional rule.

## 22.16.0 — 2026-11-24

Reconciles nightly spec drift (#588). Additive only. No breaking changes.
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ tests/

## API Reference

- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.37.0, 145 operations; 144 mapped in the core SDK — `POST /portfolio/intra_exchange_instance_transfer` is implemented on `PerpsClient.transfers.transfer_instance` and left unimplemented on the core client)
- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.38.0, 145 operations; 144 mapped in the core SDK — `POST /portfolio/intra_exchange_instance_transfer` is implemented on `PerpsClient.transfers.transfer_instance` and left unimplemented on the core client)
- AsyncAPI spec: https://docs.kalshi.com/asyncapi.yaml (16 WebSocket channels; 13 typed `subscribe_*` + escape-hatch)
- Base URL: https://api.elections.kalshi.com/trade-api/v2
- Demo URL: https://demo-api.kalshi.co/trade-api/v2
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ A professional, spec-first Python SDK for the [Kalshi](https://kalshi.com) predi
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Type checked: mypy strict](https://img.shields.io/badge/mypy-strict-blue.svg)](https://mypy.readthedocs.io/)

- **Full coverage** of the Kalshi REST API (144 mapped of 145 operations across 19 resources, OpenAPI v3.37.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch).
- **Perps (margin) API**: standalone `PerpsClient` / `AsyncPerpsClient` + `PerpsWebSocket` for the perpetual-futures exchange (54 REST operations, 6 WS channels), plus a `KlearClient` for the Self-Clearing-Member "Klear" settlement API (26 of 27 operations). See [Perps (margin) trading](#perps-margin-trading).
- **Full coverage** of the Kalshi REST API (144 mapped of 145 operations across 19 resources, OpenAPI v3.38.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch).
- **Perps (margin) API**: standalone `PerpsClient` / `AsyncPerpsClient` + `PerpsWebSocket` for the perpetual-futures exchange (55 REST operations, 9 WS channels), plus a `KlearClient` for the Self-Clearing-Member "Klear" settlement API (26 of 27 operations). See [Perps (margin) trading](#perps-margin-trading).
- **FIX protocol**: an async-first FIX engine (FIXT.1.1 / FIX50SP2) for both products — order-entry, drop-copy, market-data, post-trade (prediction), and RFQ (prediction) sessions (plus order-group management over the order-entry session) with typed message models, sequence recovery, and order-book / settlement reassembly. `from kalshi import FixClient` / `MarginFixClient`. See [FIX protocol](#fix-protocol-low-latency-trading).
- **V2 event-market orders**: `create_v2` / `amend_v2` / `decrease_v2` / `cancel_v2` / `cancel_all_v2` plus batched variants on `/portfolio/events/orders/*` — the only order-write surface.
- **Funding & cost introspection**: `portfolio.deposits()`, `portfolio.withdrawals()`, `account.endpoint_costs()`.
Expand Down
4 changes: 2 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ A professional, spec-first Python SDK for the [Kalshi](https://kalshi.com) predi
markets API.

- **Full REST coverage** — 144 mapped of 145 operations across 19 resources
(OpenAPI v3.37.0), every kwarg drift-tested against the spec.
(OpenAPI v3.38.0), every kwarg drift-tested against the spec.
- **V2 event-market orders** — new `create_v2` / `amend_v2` / `decrease_v2` /
`cancel_v2` / `cancel_all_v2` family on `/portfolio/events/orders/*`. Legacy `/portfolio/orders`
keeps working; deprecation no earlier than May 6, 2026.
Expand All @@ -16,7 +16,7 @@ markets API.
channels), backpressure strategies, and an in-memory orderbook builder.
Async-only — access via `AsyncKalshiClient.ws`.
- **Perps (margin) API** — standalone `PerpsClient` / `AsyncPerpsClient` +
`PerpsWebSocket` for the perpetual-futures exchange (54 REST operations, 6 WS
`PerpsWebSocket` for the perpetual-futures exchange (55 REST operations, 9 WS
channels), and a `KlearClient` for the Self-Clearing-Member settlement API
(26 of 27 operations, Bearer token auth). See [Perps](perps.md).
- **FIX protocol** — a hand-rolled, async-first FIX engine (FIXT.1.1 / FIX50SP2)
Expand Down
70 changes: 58 additions & 12 deletions docs/perps.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ async with AsyncPerpsClient.from_env(demo=True) as perps:
| `orders` | `create()`, `get()`, `list()` / `list_all()`, `cancel()`, `cancel_all()`, `decrease()`, `amend()` |
| `order_groups` | `list()`, `get()`, `create()`, `delete()`, `reset()`, `trigger()`, `update_limit()` |
| `portfolio` | `positions()`, `fills()` / `fills_all()`, `trades()` / `trades_all()`, cross/isolated exit triggers |
| `margin` | `balance()`, `risk()`, `notional_risk_limit()`, `fee_tiers()`, `fee_tier_rates()`, `api_limits()`, `corporate_actions()` |
| `margin` | `balance()`, `risk()`, `notional_risk_limit()`, `fee_tiers()`, `fee_tier_rates()`, `api_limits()`, `corporate_actions()`, `corporate_action_payment_history()` |
| `funding` | `rate_estimate()`, `historical_rates()`, `premium_index()`, `history()` |
| `transfers` | `transfer_instance()`, `create_subaccount()`, `transfer_subaccount()` |
| `fcm` | `create_subtrader(subtrader_suffix=..., require_category_cap=...)`; `risk_controls` / `update_risk_controls` / `delete_risk_controls`; `update_notional_risk_limit` / `delete_notional_risk_limit`; `transfer_position(...)` |
Expand Down Expand Up @@ -94,6 +94,7 @@ Empty cron arrays mean continuous trading except for
`start` on `MarginHolidayWindow` (`until` is the exclusive end).

The margin order side is `bid` / `ask` (not the prediction API's `yes` / `no`).
Order `price` is per contract, not per unit of the underlying.
Orders create/cancel/decrease/amend are POSTs/DELETEs and are **never retried**.
`orders.amend(..., expiration_time=)` is int64 Unix seconds: omit it to keep
the current expiry, or pass `0` to clear it (good-till-canceled).
Expand All @@ -106,9 +107,12 @@ stable exchange market UUID. It may be supplied with `ticker` (ticker takes
precedence when both are set). Omit so the key is not sent.
`orders.create(..., subaccount=)` is optional (0 = primary). Omit so the
key is not sent.
`portfolio.fills()` / `portfolio.positions()` omit `subaccount` to return
rows across all subaccounts (subaccount-restricted API keys still only
see their locked subaccount). Pass `subaccount=0` for the primary.
`portfolio.fills()` omit `subaccount` to return rows across all
subaccounts (subaccount-restricted API keys still only see their locked
subaccount). Pass `subaccount=0` for the primary. `portfolio.positions()`
with `subaccount=0` returns only the primary account's cross-margin
positions; omit `subaccount` to include isolated positions held in a
market's isolated subaccount (64–4095).
`portfolio.trades()` / `trades_all()` take an optional `ticker`; omit it
to retrieve public trades across all margin markets. Optional
`is_block_trade` filters by block / non-block: omit for all trades,
Expand Down Expand Up @@ -160,7 +164,10 @@ the same subtrader). Each `FCMSubtraderRiskControls` row includes required

Exit triggers (stop-loss / take-profit / trailing) sit on a position slot.
Bracket `stop_loss_price` / `take_profit_price` must be strictly positive when
supplied; the client rejects zero and negative values.
supplied; the client rejects zero and negative values. Optional `count` is
the contracts the trigger closes when it fires; omit it to cover the whole
position. If supplied, it must be a whole number of contracts, or a multiple
of `0.01` on a market whose `fractional_trading_enabled` is true.

```python
from decimal import Decimal
Expand Down Expand Up @@ -199,7 +206,14 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id)
config / price data is unavailable. `MarginMarket.bid_size` / `ask_size`
(`FixedPointCount | None`) are the resting size at the best bid/ask
(`bid_size_fp` / `ask_size_fp` on the wire); omitted when market stats are
unavailable. `MarginMarket.funding_deadband` / `funding_cap`
unavailable. `MarginMarket.bid` is `0.0000` when there is no bid, so check
`bid_size` first. `MarginMarket.ask` is a placeholder when there is no
ask (`922337203685477.5807` or `0.0000`), so check `ask_size` first.
`MarginMarket.contract_size` is the size of one contract in the market's
underlying units; `underlying_multiplier` is how many of the underlying
asset make up one underlying unit. Prices are per contract and track the
underlying × `underlying_multiplier` × `contract_size`.
`MarginMarket.funding_deadband` / `funding_cap`
(`MultiplierDecimal`) and `funding_limit_unit` (`"percentage"` /
`"dollar"`) are required; they are the funding limits configured at
market creation, expressed in `funding_limit_unit`.
Expand Down Expand Up @@ -230,14 +244,18 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id)
null while open.
- **Subaccounts** (since the v3.21.0 spec sync) — `MarginPosition` (the
`portfolio.positions()` rows) carries a **required** `subaccount` (`int`)
identifying which subaccount holds the position. `subaccount_type`
identifying which subaccount holds the position (0 for primary, 1–63 for
numbered subaccounts, 64–4095 for a market's isolated subaccount).
`subaccount_type`
(`"cross"` / `"isolated"` / `"auto_rebalance"` / `"managed_isolated"` /
`"swaps"`, or `None` when the key is absent) is optional on `MarginPosition`,
`MarginSubaccountBalance`, `MarginRiskPosition`, and
`MarginFundingHistoryEntry`. `managed_isolated` uses the same subaccount
number as the market's isolated subaccount. `swaps` is a cross-margined
swaps wallet whose subaccount number is its swaps code. The spec marks it
required; the SDK keeps it optional so older payloads still parse.
`MarginPosition.unrealized_pnl` and `MarginFill.realized_pnl` are before
fees (`fees` is reported separately).
- **Portfolio hedging** (since the v3.23.0 spec sync) — `MarginPosition` and
`MarginRiskPosition` carry a **required** `is_portfolio` (`bool`), `True` when
the position is hedged within a portfolio so its margin is computed at the
Expand Down Expand Up @@ -299,6 +317,28 @@ for action in notices.corporate_actions:
print(action.cash.cash_per_contract, action.cash.ex_date)
```

`perps.margin.corporate_action_payment_history(*, start_date, end_date)`
(`GET /margin/corporate_action_payment_history`) returns cash received or
paid for corporate actions (cash dividends, special dividends, and cash
spin-offs) over an inclusive UTC date range. Auth required. `start_date`
and `end_date` are required YYYY-MM-DD (`datetime.date` or `str`). Optional
`ticker` filters to one market; omit for all markets. Optional
`subaccount`; omit for all subaccounts. Stock split adjustments are not
included. `payment_amount` is gross dollars before withholding (positive =
received, negative = paid).

```python
from datetime import date

history = perps.margin.corporate_action_payment_history(
start_date=date(2026, 10, 1),
end_date=date(2026, 10, 31),
ticker="AAPL-PERP",
)
for row in history.payment_history:
print(row.corporate_action_id, row.payment_amount, row.withholding_amount)
```

## WebSocket streaming

```python
Expand All @@ -312,12 +352,13 @@ async with ws.connect() as session:
print(msg.msg.funding_rate.rate, msg.msg.funding_rate.next_funding_time_ms)
```

Eight data channels — `orderbook_delta` (snapshot + delta, sequenced), `ticker`,
Nine data channels — `orderbook_delta` (snapshot + delta, sequenced), `ticker`,
`trade`, `fill`, `user_orders`, `order_group_updates`, `corporate_actions`,
`market_lifecycle_v2`. The connection, sequence-gap detection, reconnect, and
backpressure machinery are reused from the event-contract WS stack (see
[WebSocket](websockets.md)); the perps orderbook is `bid` / `ask`. The
prediction-only channels (`market_positions`, `multivariate*`, `communications`,
`market_lifecycle_v2`, `exchange_status`. The connection, sequence-gap
detection, reconnect, and backpressure machinery are reused from the
event-contract WS stack (see [WebSocket](websockets.md)); the perps
orderbook is `bid` / `ask`. The prediction-only channels
(`market_positions`, `multivariate*`, `communications`,
`cfbenchmarks_value`) have no perps counterpart. `corporate_actions` streams
applied split / final-settlement / ticker-change notices (cash actions are
REST-only); subscribe with `session.subscribe(channel="corporate_actions")`.
Expand All @@ -327,6 +368,11 @@ activation and deactivation of every margin market (`event_type` is
`activated` or `deactivated`). `is_deactivated` is true when trading is
paused because the market is halted or outside its trading hours. Ticker
filters are not supported on that channel.
`subscribe_exchange_status()` yields `MarginExchangeStatusMessage` when
trading is paused or resumed exchange-wide, or when the exchange status
changes. Trading messages carry `trading_active`; exchange status messages
carry `exchange_active`. Trading is open exchange-wide only while both are
true. Per-market halts ride `market_lifecycle_v2`.

## FCM position transfer

Expand Down
10 changes: 8 additions & 2 deletions docs/resources/portfolio.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Auth required throughout.
| Method | Endpoint |
|---|---|
| `balance(*, subaccount=None, exchange_index=None)` | `GET /portfolio/balance` |
| `positions(*, ..., exchange_index=None)` | `GET /portfolio/positions` |
| `positions(*, ..., exchange_index=None, sort_by=None)` | `GET /portfolio/positions` |
| `settlements(...)` / `settlements_all(...)` | `GET /portfolio/settlements` |
| `fills(...)` / `fills_all(..., exchange_index=None)` | `GET /portfolio/fills` |
| `total_resting_order_value()` | `GET /portfolio/summary/total_resting_order_value` (FCM only) |
Expand Down Expand Up @@ -76,6 +76,7 @@ resp = client.portfolio.positions(
settlement_status="unsettled", # "unsettled" (server default) | "settled" | "all"
ticker="KXPRES-24-DJT",
event_ticker="KXPRES-24",
sort_by="event_ticker", # order event groups by ticker; omit for default
)
for mp in resp.market_positions:
print(mp.ticker, mp.position, mp.realized_pnl)
Expand Down Expand Up @@ -116,6 +117,10 @@ contracts, including closed markets awaiting determination) or
`"total_traded"` (any contracts traded, including fully exited positions).
Omit it for no count filter.

`sort_by="event_ticker"` orders event groups by ticker ascending. Omit it
for the default ordering. Keep filters and `sort_by` unchanged while
paginating with `cursor`.

`settlement_status` (`SettlementStatusLiteral`: `"unsettled"`, `"settled"`,
`"all"`) filters settlement state, not trading status. Unsettled (the
server default) includes closed markets awaiting determination or
Expand Down Expand Up @@ -305,7 +310,8 @@ are unaffected; constructors/fixtures must pass it.
wire-format aliases — on the wire you see `total_traded_dollars`,
`market_exposure_dollars`, `realized_pnl_dollars`, `fees_paid_dollars`,
`position_fp`. The SDK normalizes to short names returning `Decimal`.
`realized_pnl` is signed. Optional `netting_enabled` (`bool | None`) reports
`realized_pnl` is signed, before fees (`fees_paid` is reported separately).
Optional `netting_enabled` (`bool | None`) reports
whether netting applies to the position's event (`None` when the server
omits the key).

Expand Down
2 changes: 1 addition & 1 deletion kalshi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,4 +553,4 @@
"Withdrawal",
]

__version__ = "22.16.0"
__version__ = "22.17.0"
8 changes: 8 additions & 0 deletions kalshi/_contract_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -1059,6 +1059,14 @@ class ContractEntry:
sdk_model="kalshi.perps.models.margin_account.MarginCorporateAction",
spec_schema="MarginCorporateAction",
),
ContractEntry(
sdk_model="kalshi.perps.models.margin_account.GetMarginCorporateActionPaymentHistoryResponse",
spec_schema="GetMarginCorporateActionPaymentHistoryResponse",
),
ContractEntry(
sdk_model="kalshi.perps.models.margin_account.MarginCorporateActionPaymentHistoryEntry",
spec_schema="MarginCorporateActionPaymentHistoryEntry",
),
ContractEntry(
sdk_model="kalshi.perps.models.margin_account.MarginCorporateActionCashTerms",
spec_schema="MarginCorporateActionCashTerms",
Expand Down
2 changes: 2 additions & 0 deletions kalshi/models/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ class MarketPosition(BaseModel):
market_exposure: DollarDecimal | None = Field(
validation_alias=AliasChoices("market_exposure_dollars", "market_exposure"),
)
# Locked-in PnL in dollars, before fees. Fees are in ``fees_paid``.
realized_pnl: DollarDecimal | None = Field(
validation_alias=AliasChoices("realized_pnl_dollars", "realized_pnl"),
)
Expand Down Expand Up @@ -125,6 +126,7 @@ class EventPosition(BaseModel):
event_exposure: DollarDecimal | None = Field(
validation_alias=AliasChoices("event_exposure_dollars", "event_exposure"),
)
# Locked-in PnL in dollars, before fees. Fees are in ``fees_paid``.
realized_pnl: DollarDecimal | None = Field(
validation_alias=AliasChoices("realized_pnl_dollars", "realized_pnl"),
)
Expand Down
Loading
Loading