diff --git a/CHANGELOG.md b/CHANGELOG.md index 92c7af8..02fdf16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,33 @@ All notable changes to kalshi-sdk will be documented in this file. +## 22.13.0 — 2026-11-12 + +Reconciles spec drift (#580): incentive schedules, incentive-program +series/event filters, optional perps `settled_funds`, and new perps WS +`lastUpdateReason` values. Additive only. No breaking changes. + +### Added + +- **`incentive_programs.list_schedules()`** (sync and async) — + `GET /incentive_schedules`, 200 list of `IncentiveSchedule`. Public. + Recurring incentive terms for a series, or for one event of a series. + No pagination. `event_ticker` / `event_title` are empty (or `None`) when + the schedule covers the whole series; `ends` is `None` when it has no end. + `reward` is int64 centi-cents (same convention as `period_reward`). +- Optional **`series_ticker`** / **`event_ticker`** query filters on + `incentive_programs.list` / `list_all`, and matching optional fields on + `IncentiveProgram`. A perpetual's incentives belong to no event. + (Closes #580). + +### Changed + +- Perps **`GetMarginBalanceResponse.settled_funds`** is optional + (`DollarDecimal | None`). Omitted for subaccount-restricted API keys. +- Perps WS **`PerpsLastUpdateReason`** gains `"CloseCancel"`, + `"HaltCancel"`, and `"SettlementBoundsCancel"` (spec order). REST + `LastUpdateReason` is unchanged. + ## 22.12.0 — 2026-11-11 Adds on-request weather point markets (#578) against OpenAPI v3.36.0. diff --git a/CLAUDE.md b/CLAUDE.md index 13e7e90..becfe3b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -122,7 +122,7 @@ tests/ ## API Reference -- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.36.0, 137 operations; 136 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.36.0, 138 operations; 137 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 diff --git a/README.md b/README.md index 575215c..a2d5789 100644 --- a/README.md +++ b/README.md @@ -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 (136 mapped of 137 operations across 19 resources, OpenAPI v3.36.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch). +- **Full coverage** of the Kalshi REST API (137 mapped of 138 operations across 19 resources, OpenAPI v3.36.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). - **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. diff --git a/docs/index.md b/docs/index.md index 66a7a1b..3cb7d11 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,7 +3,7 @@ A professional, spec-first Python SDK for the [Kalshi](https://kalshi.com) prediction markets API. -- **Full REST coverage** — 136 mapped of 137 operations across 19 resources +- **Full REST coverage** — 137 mapped of 138 operations across 19 resources (OpenAPI v3.36.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` diff --git a/docs/resources/incentive-programs.md b/docs/resources/incentive-programs.md index a013964..473da42 100644 --- a/docs/resources/incentive-programs.md +++ b/docs/resources/incentive-programs.md @@ -11,6 +11,7 @@ Public — no auth required. | Method | Endpoint | |---|---| | `list(...)` / `list_all(...)` | `GET /incentive_programs` | +| `list_schedules()` | `GET /incentive_schedules` | ## List active programs @@ -19,6 +20,8 @@ page = client.incentive_programs.list( status="active", # IncentiveProgramStatusLiteral incentive_type="liquidity", # IncentiveProgramTypeLiteral — spec "type" incentive_description="Q2 maker", # new in v2.1.0 — exact-match filter + series_ticker="KXHIGHNY", # optional — one series' incentives + event_ticker="KXHIGHNY-24", # optional — one event; omit for a perpetual limit=100, ) for p in page: @@ -27,6 +30,8 @@ for p in page: `incentive_description` (added in v2.1.0) is an exact-string filter on the program's description — useful when multiple programs share a status/type. +`series_ticker` and `event_ticker` (added in v22.13.0) restrict the list to +one series or one event. A perpetual's incentives belong to no event. Use `list_all` to walk every program: @@ -51,6 +56,23 @@ for p in client.incentive_programs.list_all(status="active"): `"closed"`, and additional server-side categories. - `IncentiveProgramTypeLiteral`: `"all"`, `"liquidity"`, `"volume"`. +## Incentive schedules + +Recurring terms for what each market of a series — or of one event — can +expect to earn window after window. Public, no pagination. A schedule is +anticipated unless `all_markets` is true. + +```python +schedules = client.incentive_programs.list_schedules() +for s in schedules: + print(s.series_ticker, s.incentive_type, s.reward, s.window_days) +``` + +`event_ticker` / `event_title` are empty (or `None` if the server omits +them) when the schedule covers the whole series. `ends` is `None` when the schedule has +no end. `reward` is centi-cents, the same convention as +`IncentiveProgram.period_reward`. + ## Reference ::: kalshi.resources.incentive_programs.IncentiveProgramsResource diff --git a/kalshi/__init__.py b/kalshi/__init__.py index 16c76cb..86ba4dc 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -124,6 +124,7 @@ GetFiltersBySportsResponse, GetGameStatsResponse, GetIncentiveProgramsResponse, + GetIncentiveSchedulesResponse, GetLiveDataResponse, GetLiveDatasResponse, GetMilestoneResponse, @@ -150,6 +151,7 @@ IncentiveProgram, IncentiveProgramStatusLiteral, IncentiveProgramTypeLiteral, + IncentiveSchedule, IndexedBalance, IntraExchangeInstanceTransfer, IntraExchangeInstanceTransferStatusLiteral, @@ -371,6 +373,7 @@ "GetFiltersBySportsResponse", "GetGameStatsResponse", "GetIncentiveProgramsResponse", + "GetIncentiveSchedulesResponse", "GetLiveDataResponse", "GetLiveDatasResponse", "GetMilestoneResponse", @@ -397,6 +400,7 @@ "IncentiveProgram", "IncentiveProgramStatusLiteral", "IncentiveProgramTypeLiteral", + "IncentiveSchedule", "IndexedBalance", "IntraExchangeInstanceTransfer", "IntraExchangeInstanceTransferStatusLiteral", @@ -515,4 +519,4 @@ "Withdrawal", ] -__version__ = "22.12.0" +__version__ = "22.13.0" diff --git a/kalshi/_contract_map.py b/kalshi/_contract_map.py index 2da6b78..9db7354 100644 --- a/kalshi/_contract_map.py +++ b/kalshi/_contract_map.py @@ -429,6 +429,15 @@ class ContractEntry: spec_schema="IncentiveProgram", notes="period_reward is int centi-cents; target_size_fp DollarDecimal", ), + ContractEntry( + sdk_model="kalshi.models.incentive_programs.IncentiveSchedule", + spec_schema="IncentiveSchedule", + notes="reward is int centi-cents; event_ticker/event_title optional (server omits empties)", + ), + ContractEntry( + sdk_model="kalshi.models.incentive_programs.GetIncentiveSchedulesResponse", + spec_schema="GetIncentiveSchedulesResponse", + ), ContractEntry( sdk_model="kalshi.models.portfolio.TotalRestingOrderValue", spec_schema="GetPortfolioRestingOrderTotalValueResponse", diff --git a/kalshi/models/__init__.py b/kalshi/models/__init__.py index 16b29f3..3ebea1f 100644 --- a/kalshi/models/__init__.py +++ b/kalshi/models/__init__.py @@ -98,9 +98,11 @@ from kalshi.models.historical import HistoricalCutoff, MveHistoricalFilterLiteral, Trade from kalshi.models.incentive_programs import ( GetIncentiveProgramsResponse, + GetIncentiveSchedulesResponse, IncentiveProgram, IncentiveProgramStatusLiteral, IncentiveProgramTypeLiteral, + IncentiveSchedule, ) from kalshi.models.live_data import ( EventLiveData, @@ -344,6 +346,7 @@ "GetFiltersBySportsResponse", "GetGameStatsResponse", "GetIncentiveProgramsResponse", + "GetIncentiveSchedulesResponse", "GetLiveDataResponse", "GetLiveDatasResponse", "GetMilestoneResponse", @@ -370,6 +373,7 @@ "IncentiveProgram", "IncentiveProgramStatusLiteral", "IncentiveProgramTypeLiteral", + "IncentiveSchedule", "IndexedBalance", "IntraExchangeInstanceTransfer", "IntraExchangeInstanceTransferStatusLiteral", diff --git a/kalshi/models/incentive_programs.py b/kalshi/models/incentive_programs.py index 7820ba2..3938d67 100644 --- a/kalshi/models/incentive_programs.py +++ b/kalshi/models/incentive_programs.py @@ -27,6 +27,8 @@ class IncentiveProgram(BaseModel): id: str market_id: str market_ticker: str + series_ticker: str | None = None + event_ticker: str | None = None incentive_type: str # "liquidity" | "volume" start_date: AwareDatetime end_date: AwareDatetime @@ -54,3 +56,37 @@ class GetIncentiveProgramsResponse(BaseModel): next_cursor: str | None = None model_config = {"extra": "allow"} + + +class IncentiveSchedule(BaseModel): + """Recurring incentive terms for a series, or for one event of a series.""" + + series_ticker: str + series_title: str + series_category: str + # Spec-required but empty when the schedule covers the whole series; + # the server may omit empties. + event_ticker: str | None = None + event_title: str | None = None + incentive_type: str # "liquidity" | "volume" + source: str + # Spec: integer (int64), centi-cents. Same convention as period_reward. + reward: int + window_days: int + discount_factor_bps: int | None = None + target_size_fp: FixedPointCount | None = None + ends: AwareDatetime | None = None + description: str + all_markets: bool + posted_ts: AwareDatetime + updated_ts: AwareDatetime + + model_config = {"extra": "allow"} + + +class GetIncentiveSchedulesResponse(BaseModel): + """Response for GET /incentive_schedules.""" + + schedules: NullableList[IncentiveSchedule] = [] + + model_config = {"extra": "allow"} diff --git a/kalshi/perps/models/margin_account.py b/kalshi/perps/models/margin_account.py index f40fd43..e12f2cd 100644 --- a/kalshi/perps/models/margin_account.py +++ b/kalshi/perps/models/margin_account.py @@ -55,7 +55,8 @@ class GetMarginBalanceResponse(BaseModel): model_config = ConfigDict(extra="allow") subaccount_balances: NullableList[MarginSubaccountBalance] - settled_funds: DollarDecimal + # Omitted for subaccount-restricted API keys. + settled_funds: DollarDecimal | None = None class MarginRiskPosition(BaseModel): diff --git a/kalshi/perps/ws/models/_common.py b/kalshi/perps/ws/models/_common.py index b7645c2..5a07818 100644 --- a/kalshi/perps/ws/models/_common.py +++ b/kalshi/perps/ws/models/_common.py @@ -35,9 +35,12 @@ "MarginCancel", "SelfTradeCancel", "ExpiryCancel", + "CloseCancel", + "HaltCancel", "Trade", "PostOnlyCrossCancel", "ReduceOnlyCancel", + "SettlementBoundsCancel", ] # Spec ``orderGroupUpdatesPayload.msg.event_type`` enum. diff --git a/kalshi/resources/incentive_programs.py b/kalshi/resources/incentive_programs.py index da8a90d..8410e70 100644 --- a/kalshi/resources/incentive_programs.py +++ b/kalshi/resources/incentive_programs.py @@ -7,13 +7,16 @@ from __future__ import annotations +import builtins from collections.abc import AsyncIterator, Iterator from kalshi.models.common import Page from kalshi.models.incentive_programs import ( + GetIncentiveSchedulesResponse, IncentiveProgram, IncentiveProgramStatusLiteral, IncentiveProgramTypeLiteral, + IncentiveSchedule, ) from kalshi.resources._base import ( AsyncResource, @@ -37,6 +40,8 @@ def list( status: IncentiveProgramStatusLiteral | None = None, incentive_type: IncentiveProgramTypeLiteral | None = None, incentive_description: str | None = None, + series_ticker: str | None = None, + event_ticker: str | None = None, limit: int | None = None, cursor: str | None = None, extra_headers: dict[str, str] | None = None, @@ -46,6 +51,8 @@ def list( status=status, type=incentive_type, incentive_description=incentive_description, + series_ticker=series_ticker, + event_ticker=event_ticker, limit=limit, cursor=cursor, ) @@ -64,6 +71,8 @@ def list_all( status: IncentiveProgramStatusLiteral | None = None, incentive_type: IncentiveProgramTypeLiteral | None = None, incentive_description: str | None = None, + series_ticker: str | None = None, + event_ticker: str | None = None, limit: int | None = None, max_pages: int | None = None, extra_headers: dict[str, str] | None = None, @@ -74,6 +83,8 @@ def list_all( status=status, type=incentive_type, incentive_description=incentive_description, + series_ticker=series_ticker, + event_ticker=event_ticker, limit=limit, ) return self._list_all( @@ -86,6 +97,13 @@ def list_all( extra_headers=extra_headers, ) + def list_schedules( + self, *, extra_headers: dict[str, str] | None = None + ) -> builtins.list[IncentiveSchedule]: + """``GET /incentive_schedules``. Public. No pagination.""" + data = self._get("/incentive_schedules", extra_headers=extra_headers) + return GetIncentiveSchedulesResponse.model_validate(data).schedules + class AsyncIncentiveProgramsResource(AsyncResource): """Async incentive programs API.""" @@ -96,6 +114,8 @@ async def list( status: IncentiveProgramStatusLiteral | None = None, incentive_type: IncentiveProgramTypeLiteral | None = None, incentive_description: str | None = None, + series_ticker: str | None = None, + event_ticker: str | None = None, limit: int | None = None, cursor: str | None = None, extra_headers: dict[str, str] | None = None, @@ -105,6 +125,8 @@ async def list( status=status, type=incentive_type, incentive_description=incentive_description, + series_ticker=series_ticker, + event_ticker=event_ticker, limit=limit, cursor=cursor, ) @@ -123,6 +145,8 @@ def list_all( status: IncentiveProgramStatusLiteral | None = None, incentive_type: IncentiveProgramTypeLiteral | None = None, incentive_description: str | None = None, + series_ticker: str | None = None, + event_ticker: str | None = None, limit: int | None = None, max_pages: int | None = None, extra_headers: dict[str, str] | None = None, @@ -134,6 +158,8 @@ def list_all( status=status, type=incentive_type, incentive_description=incentive_description, + series_ticker=series_ticker, + event_ticker=event_ticker, limit=limit, ) return self._list_all( @@ -145,3 +171,10 @@ def list_all( cursor_key="next_cursor", extra_headers=extra_headers, ) + + async def list_schedules( + self, *, extra_headers: dict[str, str] | None = None + ) -> builtins.list[IncentiveSchedule]: + """Async :meth:`IncentiveProgramsResource.list_schedules`.""" + data = await self._get("/incentive_schedules", extra_headers=extra_headers) + return GetIncentiveSchedulesResponse.model_validate(data).schedules diff --git a/pyproject.toml b/pyproject.toml index 397b20d..23aec2e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "22.12.0" +version = "22.13.0" description = "A professional Python SDK for the Kalshi prediction markets and Perps (margin) APIs" readme = "README.md" license = { text = "MIT" } diff --git a/specs/openapi.yaml b/specs/openapi.yaml index 519bd50..1206361 100644 --- a/specs/openapi.yaml +++ b/specs/openapi.yaml @@ -4193,11 +4193,10 @@ paths: threshold, creating it if it doesn't exist yet. The same request always returns the same market, so call this before sending an RFQ for a market you haven't seen. `created` tells you whether the market is new. - An existing market is returned until its window ends, even where new - markets like it are no longer offered. The exception is when weather - markets are switched off (`enabled` is false in the availability - response) or the variable has been withdrawn entirely: the request is - then refused whether or not the market exists. + An existing market is normally returned until its window ends, even + where new markets like it are no longer offered. If weather markets + are switched off entirely, the request can be refused whether or not + the market exists. The location snaps to the center of the NOAA MRMS grid cell containing it; the response carries the snapped coordinates. Markets are only @@ -4425,6 +4424,18 @@ paths: description: Filter by exact incentive description. schema: type: string + - name: series_ticker + in: query + required: false + description: Filter to one series' incentives. + schema: + type: string + - name: event_ticker + in: query + required: false + description: Filter to one event's incentives. A perpetual's incentives belong to no event. + schema: + type: string - name: limit in: query required: false @@ -4459,6 +4470,23 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' + /incentive_schedules: + get: + operationId: GetIncentiveSchedules + summary: Get Incentive Schedules + description: ' Recurring incentives: what each market of a series, or of one event, can expect to earn window after window. A schedule is anticipated, not promised, unless `all_markets` is true. The incentives themselves are listed by Get Incentives.' + tags: + - incentive-programs + responses: + '200': + description: Incentive schedules retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetIncentiveSchedulesResponse' + '500': + $ref: '#/components/responses/InternalServerError' + /fcm/fills: get: operationId: GetFCMFills @@ -8171,6 +8199,12 @@ components: market_ticker: type: string description: The ticker symbol of the market associated with this incentive program + series_ticker: + type: string + description: The series of the market associated with this incentive program + event_ticker: + type: string + description: The event of the market associated with this incentive program; empty for a perpetual incentive_type: type: string enum: ['liquidity', 'volume', 'margin_maker_volume', 'margin_taker_volume'] @@ -8208,6 +8242,93 @@ components: nullable: true description: Maximum reward per account in centi-cents (optional) + GetIncentiveSchedulesResponse: + type: object + required: + - schedules + properties: + schedules: + type: array + items: + $ref: '#/components/schemas/IncentiveSchedule' + + IncentiveSchedule: + type: object + required: + - series_ticker + - series_title + - series_category + - event_ticker + - event_title + - incentive_type + - source + - reward + - window_days + - description + - all_markets + - posted_ts + - updated_ts + properties: + series_ticker: + type: string + description: The series the schedule covers + series_title: + type: string + description: The series' title + series_category: + type: string + description: The series' category + event_ticker: + type: string + description: The one event of the series the schedule covers; empty when it covers the whole series + event_title: + type: string + description: The event's title; empty when the schedule covers the whole series + incentive_type: + type: string + enum: ['liquidity', 'volume'] + description: Type of the incentives the schedule creates + source: + type: string + description: The job that publishes the schedule. With the series, event and type, it identifies the schedule. + reward: + type: integer + format: int64 + description: What each market earns per window, in centi-cents, as period_reward is on an incentive program + window_days: + type: integer + format: int32 + description: Days per window; 0 rewards each market once, up to its close + discount_factor_bps: + type: integer + format: int32 + nullable: true + description: Discount factor in basis points (liquidity only) + target_size_fp: + $ref: '#/components/schemas/FixedPointCount' + nullable: true + description: String representation of the target size (liquidity only) + ends: + type: string + format: date-time + nullable: true + x-omitempty: false + description: When the schedule stops (exclusive); null when it has no end + description: + type: string + description: Plain text description of the schedule + all_markets: + type: boolean + description: A promise that every market the schedule covers, including markets listed later, gets these terms window after window, from posted_ts until ends. When false the schedule is anticipated, not promised. + posted_ts: + type: string + format: date-time + description: When the schedule was first published on its current terms + updated_ts: + type: string + format: date-time + description: When the schedule was last published + GetTradesResponse: type: object required: diff --git a/specs/perps_asyncapi.yaml b/specs/perps_asyncapi.yaml index c7f5df8..d26d99a 100644 --- a/specs/perps_asyncapi.yaml +++ b/specs/perps_asyncapi.yaml @@ -757,8 +757,8 @@ components: lastUpdateReason: type: string - enum: ["Decrease", "Amend", "MarginCancel", "SelfTradeCancel", "ExpiryCancel", "CloseCancel", "HaltCancel", "Trade", "PostOnlyCrossCancel", "ReduceOnlyCancel"] - description: Margin order update reason. The value ReduceOnlyCancel means reduce_only capped the order at placement. The field is omitted when no reason applies. + enum: ["Decrease", "Amend", "MarginCancel", "SelfTradeCancel", "ExpiryCancel", "CloseCancel", "HaltCancel", "Trade", "PostOnlyCrossCancel", "ReduceOnlyCancel", "SettlementBoundsCancel"] + description: Margin order update reason. The value ReduceOnlyCancel means reduce_only capped the order at placement, and SettlementBoundsCancel means the overnight settlement band canceled a resting order priced outside it. The field is omitted when no reason applies. tickerPrice: type: object diff --git a/specs/perps_openapi.yaml b/specs/perps_openapi.yaml index 3328b2a..4f0f2e5 100644 --- a/specs/perps_openapi.yaml +++ b/specs/perps_openapi.yaml @@ -1180,6 +1180,7 @@ paths: summary: Get Balance description: | Endpoint for retrieving the balance breakdown for the authenticated direct margin user. Returns cash balance (aggregate and per-subaccount), position value, total balance, and maintenance margin requirement. + Subaccount-restricted API keys read only their locked subaccount's balance, and the response omits the account-wide `settled_funds` total. Resource-bound MCP OAuth tokens may read the owner's balance with read::mcp_portfolio. x-mint: content: | @@ -1333,7 +1334,12 @@ paths: x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: validate: required - - $ref: '#/components/parameters/SubaccountQuery' + - name: subaccount + in: query + required: false + description: Subaccount number (0 for primary, 1-63 for subaccounts). If omitted, defaults to all subaccounts. Subaccount-restricted API keys must omit this or pass their locked subaccount, and read only that subaccount's funding payments. + schema: + type: integer responses: '200': description: Funding history retrieved successfully @@ -3887,16 +3893,15 @@ components: type: object required: - subaccount_balances - - settled_funds properties: subaccount_balances: type: array items: $ref: '#/components/schemas/MarginSubaccountBalance' - description: Per-subaccount balance breakdown + description: Per-subaccount balance breakdown. Subaccount-restricted API keys receive only their locked subaccount. settled_funds: $ref: '#/components/schemas/FixedPointDollars' - description: Total settled funds across all subaccounts in fixed-point dollars + description: Total settled funds across all subaccounts in fixed-point dollars. Omitted when access is restricted to a subaccount. MarginRiskPosition: type: object diff --git a/tests/_contract_support.py b/tests/_contract_support.py index 2451a82..fb7916e 100644 --- a/tests/_contract_support.py +++ b/tests/_contract_support.py @@ -1024,6 +1024,11 @@ class Exclusion: http_method="GET", path_template="/incentive_programs", ), + MethodEndpointEntry( + sdk_method="kalshi.resources.incentive_programs.IncentiveProgramsResource.list_schedules", + http_method="GET", + path_template="/incentive_schedules", + ), # ── search ────────────────────────────────────────────────────────────── MethodEndpointEntry( sdk_method="kalshi.resources.search.SearchResource.tags_by_categories", @@ -1473,6 +1478,33 @@ class Exclusion: ), kind="server_omits_despite_required", ), + ("kalshi.models.incentive_programs.IncentiveSchedule", "event_ticker"): Exclusion( + reason=( + "spec marks event_ticker required (empty when the schedule covers " + "the whole series); the server may omit empties. SDK keeps it " + "optional (None when absent) so those payloads parse (22.13.0)." + ), + kind="server_omits_despite_required", + ), + ("kalshi.models.incentive_programs.IncentiveSchedule", "event_title"): Exclusion( + reason=( + "spec marks event_title required (empty when the schedule covers " + "the whole series); the server may omit empties. SDK keeps it " + "optional (None when absent) so those payloads parse (22.13.0)." + ), + kind="server_omits_despite_required", + ), + ( + "kalshi.models.incentive_programs.GetIncentiveSchedulesResponse", + "schedules", + ): Exclusion( + reason=( + "spec marks schedules required; SDK defaults to [] so a missing " + "or null array parses as an empty list, matching " + "GetIncentiveProgramsResponse (22.13.0)." + ), + kind="server_omits_despite_required", + ), # --- server_omits_despite_required (#183, post-#172 nightly findings) --- # Fields the OpenAPI spec marks `required: true` but the live demo server # omits in practice. Each entry MUST cite a demo+prod observation in diff --git a/tests/perps/test_margin_account.py b/tests/perps/test_margin_account.py index 56fd4ee..516e15e 100644 --- a/tests/perps/test_margin_account.py +++ b/tests/perps/test_margin_account.py @@ -81,6 +81,14 @@ def test_flag_omitted_by_default(self, perps_client: PerpsClient) -> None: # Param absent unless caller opts in. assert "compute_available_balance" not in route.calls.last.request.url.params + @respx.mock + def test_omitted_settled_funds_parses_as_none(self, perps_client: PerpsClient) -> None: + respx.get(f"{BASE}/margin/balance").mock( + return_value=httpx.Response(200, json={"subaccount_balances": []}) + ) + resp = perps_client.margin.balance() + assert resp.settled_funds is None + @respx.mock def test_null_subaccount_balances_tolerated(self, perps_client: PerpsClient) -> None: # #407: NullableList coerces a server-returned null array to []. diff --git a/tests/perps/ws/test_perps_ws_models.py b/tests/perps/ws/test_perps_ws_models.py index 001b716..2f4b844 100644 --- a/tests/perps/ws/test_perps_ws_models.py +++ b/tests/perps/ws/test_perps_ws_models.py @@ -319,6 +319,22 @@ def test_delta_last_update_reason_reduce_only_cancel(self) -> None: msg = MarginOrderbookDeltaMessage.model_validate(frame) assert msg.msg.last_update_reason == "ReduceOnlyCancel" + def test_delta_last_update_reason_settlement_bounds_cancel(self) -> None: + frame = { + "type": "orderbook_delta", + "sid": 1, + "seq": 2, + "msg": { + "market_ticker": "BTC-PERP", + "price": "100.5000", + "delta": "3.00", + "side": "ask", + "last_update_reason": "SettlementBoundsCancel", + }, + } + msg = MarginOrderbookDeltaMessage.model_validate(frame) + assert msg.msg.last_update_reason == "SettlementBoundsCancel" + class TestTicker: def _full_frame(self) -> dict[str, Any]: diff --git a/tests/test_incentive_programs.py b/tests/test_incentive_programs.py index 3391463..4d666ef 100644 --- a/tests/test_incentive_programs.py +++ b/tests/test_incentive_programs.py @@ -2,6 +2,7 @@ from __future__ import annotations +from datetime import datetime from decimal import Decimal import httpx @@ -11,6 +12,8 @@ from kalshi._base_client import AsyncTransport, SyncTransport from kalshi.auth import KalshiAuth from kalshi.config import KalshiConfig +from kalshi.errors import KalshiServerError +from kalshi.models.incentive_programs import IncentiveProgram, IncentiveSchedule from kalshi.resources.incentive_programs import ( AsyncIncentiveProgramsResource, IncentiveProgramsResource, @@ -56,6 +59,39 @@ def async_resource( target_size_fp="100.5000", ) +_BASE = "https://test.kalshi.com/trade-api/v2" + +_SAMPLE_SCHEDULE = { + "series_ticker": "KXHIGHNY", + "series_title": "Highest temperature in NYC", + "series_category": "Climate and Weather", + "event_ticker": "KXHIGHNY-24JAN01", + "event_title": "Highest temperature in NYC on Jan 1", + "incentive_type": "liquidity", + "source": "weather-liquidity", + "reward": 1_000_000, + "window_days": 7, + "discount_factor_bps": 25, + "target_size_fp": "100.00", + "ends": "2026-12-31T00:00:00Z", + "description": "Weekly liquidity on NYC high-temp markets", + "all_markets": True, + "posted_ts": "2026-01-01T00:00:00Z", + "updated_ts": "2026-01-02T12:00:00Z", +} + +_SAMPLE_SCHEDULE_OPEN_ENDED = { + **_SAMPLE_SCHEDULE, + "series_ticker": "KXBTC", + "event_ticker": None, + "event_title": None, + "incentive_type": "volume", + "ends": None, + "target_size_fp": None, + "discount_factor_bps": None, + "all_markets": False, +} + class TestList: @respx.mock @@ -113,6 +149,21 @@ def test_forwards_filters(self, resource: IncentiveProgramsResource) -> None: # Wire key is `type`, SDK kwarg is `incentive_type` assert url.params["type"] == "volume" assert url.params["limit"] == "50" + assert "series_ticker" not in url.params + assert "event_ticker" not in url.params + + @respx.mock + def test_forwards_series_and_event_ticker( + self, + resource: IncentiveProgramsResource, + ) -> None: + route = respx.get(f"{_BASE}/incentive_programs").mock( + return_value=httpx.Response(200, json={"incentive_programs": []}) + ) + resource.list(series_ticker="KXHIGHNY", event_ticker="KXHIGHNY-24") + url = route.calls.last.request.url + assert url.params["series_ticker"] == "KXHIGHNY" + assert url.params["event_ticker"] == "KXHIGHNY-24" @respx.mock def test_null_target_size_fp( @@ -168,6 +219,32 @@ def test_paginates_next_cursor( # Second call must send cursor=page-2 assert route.calls[1].request.url.params["cursor"] == "page-2" + @respx.mock + def test_forwards_series_and_event_ticker( + self, + resource: IncentiveProgramsResource, + ) -> None: + route = respx.get(f"{_BASE}/incentive_programs").mock( + return_value=httpx.Response(200, json={"incentive_programs": []}) + ) + list(resource.list_all(series_ticker="KXHIGHNY", event_ticker="KXHIGHNY-24")) + url = route.calls.last.request.url + assert url.params["series_ticker"] == "KXHIGHNY" + assert url.params["event_ticker"] == "KXHIGHNY-24" + + @respx.mock + def test_omits_unset_tickers( + self, + resource: IncentiveProgramsResource, + ) -> None: + route = respx.get(f"{_BASE}/incentive_programs").mock( + return_value=httpx.Response(200, json={"incentive_programs": []}) + ) + list(resource.list_all()) + url = route.calls.last.request.url + assert "series_ticker" not in url.params + assert "event_ticker" not in url.params + class TestAsync: @respx.mock @@ -212,6 +289,39 @@ async def test_forwards_filters( assert url.params["type"] == "volume" assert url.params["status"] == "active" assert url.params["limit"] == "50" + assert "series_ticker" not in url.params + assert "event_ticker" not in url.params + + @respx.mock + @pytest.mark.asyncio + async def test_forwards_series_and_event_ticker( + self, + async_resource: AsyncIncentiveProgramsResource, + ) -> None: + route = respx.get(f"{_BASE}/incentive_programs").mock( + return_value=httpx.Response(200, json={"incentive_programs": []}) + ) + await async_resource.list( + series_ticker="KXHIGHNY", + event_ticker="KXHIGHNY-24", + ) + url = route.calls.last.request.url + assert url.params["series_ticker"] == "KXHIGHNY" + assert url.params["event_ticker"] == "KXHIGHNY-24" + + @respx.mock + @pytest.mark.asyncio + async def test_list_all_forwards_tickers( + self, + async_resource: AsyncIncentiveProgramsResource, + ) -> None: + route = respx.get(f"{_BASE}/incentive_programs").mock( + return_value=httpx.Response(200, json={"incentive_programs": []}) + ) + [item async for item in async_resource.list_all(series_ticker="KXHIGHNY")] + url = route.calls.last.request.url + assert url.params["series_ticker"] == "KXHIGHNY" + assert "event_ticker" not in url.params @respx.mock @pytest.mark.asyncio @@ -264,3 +374,176 @@ async def test_paginates_next_cursor( assert items[1].id == "prog-2" assert route.call_count == 2 assert route.calls[1].request.url.params["cursor"] == "page-2" + + +class TestIncentiveProgramTickers: + def test_parses_series_and_event_ticker(self) -> None: + prog = IncentiveProgram.model_validate( + incentive_program_dict( + series_ticker="KXHIGHNY", + event_ticker="KXHIGHNY-24", + ) + ) + assert prog.series_ticker == "KXHIGHNY" + assert prog.event_ticker == "KXHIGHNY-24" + + def test_parses_without_tickers(self) -> None: + prog = IncentiveProgram.model_validate(incentive_program_dict()) + assert prog.series_ticker is None + assert prog.event_ticker is None + + +class TestListSchedules: + @respx.mock + def test_happy_path(self, resource: IncentiveProgramsResource) -> None: + route = respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response( + 200, + json={"schedules": [_SAMPLE_SCHEDULE, _SAMPLE_SCHEDULE_OPEN_ENDED]}, + ) + ) + schedules = resource.list_schedules() + assert route.calls[0].request.method == "GET" + assert str(route.calls[0].request.url) == f"{_BASE}/incentive_schedules" + assert len(schedules) == 2 + first = schedules[0] + assert first.series_ticker == "KXHIGHNY" + assert first.series_title == "Highest temperature in NYC" + assert first.series_category == "Climate and Weather" + assert first.event_ticker == "KXHIGHNY-24JAN01" + assert first.event_title == "Highest temperature in NYC on Jan 1" + assert first.incentive_type == "liquidity" + assert first.source == "weather-liquidity" + assert first.reward == 1_000_000 + assert first.window_days == 7 + assert first.discount_factor_bps == 25 + assert first.target_size_fp == Decimal("100.00") + assert isinstance(first.target_size_fp, Decimal) + assert isinstance(first.ends, datetime) + assert first.ends.tzinfo is not None + assert first.ends.year == 2026 + assert first.all_markets is True + assert isinstance(first.posted_ts, datetime) + assert first.posted_ts.tzinfo is not None + assert isinstance(first.updated_ts, datetime) + assert first.updated_ts.tzinfo is not None + second = schedules[1] + assert second.ends is None + assert second.event_ticker is None + assert second.event_title is None + assert second.target_size_fp is None + assert second.all_markets is False + + @respx.mock + def test_empty_list(self, resource: IncentiveProgramsResource) -> None: + respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response(200, json={"schedules": []}) + ) + assert resource.list_schedules() == [] + + @respx.mock + def test_null_schedules_coerced_to_empty( + self, resource: IncentiveProgramsResource + ) -> None: + respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response(200, json={"schedules": None}) + ) + assert resource.list_schedules() == [] + + @respx.mock + def test_missing_schedules_coerced_to_empty( + self, resource: IncentiveProgramsResource + ) -> None: + respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response(200, json={}) + ) + assert resource.list_schedules() == [] + + @respx.mock + def test_omitted_event_fields_are_none( + self, resource: IncentiveProgramsResource + ) -> None: + payload = { + k: v + for k, v in _SAMPLE_SCHEDULE.items() + if k not in ("event_ticker", "event_title") + } + respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response(200, json={"schedules": [payload]}) + ) + schedule = resource.list_schedules()[0] + assert schedule.event_ticker is None + assert schedule.event_title is None + + def test_omitted_event_fields_parse_on_model(self) -> None: + payload = { + k: v + for k, v in _SAMPLE_SCHEDULE.items() + if k not in ("event_ticker", "event_title") + } + schedule = IncentiveSchedule.model_validate(payload) + assert schedule.event_ticker is None + assert schedule.event_title is None + + @respx.mock + def test_server_error(self, resource: IncentiveProgramsResource) -> None: + respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response(500, json={"error": {"code": "internal"}}) + ) + with pytest.raises(KalshiServerError): + resource.list_schedules() + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path( + self, async_resource: AsyncIncentiveProgramsResource + ) -> None: + route = respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response( + 200, json={"schedules": [_SAMPLE_SCHEDULE]} + ) + ) + schedules = await async_resource.list_schedules() + assert route.calls[0].request.method == "GET" + assert len(schedules) == 1 + assert schedules[0].target_size_fp == Decimal("100.00") + assert isinstance(schedules[0].posted_ts, datetime) + assert schedules[0].posted_ts.tzinfo is not None + + @respx.mock + @pytest.mark.asyncio + async def test_async_null_and_empty( + self, async_resource: AsyncIncentiveProgramsResource + ) -> None: + respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response(200, json={"schedules": None}) + ) + assert await async_resource.list_schedules() == [] + + @respx.mock + @pytest.mark.asyncio + async def test_async_omitted_event_fields( + self, async_resource: AsyncIncentiveProgramsResource + ) -> None: + payload = { + k: v + for k, v in _SAMPLE_SCHEDULE.items() + if k not in ("event_ticker", "event_title") + } + respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response(200, json={"schedules": [payload]}) + ) + schedule = (await async_resource.list_schedules())[0] + assert schedule.event_ticker is None + assert schedule.event_title is None + + @respx.mock + @pytest.mark.asyncio + async def test_async_server_error( + self, async_resource: AsyncIncentiveProgramsResource + ) -> None: + respx.get(f"{_BASE}/incentive_schedules").mock( + return_value=httpx.Response(500, json={"error": {"code": "internal"}}) + ) + with pytest.raises(KalshiServerError): + await async_resource.list_schedules()