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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ on:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:

jobs:
test:
Expand Down
37 changes: 37 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,43 @@

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

## 22.19.0 — 2026-12-02

Reconciles nightly spec drift (#594). Additive only. No breaking changes.
Synced OpenAPI 3.39.0 / AsyncAPI / perps / SCM specs.

### Added

- Perps FCM **`fcm.get_im_cap()`** / **`update_im_cap(*, im_cap=)`** /
**`delete_im_cap()`** (sync + async) — `GET`/`PUT`/`DELETE
/margin/fcm/im_cap`. Auth required. PUT/DELETE are never retried.
`GetFCMIMCapResponse.im_cap` and `current_im` are optional
`DollarDecimal` (wire names `im_cap` / `current_im`, no `_dollars`
suffix; both absent when unset or unavailable). PUT body is
`UpdateFCMIMCapRequest` (`extra="forbid"`); returns no body.
- Core **`incentive_programs.dlp_programs()`** (sync + async) —
`GET /dlp_programs`. Public. Returns `GetDlpProgramsResponse` with
`bidding_periods` and `incentivized_series` (null/missing lists parse
as `[]`).
- Core **`Settlement.value_dollars`** (`DollarDecimal | None`). `value`
(integer cents) is deprecated and kept.
- Klear **`ObligationEntry.obligation_type`** (`str | None`) and
**`CorporateActionPaymentDetail.withholding_fp`** /
**`withholding_rate_bps`** / **`withholding_reason`** (all optional so
older payloads still parse).
- WebSocket **`cover_market_lifecycle`** channel and
**`subscribe_cover_market_lifecycle()`**. Payload
`CoverMarketLifecycleMessage` (same msg shape as `market_lifecycle_v2`).
`market_lifecycle_v2` also carries **`milestone_updated`**
(`MilestoneUpdatedMessage`: `milestone_id`, `last_updated_ts_us`,
free-form `milestone` dict). AsyncAPI 16 → 17 channels. (Closes #594).

### Docs

- FCM account-level IM cap; DLP programs; `Settlement.value_dollars`;
Klear withholding / `obligation_type`; cover market lifecycle and
milestone-updated WS messages.

## 22.18.0 — 2026-12-01

Reconciles nightly spec drift (#592). Additive only. No breaking changes.
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ tests/

## API Reference

- 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)
- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.39.0, 146 operations; 145 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 (17 WebSocket channels; 14 typed `subscribe_*` + escape-hatch)
- Base URL: https://api.elections.kalshi.com/trade-api/v2
- Demo URL: https://demo-api.kalshi.co/trade-api/v2
- Auth: RSA-PSS / SHA256 / MGF1(SHA256) / salt_length=DIGEST_LENGTH / base64
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ 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.38.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch).
- **Full coverage** of the Kalshi REST API (145 mapped of 146 operations across 19 resources, OpenAPI v3.39.0) and WebSocket API (14 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.
Expand Down Expand Up @@ -171,16 +171,17 @@ async def main() -> None:
asyncio.run(main())
```

Available channels (13 typed + escape-hatch). Thirteen have dedicated
Available channels (14 typed + escape-hatch). Fourteen have dedicated
`subscribe_*` methods — `subscribe_ticker`, `subscribe_trade`,
`subscribe_orderbook_delta`, `subscribe_fill`, `subscribe_market_positions`,
`subscribe_user_orders`, `subscribe_order_group`,
`subscribe_market_lifecycle`, `subscribe_multivariate_lifecycle`,
`subscribe_cover_market_lifecycle`,
`subscribe_communications`, `subscribe_cfbenchmarks_value`,
`subscribe_cfbenchmarks_value_5hz`, `subscribe_ebattle_scores`. The
AsyncAPI-declared `control_frames`, `root`, and `pyth_value` channels are
reachable through the generic `subscribe(channel, ...)` escape hatch. See
[docs/websockets.md](docs/websockets.md#the-13-channels) for the full
[docs/websockets.md](docs/websockets.md#the-14-channels) for the full
channel table.

## Perps (margin) trading
Expand Down
6 changes: 3 additions & 3 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
A professional, spec-first Python SDK for the [Kalshi](https://kalshi.com) prediction
markets API.

- **Full REST coverage** — 144 mapped of 145 operations across 19 resources
(OpenAPI v3.38.0), every kwarg drift-tested against the spec.
- **Full REST coverage** — 145 mapped of 146 operations across 19 resources
(OpenAPI v3.39.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.
- **Funding + cost introspection** — `portfolio.deposits()`,
`portfolio.withdrawals()`, `portfolio.intra_exchange_transfers()`,
`account.endpoint_costs()`.
- **Full WebSocket coverage** — 13 typed channels with sequence-gap detection,
- **Full WebSocket coverage** — 14 typed channels with sequence-gap detection,
automatic reconnection (with resubscribe-window frame stashing for high-volume
channels), backpressure strategies, and an in-memory orderbook builder.
Async-only — access via `AsyncKalshiClient.ws`.
Expand Down
15 changes: 12 additions & 3 deletions docs/perps.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ async with AsyncPerpsClient.from_env(demo=True) as perps:
| `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()` (Predictions ↔ Perps; not available to FCM members or self-clearing members), `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(...)` |
| `fcm` | `create_subtrader(subtrader_suffix=..., require_category_cap=...)`; `risk_controls` / `update_risk_controls` / `delete_risk_controls`; `update_notional_risk_limit` / `delete_notional_risk_limit`; `get_im_cap` / `update_im_cap` / `delete_im_cap`; `transfer_position(...)` |

`markets.bulk_orderbooks(*, tickers)` fetches up to 100 margin orderbooks
in one call (`GET /margin/markets/orderbooks`). `tickers` is required
Expand Down Expand Up @@ -153,6 +153,12 @@ perps.fcm.risk_controls(subtrader_id="user_desk1", asset_class="Crypto")
# The exchange enforces the smaller of this value and the Kalshi-set limit.
perps.fcm.update_notional_risk_limit(notional_value_risk_limit=Decimal("5000.0000"))
perps.fcm.delete_notional_risk_limit()

# Account-level initial margin cap (PUT/DELETE are never retried).
# `im_cap` / `current_im` are omitted when unset or unavailable.
cap = perps.fcm.get_im_cap()
perps.fcm.update_im_cap(im_cap=Decimal("10000000.0000"))
perps.fcm.delete_im_cap()
```

`risk_controls()` also returns `notional_limits` (admin-set notional caps for
Expand Down Expand Up @@ -480,8 +486,11 @@ cash and split corporate-action payments already included in settlement PnL
for splits. Centicents fields on that model stay plain integers.
`payment_amount_fp` is the optional dollar-string counterpart of
`payment_amount_centicents` (separate attribute, not an alias).
`position_quantity_fp` and `post_position_quantity_fp` are fixed-point
contract counts. `corporate_action_payments` / `corporate_action_payments_all`
`withholding_fp`, `withholding_rate_bps`, and `withholding_reason` are
optional (omitted on older payloads). `position_quantity_fp` and
`post_position_quantity_fp` are fixed-point contract counts.
`ObligationEntry.obligation_type` is optional (`None` when the server
omits it). `corporate_action_payments` / `corporate_action_payments_all`
page the full set when `corporate_action_payments_truncated` is true (limit
max 1000):

Expand Down
19 changes: 19 additions & 0 deletions docs/resources/incentive-programs.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Public — no auth required.
|---|---|
| `list(...)` / `list_all(...)` | `GET /incentive_programs` |
| `list_schedules()` | `GET /incentive_schedules` |
| `dlp_programs()` | `GET /dlp_programs` |

## List active programs

Expand Down Expand Up @@ -73,6 +74,24 @@ them) when the schedule covers the whole series. `ends` is `None` when the sched
no end. `reward` is centi-cents, the same convention as
`IncentiveProgram.period_reward`.

## DLP programs

Public listing of the Designated Liquidity Provider program: programs taking
bids now, and programs whose DLPs are selected and whose incentive period
has not ended. No rates, makers, or quoting requirements. Public, no
pagination.

```python
resp = client.incentive_programs.dlp_programs()
for p in resp.bidding_periods:
print(p.id, p.title, p.target_dlps, p.closes_ts)
for p in resp.incentivized_series:
print(p.id, p.title, p.selected_dlps)
```

A missing or null `bidding_periods` / `incentivized_series` array parses as
`[]`.

## Reference

::: kalshi.resources.incentive_programs.IncentiveProgramsResource
Expand Down
6 changes: 5 additions & 1 deletion docs/resources/portfolio.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,17 @@ page = client.portfolio.settlements(
limit=200,
)
for s in page:
print(s.ticker, s.settled_at, s.market_result, s.revenue)
print(s.ticker, s.settled_at, s.market_result, s.revenue, s.value_dollars)

# Or:
for s in client.portfolio.settlements_all():
...
```

`value` is integer cents (deprecated). `value_dollars` is the exact
fixed-point payout of a single yes contract; omitted, like `value`, when
the market has no recorded settlement value.

Standard `Page[Settlement]` pagination — see [Pagination](../pagination.md).

## Fills
Expand Down
35 changes: 29 additions & 6 deletions docs/websockets.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# WebSocket

The SDK ships an async-only WebSocket client, `KalshiWebSocket`, that covers
the Kalshi market-data WebSocket surface (13 typed channels plus the generic
the Kalshi market-data WebSocket surface (14 typed channels plus the generic
escape hatch). It handles RSA-PSS auth on the upgrade handshake,
per-subscription sequence-gap detection, automatic reconnection with
re-subscription, and a configurable backpressure strategy on each per-channel
Expand Down Expand Up @@ -30,15 +30,16 @@ SDK's perspective on it.
on every delta.
- `on_state_change=` and `on_error=` hooks on the constructor for observability.

## The 13 channels
## The 14 channels

| SDK method | Wire channel | Message `type` field | Message class | Auth |
|---|---|---|---|---|
| `subscribe_ticker` | `ticker` | `ticker` | `TickerMessage` | public |
| `subscribe_trade` | `trade` | `trade` | `TradeMessage` | public |
| `subscribe_orderbook_delta` | `orderbook_delta` | `orderbook_snapshot` → `orderbook_delta` | `OrderbookSnapshotMessage` / `OrderbookDeltaMessage` | public |
| `subscribe_market_lifecycle` | `market_lifecycle_v2` | `market_lifecycle_v2` / `event_fee_update` | `MarketLifecycleMessage` / `EventFeeUpdateMessage` | public |
| `subscribe_market_lifecycle` | `market_lifecycle_v2` | `market_lifecycle_v2` / `event_fee_update` / `milestone_updated` | `MarketLifecycleMessage` / `EventFeeUpdateMessage` / `MilestoneUpdatedMessage` | public |
| `subscribe_multivariate_lifecycle` | `multivariate_market_lifecycle` | `multivariate_market_lifecycle` | `MultivariateLifecycleMessage` | public |
| `subscribe_cover_market_lifecycle` | `cover_market_lifecycle` | `cover_market_lifecycle` | `CoverMarketLifecycleMessage` | public |
| `subscribe_fill` | `fill` | `fill` | `FillMessage` | private |
| `subscribe_user_orders` | `user_orders` | `user_order` (singular) | `UserOrdersMessage` | private |
| `subscribe_market_positions` | `market_positions` | `market_position` (singular) | `MarketPositionsMessage` | private |
Expand All @@ -56,14 +57,17 @@ The standalone `batch_communications` channel was removed from AsyncAPI
`communications`. The SDK never shipped a typed
`subscribe_batch_communications` helper. AsyncAPI later added
`ebattle_scores` (SDK v22.11.0, 15 → 16 spec channels);
`batch_communications` remains gone.
`batch_communications` remains gone. AsyncAPI later added
`cover_market_lifecycle` (SDK v22.19.0, 16 → 17 spec channels) for KXRFQ
cover markets.

!!! warning "Migration (v3.1.0): `event_fee_update` rides `market_lifecycle_v2`"
Since the v3.20.0 spec sync (SDK v3.1.0) the `market_lifecycle_v2` channel
also emits `event_fee_update` frames (event-level fee override set or
cleared), so
`subscribe_market_lifecycle()` now yields
`MarketLifecycleMessage | EventFeeUpdateMessage`. **Existing consumers must
`MarketLifecycleMessage | EventFeeUpdateMessage | MilestoneUpdatedMessage`.
**Existing consumers must
discriminate on `.type` before touching payload fields** — an
`EventFeeUpdatePayload` has no `market_ticker`, so naive access raises
`AttributeError`:
Expand All @@ -72,6 +76,8 @@ The standalone `batch_communications` channel was removed from AsyncAPI
async for msg in session.subscribe_market_lifecycle():
if msg.type == "event_fee_update":
print(msg.msg.event_ticker, msg.msg.fee_type_override) # None when cleared
elif msg.type == "milestone_updated":
print(msg.msg.milestone_id, msg.msg.last_updated_ts_us)
else: # market_lifecycle_v2
print(msg.msg.market_ticker, msg.msg.event_type)
```
Expand All @@ -81,7 +87,24 @@ The standalone `batch_communications` channel was removed from AsyncAPI
[`EventFeeChange`](resources/events.md#event-fee-changes):
`EventFeeUpdatePayload` carries `event_ticker`, `fee_type_override`, and
`fee_multiplier_override` (the latter two `None` when the override is
cleared).
cleared). `milestone_updated` (SDK v22.19.0) is a third type on the same
channel: `MilestoneUpdatedPayload` carries `milestone_id`,
`last_updated_ts_us`, and a free-form `milestone` dict.

## Cover market lifecycle

`subscribe_cover_market_lifecycle()` streams lifecycle events for KXRFQ cover
markets (weather and concert cover markets created on request).
`market_lifecycle_v2` leaves those tickers out. `market_ticker` filters are
not supported. The inner payload has the same shape as
`MarketLifecycleMessage`.

```python
from kalshi.ws.models import CoverMarketLifecycleMessage

async for msg in session.subscribe_cover_market_lifecycle():
print(msg.msg.market_ticker, msg.msg.event_type)
```

Two channels carry monotonic `seq` numbers and have built-in sequence-gap
recovery: `orderbook_delta` (which delivers both snapshot and delta envelopes
Expand Down
8 changes: 7 additions & 1 deletion kalshi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@
DecreaseOrderV2Request,
DecreaseOrderV2Response,
Deposit,
DlpBiddingProgram,
DlpIncentivizedProgram,
EndpointTokenCost,
Event,
EventCandlesticks,
Expand Down Expand Up @@ -130,6 +132,7 @@
GetCommunicationsIDResponse,
GetConcertCancellationAvailabilityResponse,
GetConcertsResponse,
GetDlpProgramsResponse,
GetEventContractExitTriggersResponse,
GetEventLiveDataResponse,
GetFCMEventContractDailyCapResponse,
Expand Down Expand Up @@ -359,6 +362,8 @@
"DecreaseOrderV2Request",
"DecreaseOrderV2Response",
"Deposit",
"DlpBiddingProgram",
"DlpIncentivizedProgram",
"EndpointTokenCost",
"Event",
"EventCandlesticks",
Expand Down Expand Up @@ -396,6 +401,7 @@
"GetCommunicationsIDResponse",
"GetConcertCancellationAvailabilityResponse",
"GetConcertsResponse",
"GetDlpProgramsResponse",
"GetEventContractExitTriggersResponse",
"GetEventLiveDataResponse",
"GetFCMEventContractDailyCapResponse",
Expand Down Expand Up @@ -553,4 +559,4 @@
"Withdrawal",
]

__version__ = "22.18.0"
__version__ = "22.19.0"
30 changes: 30 additions & 0 deletions kalshi/_contract_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,18 @@ class ContractEntry:
sdk_model="kalshi.models.incentive_programs.GetIncentiveSchedulesResponse",
spec_schema="GetIncentiveSchedulesResponse",
),
ContractEntry(
sdk_model="kalshi.models.incentive_programs.DlpBiddingProgram",
spec_schema="DlpBiddingProgram",
),
ContractEntry(
sdk_model="kalshi.models.incentive_programs.DlpIncentivizedProgram",
spec_schema="DlpIncentivizedProgram",
),
ContractEntry(
sdk_model="kalshi.models.incentive_programs.GetDlpProgramsResponse",
spec_schema="GetDlpProgramsResponse",
),
ContractEntry(
sdk_model="kalshi.models.portfolio.TotalRestingOrderValue",
spec_schema="GetPortfolioRestingOrderTotalValueResponse",
Expand Down Expand Up @@ -829,6 +841,16 @@ class ContractEntry:
spec_schema="eventFeeUpdatePayload",
notes="New v3.20.0 message (#385); rides the market_lifecycle_v2 channel.",
),
ContractEntry(
sdk_model="kalshi.ws.models.milestone.MilestoneUpdatedPayload",
spec_schema="milestoneUpdatedPayload",
notes="New #594 message; rides the market_lifecycle_v2 channel.",
),
ContractEntry(
sdk_model="kalshi.ws.models.cover.CoverMarketLifecyclePayload",
spec_schema="coverMarketLifecyclePayload",
notes="Cover market lifecycle (#594); same msg shape as market_lifecycle_v2.",
),
ContractEntry(
sdk_model="kalshi.ws.models.market_positions.MarketPositionsPayload",
spec_schema="marketPositionPayload",
Expand Down Expand Up @@ -1161,6 +1183,14 @@ class ContractEntry:
sdk_model="kalshi.perps.models.fcm.UpdateFCMNotionalRiskLimitRequest",
spec_schema="UpdateFCMNotionalRiskLimitRequest",
),
ContractEntry(
sdk_model="kalshi.perps.models.fcm.GetFCMIMCapResponse",
spec_schema="GetFCMIMCapResponse",
),
ContractEntry(
sdk_model="kalshi.perps.models.fcm.UpdateFCMIMCapRequest",
spec_schema="UpdateFCMIMCapRequest",
),
ContractEntry(
sdk_model="kalshi.perps.models.fcm.CreateMarginFCMPositionTransferRequest",
spec_schema="CreateMarginFCMPositionTransferRequest",
Expand Down
6 changes: 6 additions & 0 deletions kalshi/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@
)
from kalshi.models.historical import HistoricalCutoff, MveHistoricalFilterLiteral, Trade
from kalshi.models.incentive_programs import (
DlpBiddingProgram,
DlpIncentivizedProgram,
GetDlpProgramsResponse,
GetIncentiveProgramsResponse,
GetIncentiveSchedulesResponse,
IncentiveProgram,
Expand Down Expand Up @@ -336,6 +339,8 @@
"DecreaseOrderV2Request",
"DecreaseOrderV2Response",
"Deposit",
"DlpBiddingProgram",
"DlpIncentivizedProgram",
"EndpointTokenCost",
"Event",
"EventCandlesticks",
Expand Down Expand Up @@ -369,6 +374,7 @@
"GetCommunicationsIDResponse",
"GetConcertCancellationAvailabilityResponse",
"GetConcertsResponse",
"GetDlpProgramsResponse",
"GetEventContractExitTriggersResponse",
"GetEventLiveDataResponse",
"GetFCMEventContractDailyCapResponse",
Expand Down
Loading
Loading