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
43 changes: 43 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,49 @@

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

## 22.18.0 — 2026-12-01

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

### Added

- Combo **`allowed_leg_misses`** (`int | None`, `>= 0`) on `RFQ`, `Market`,
`CreateQuoteRequest`, `CreateRFQBatchQuoteRequest`, WS `RfqCreatedPayload`,
and WS `RfqBatchCreatedPayload`. Present on combo RFQs/markets; omitted for
non-combo and for combos whose collection no longer exists — do not treat a
missing value on a combo as standard. Quote create kwargs
(`quotes.create` / `rfq_batches.quotes.create`, sync and async) forward it
and send it only when set. Required by the server when the RFQ's (or
batch's) `allowed_leg_misses` is greater than 0; otherwise rejected with
`allowed_leg_misses_required` / `allowed_leg_misses_mismatch`. `0` and
omitted mean the same.
- `IntraExchangeInstanceTransferStatusLiteral` gains `"failed"`
(`"pending"`, `"complete"`, `"failed"`).
- Quote-create 409 (`quote_timed_out`) may send **`X-Retry-After`** (integer
seconds). `_parse_retry_after` falls back to it when `Retry-After` is
absent; `KalshiConflictError.retry_after` is populated. POST is never
retried and 409 is not retryable.
- Perps **`MarginMarket.expiration_ts`** (`AwareDatetime | None`; omitted for
markets without an expiration) and optional
**`taker_long_volume_24h` / `taker_short_volume_24h`** (FixedPointCount,
`_fp` alias like `volume_24h`).

### Changed

- `MultivariateEventCollection.is_ordered` is a legacy field (always false);
kept as-is under deprecated fields.

### Docs

- Combo `allowed_leg_misses` on quotes, RFQs, and markets; quote 409
`X-Retry-After`.
- Perps intra-exchange transfer is between your Predictions and Perps
accounts; not available to FCM members or self-clearing members.
- Perps `settlement_mark_price` is a running estimate refreshed every few
seconds; applied 12:00 PM / 4:00 PM ET marks can differ (see
`GET /margin/settlement_prices`). Ticker WS `liquidation_mark_price` is
the last published mark used for margin and liquidation.

## 22.17.0 — 2026-11-26

Reconciles nightly spec drift (#590). Additive only. No breaking changes.
Expand Down
2 changes: 1 addition & 1 deletion docs/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ leave it `None`.
| `400` | `KalshiValidationError` | `.details` is populated from `body["details"]` or `body["errors"]` when present and dict-shaped. |
| `401` / `403` | `KalshiAuthError` | Bad signature, expired key, missing scope. |
| `404` | `KalshiNotFoundError` | Unknown ticker, missing order, etc. |
| `409` | `KalshiConflictError` | Duplicate `client_order_id` or other state conflict. |
| `409` | `KalshiConflictError` | Duplicate `client_order_id` or other state conflict. Quote create may send `X-Retry-After` (integer seconds) for a temporary `quote_timed_out` restriction; `.retry_after` is populated from `Retry-After` when present, else `X-Retry-After`. 409 is not retried. |
| `429` | `KalshiRateLimitError` | `.retry_after` parsed from the `Retry-After` header if it's a non-negative finite numeric (HTTP-date form falls back to computed backoff). |
| `5xx` | `KalshiServerError` | All server-side failures. |
| anything else | `KalshiError` | Catch-all, with `status_code` set. |
Expand Down
4 changes: 3 additions & 1 deletion docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,9 @@ Syncs the SDK to OpenAPI/AsyncAPI spec **3.25.0**. **No breaking changes.**

- Core OpenAPI lists `POST /portfolio/intra_exchange_instance_transfer`, still
marked **currently not available**. The core client does not expose it; use
`PerpsClient.transfers.transfer_instance()` on the margin product.
`PerpsClient.transfers.transfer_instance()` on the margin product
(Predictions ↔ Perps; not available to FCM members or self-clearing
members).

See the [changelog](https://github.com/TexasCoding/kalshi-python-sdk/blob/main/CHANGELOG.md)
for the full list.
Expand Down
12 changes: 11 additions & 1 deletion docs/perps.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ async with AsyncPerpsClient.from_env(demo=True) as perps:
| `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()`, `corporate_action_payment_history()` |
| `funding` | `rate_estimate()`, `historical_rates()`, `premium_index()`, `history()` |
| `transfers` | `transfer_instance()`, `create_subaccount()`, `transfer_subaccount()` |
| `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(...)` |

`markets.bulk_orderbooks(*, tickers)` fetches up to 100 margin orderbooks
Expand Down Expand Up @@ -226,13 +226,23 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id)
`"corporate_action"`, …). Empty means the market is not halted or
the reason has not been observed — do not read empty as proof the
market is live.
`MarginMarket.expiration_ts` (`AwareDatetime | None`) is omitted for
markets without an expiration. Optional `taker_long_volume_24h` /
`taker_short_volume_24h` are 24h taker-side contract counts typed like
`volume_24h` (`FixedPointCount | None`, `_fp` alias accepted).
- **Mark prices** (since the v3.21.0 spec sync) — `MarginMarket` carries three
optional reference-price objects: `settlement_mark_price`,
`liquidation_mark_price`, and `reference_price`, each a nested `TickerPrice`
(`TickerPrice | None`). `TickerPrice` is a new model with `price`
(`DollarDecimal`, a `FixedPointDollars` USD string) and `ts_ms` (the source
timestamp in epoch **milliseconds**, `int`). All three are absent from the spec
`required` list, so they are `None` when the upstream price is unavailable.
`settlement_mark_price` is a running estimate refreshed every few seconds;
the mark applied at 12:00 PM / 4:00 PM ET can differ — see
`GET /margin/settlement_prices`. On the ticker WS payload,
`liquidation_mark_price` is the last published mark used for margin and
liquidation; `reference_price` is the underlying reference scaled to one
contract, from the market's underlying price source, when available.
- **Exchange shard** (SDK v11.0.0) — `MarginMarket.exchange_index` (`int`) is
required; order groups may only reference markets that share their
`exchange_index`.
Expand Down
14 changes: 14 additions & 0 deletions docs/resources/communications.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ resp = client.communications.quotes.create(
yes_bid="0.60",
no_bid="0.40",
rest_remainder=False,
allowed_leg_misses=1, # required when the RFQ's allowed_leg_misses > 0
)

# 3) Wait for the counterparty to accept.
Expand Down Expand Up @@ -288,6 +289,19 @@ suffix), matching `quotes.create()`. Accept `min_bids` use Python name
no size of its own) or on each `CreateRFQBatchChild`. `rest_remainder`
must be false: a batch executes as one fill-or-kill.

`allowed_leg_misses` (`int | None`, optional, `>= 0`) is the combo rule
on `RFQ` and on `quotes.create` / `rfq_batches.quotes.create`. On an RFQ
it is present for every combo and omitted otherwise, except when the
combo's collection no longer exists — then the field is omitted and
quotes on it are refused. Do not treat a combo without it as standard.
On a quote it is required by the server when the RFQ's (or batch's)
`allowed_leg_misses` is greater than 0; otherwise the server rejects with
`allowed_leg_misses_required` / `allowed_leg_misses_mismatch`. `0` and
omitted mean the same. Sent only when set. Combo `Market` rows carry the
same optional field. A 409 on quote create may include `X-Retry-After`
(seconds) for a temporary `quote_timed_out` restriction; see
[Errors](../errors.md).

## Migrating from v2.x

| v2.x (deprecated) | v3.0.0 (canonical) |
Expand Down
6 changes: 6 additions & 0 deletions docs/resources/markets.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ recent trades.
| `flight_disruption_availability()` | `GET /flight_disruption_markets/availability` | no |
| `list_flights(*, carrier, flight_number, date)` | `GET /flight_disruption_markets/flights` | **yes** |

Combo markets (`mve_collection_ticker` set) may include
`allowed_leg_misses` (`int | None`): how many selected legs may lose while
the market still resolves Yes. `0` is a standard combo. Omitted for
non-combo markets and for combos whose collection no longer exists — do
not treat a missing value on a combo as standard.

!!! warning "Orderbook endpoints require auth"
`orderbook()` and `bulk_orderbooks()` raise `AuthRequiredError` on an
unauthenticated client. The rest of the market-data surface is public.
Expand Down
4 changes: 4 additions & 0 deletions docs/resources/multivariate.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ Each collection includes required `price_level_structure` (`str`) and
`price_ranges` (list of `{start, end, step}` dicts) describing the price
bands used for **new** markets created in the collection. Existing markets
may differ — use the minted `Market`'s fields for its current pricing.
`is_ordered` is a legacy field (always false) and is still returned.

Combo `Market` rows may include `allowed_leg_misses`; see
[Communications](communications.md) and [Markets](markets.md).

## Select legs

Expand Down
5 changes: 5 additions & 0 deletions docs/resources/portfolio.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,11 @@ print(t.status, t.created_ts)

`IntraExchangeInstanceTransfer.amount` is a fixed-point dollar
`DollarDecimal` (not the integer centicents used on the POST create body).
`status` is `"pending"`, `"complete"`, or `"failed"`.

`PerpsClient.transfers.transfer_instance()` moves funds between your
Predictions and Perps accounts; it is not available to FCM members or
self-clearing members.

## Target balance allocation

Expand Down
5 changes: 5 additions & 0 deletions docs/retries.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ The header is only honored when it parses as a non-negative finite number.
`Retry-After: 0` is honored (sleeps 0). HTTP-date form, `NaN`, negatives, and
non-numeric values fall back to the computed full-jitter backoff.

When `Retry-After` is absent, `X-Retry-After` is parsed the same way as
delta-seconds (quote create 409 `quote_timed_out`). `Retry-After` wins
when both are present. 409 is never retried; POST is never retried. The
hint is on `KalshiConflictError.retry_after` for the caller.

When retries are exhausted, the last `KalshiRateLimitError` is raised with
`.retry_after` populated from the header — so application-level retry logic
can see the hint.
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.17.0"
__version__ = "22.18.0"
79 changes: 49 additions & 30 deletions kalshi/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,11 @@ def _map_error(response: httpx.Response) -> KalshiError:
if status == 404:
return KalshiNotFoundError(message=message, status_code=status)
if status == 409:
return KalshiConflictError(message=message, status_code=status)
return KalshiConflictError(
message=message,
status_code=status,
retry_after=_parse_retry_after(response),
)
if status in (408, 429, 504) or status >= 500:
retry_after_val = _parse_retry_after(response)
if status == 429:
Expand All @@ -120,39 +124,54 @@ def _map_error(response: httpx.Response) -> KalshiError:
return KalshiError(message=message, status_code=status)


def _parse_retry_after(response: httpx.Response) -> float | None:
"""Parse RFC 7231 §7.1.3 Retry-After to seconds; ``None`` if absent/unparseable (#267, #322)."""
raw = response.headers.get("Retry-After")
if not raw:
return None
def _parse_delta_seconds(raw: str) -> float | None:
"""Parse a Retry-After / X-Retry-After delta-seconds value."""
try:
val = float(raw)
if not math.isfinite(val):
return None
if val < 0:
return 0.0
return val
except ValueError:
pass
# RFC 7231 §7.1.3: Retry-After may also be an HTTP-date.
try:
dt = email.utils.parsedate_to_datetime(raw)
except (TypeError, ValueError):
dt = None
if dt is None:
logger.debug(
"Retry-After %r is neither delta-seconds nor HTTP-date; "
"falling back to computed backoff",
raw,
)
return None
# RFC 5322 dates without a tz are interpreted as UTC by
# parsedate_to_datetime; ensure aware before subtracting.
if dt.tzinfo is None:
dt = dt.replace(tzinfo=UTC)
delta = (dt - datetime.now(tz=UTC)).total_seconds()
# Clamp negatives (date in the past) to 0 — retry immediately.
return max(0.0, delta)
if not math.isfinite(val):
return None
if val < 0:
return 0.0
return val


def _parse_retry_after(response: httpx.Response) -> float | None:
"""Parse RFC 7231 §7.1.3 Retry-After to seconds; ``None`` if absent/unparseable (#267, #322).

When ``Retry-After`` is absent, falls back to ``X-Retry-After`` using the
same delta-seconds parsing (quote 409 ``quote_timed_out``). A present but
unparseable ``Retry-After`` does not fall back.
"""
raw = response.headers.get("Retry-After")
if raw:
delta = _parse_delta_seconds(raw)
if delta is not None:
return delta
# RFC 7231 §7.1.3: Retry-After may also be an HTTP-date.
try:
dt = email.utils.parsedate_to_datetime(raw)
except (TypeError, ValueError):
dt = None
if dt is None:
logger.debug(
"Retry-After %r is neither delta-seconds nor HTTP-date; "
"falling back to computed backoff",
raw,
)
return None
# RFC 5322 dates without a tz are interpreted as UTC by
# parsedate_to_datetime; ensure aware before subtracting.
if dt.tzinfo is None:
dt = dt.replace(tzinfo=UTC)
http_delta = (dt - datetime.now(tz=UTC)).total_seconds()
# Clamp negatives (date in the past) to 0 — retry immediately.
return max(0.0, http_delta)
x_raw = response.headers.get("X-Retry-After")
if not x_raw:
return None
return _parse_delta_seconds(x_raw)


def _compute_backoff(attempt: int, config: KalshiConfig) -> float:
Expand Down
4 changes: 4 additions & 0 deletions kalshi/_contract_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,10 @@ class ContractEntry:
spec_schema="rfqCreatedPayload",
notes="Spec has mve_collection_ticker, mve_selected_legs not in SDK",
),
ContractEntry(
sdk_model="kalshi.ws.models.communications.RfqBatchCreatedPayload",
spec_schema="rfqBatchCreatedPayload",
),
ContractEntry(
sdk_model="kalshi.ws.models.communications.RfqDeletedPayload",
spec_schema="rfqDeletedPayload",
Expand Down
16 changes: 11 additions & 5 deletions kalshi/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ class KalshiError(Exception):
"""Base exception for all Kalshi SDK errors.

``retry_after`` carries the server's RFC 7231 §7.1.3 Retry-After hint
(parsed to seconds) when present. Populated for 408/429/503/504 and
other retryable 5xx responses; ``None`` otherwise. The transport
retry loop reads it via plain attribute access regardless of error
subclass (#322).
(parsed to seconds) when present, or ``X-Retry-After`` (delta-seconds)
when ``Retry-After`` is absent. Populated for 408/429/409/503/504 and
other retryable 5xx responses; ``None`` otherwise. 409 is not retryable
— the hint is for the caller. The transport retry loop reads it via
plain attribute access regardless of error subclass (#322).
"""

def __init__(
Expand Down Expand Up @@ -67,7 +68,12 @@ class KalshiRateLimitError(KalshiError):


class KalshiConflictError(KalshiError):
"""409 Conflict (e.g., duplicate ``client_order_id``)."""
"""409 Conflict (e.g., duplicate ``client_order_id``).

Quote create may send ``X-Retry-After`` (seconds) for a temporary
``quote_timed_out`` restriction; ``retry_after`` is populated then.
POST is never retried and 409 is not retryable.
"""


class KalshiTimeoutError(KalshiError):
Expand Down
11 changes: 11 additions & 0 deletions kalshi/models/communications.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ class RFQ(BaseModel):
)
mve_collection_ticker: str | None = None
mve_selected_legs: list[MveSelectedLeg] | None = None
# Combo-only. Omitted for non-combo and for combos whose collection no
# longer exists — do not treat a missing value on a combo as standard.
allowed_leg_misses: int | None = None
rest_remainder: bool | None = None
cancellation_reason: str | None = None
creator_user_id: str | None = None
Expand Down Expand Up @@ -219,6 +222,10 @@ class CreateQuoteRequest(BaseModel):
rest_remainder: bool
subaccount: StrictInt | None = Field(default=None, ge=0)
post_only: bool | None = None
# Required by the server when the RFQ's allowed_leg_misses > 0 (else
# rejected with allowed_leg_misses_required / allowed_leg_misses_mismatch);
# 0 and omitted mean the same.
allowed_leg_misses: int | None = Field(default=None, ge=0)

model_config = {"extra": "forbid"}

Expand Down Expand Up @@ -502,6 +509,10 @@ class CreateRFQBatchQuoteRequest(BaseModel):
rest_remainder: bool
post_only: bool | None = None
subaccount: StrictInt | None = Field(default=None, ge=0)
# Required by the server when the batch's allowed_leg_misses > 0 (else
# rejected with allowed_leg_misses_required / allowed_leg_misses_mismatch);
# 0 and omitted mean the same.
allowed_leg_misses: int | None = Field(default=None, ge=0)

model_config = {"extra": "forbid"}

Expand Down
3 changes: 3 additions & 0 deletions kalshi/models/markets.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ class Market(BaseModel):
is_provisional: bool | None = None
mve_collection_ticker: str | None = None
mve_selected_legs: list[dict[str, Any]] | None = None
# Combo-only. Omitted for non-combo and for combos whose collection no
# longer exists — do not treat a missing value on a combo as standard.
allowed_leg_misses: int | None = None
price_level_structure: str
price_ranges: NullableList[dict[str, Any]]
primary_participant_key: str | None = None
Expand Down
8 changes: 6 additions & 2 deletions kalshi/models/multivariate.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ class AssociatedEvent(BaseModel):


class MultivariateEventCollection(BaseModel):
"""A multivariate event collection (combo contract template)."""
"""A multivariate event collection (combo contract template).

``is_ordered`` is a legacy field. Always false.
"""

collection_ticker: str
series_ticker: str
Expand All @@ -46,8 +49,9 @@ class MultivariateEventCollection(BaseModel):
associated_event_tickers: NullableList[str]
is_single_market_per_event: bool
is_all_yes: bool
# Active fields
# Legacy field. Always false.
is_ordered: bool
# Active fields
size_min: int
size_max: int
functional_description: str
Expand Down
2 changes: 1 addition & 1 deletion kalshi/models/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ class Settlement(BaseModel):
ExchangeInstanceLiteral = Literal["event_contract", "margined"]
"""Exchange instance for intra-exchange fund movement (event vs margined)."""

IntraExchangeInstanceTransferStatusLiteral = Literal["pending", "complete"]
IntraExchangeInstanceTransferStatusLiteral = Literal["pending", "complete", "failed"]
"""Status of an intra-exchange instance transfer."""


Expand Down
Loading
Loading