From 5beba5be375b13930e04115f71faeb90ebe4abeb Mon Sep 17 00:00:00 2001 From: Jeff West Date: Wed, 2 Dec 2026 09:12:17 -0600 Subject: [PATCH 1/4] chore(specs): sync OpenAPI 3.39.0 / AsyncAPI / perps / SCM specs (2026-12-02) (#594) --- specs/asyncapi.yaml | 219 ++++++++++++++++++++++++++++++++++- specs/openapi.yaml | 135 +++++++++++++++++++-- specs/perps_asyncapi.yaml | 4 + specs/perps_openapi.yaml | 146 +++++++++++++++++++++++ specs/perps_scm_openapi.yaml | 64 ++++++---- 5 files changed, 534 insertions(+), 34 deletions(-) diff --git a/specs/asyncapi.yaml b/specs/asyncapi.yaml index 6c9c162..0a27ad7 100644 --- a/specs/asyncapi.yaml +++ b/specs/asyncapi.yaml @@ -313,11 +313,11 @@ channels: address: market_lifecycle_v2 title: Market & Event Lifecycle description: | - Market state changes and event creation notifications. + Market state changes, event creation notifications, and milestone metadata updates. **Requirements:** - No additional channel-level authentication beyond the authenticated WebSocket connection - - Receives all market and event lifecycle notifications (`market_ticker` filters are not supported) + - Receives lifecycle notifications for all markets and events except multivariate ones (tickers starting with `KXMVE`, sent on `multivariate_market_lifecycle`) and cover markets (tickers starting with `KXRFQ`, sent on `cover_market_lifecycle`); `market_ticker` filters are not supported - Event creation notifications **Use case:** Tracking market lifecycle including creation, de(activation), close date changes, determination, settlement, price level structure changes, and metadata updates @@ -328,6 +328,8 @@ channels: $ref: '#/components/messages/marketMetadataUpdated' eventLifecycle: $ref: '#/components/messages/eventLifecycle' + milestoneUpdated: + $ref: '#/components/messages/milestoneUpdated' eventFeeUpdate: $ref: '#/components/messages/eventFeeUpdate' @@ -350,6 +352,25 @@ channels: eventLifecycle: $ref: '#/components/messages/eventLifecycle' + cover_market_lifecycle: + address: cover_market_lifecycle + title: Cover Market & Event Lifecycle + description: | + Cover market state changes and event creation notifications. Cover markets, such as the weather and concert cover markets, are created when a user requests them, and their tickers start with `KXRFQ`. `market_lifecycle_v2` leaves them out. A `created` message carries the market's schedule, exchange index and price level structure but no `additional_metadata`; read the market's title, rules and strike from `GET /markets/{ticker}`. + + **Requirements:** + - No additional channel-level authentication beyond the authenticated WebSocket connection + - Receives all cover market lifecycle notifications (`market_ticker` filters are not supported) + - Only emits lifecycle updates for markets and events whose tickers start with `KXRFQ` + - Event creation notifications + + **Use case:** Tracking cover market lifecycle including creation, de(activation), close date changes, determination, settlement + messages: + coverMarketLifecycle: + $ref: '#/components/messages/coverMarketLifecycle' + eventLifecycle: + $ref: '#/components/messages/eventLifecycle' + communications: address: communications title: Communications @@ -1087,6 +1108,17 @@ operations: tags: - name: market-data + receiveMilestoneUpdated: + action: send + title: Milestone Updated + summary: Receive updates to the metadata of an existing milestone + channel: + $ref: '#/channels/market_lifecycle_v2' + messages: + - $ref: '#/channels/market_lifecycle_v2/messages/milestoneUpdated' + tags: + - name: market-data + receiveEventFeeUpdate: action: send title: Event Fee Override Update @@ -1120,6 +1152,28 @@ operations: tags: - name: market-data + receiveCoverMarketLifecycle: + action: send + title: Cover Market Lifecycle Event + summary: Receive cover market lifecycle updates (open, close, determination, etc.) + channel: + $ref: '#/channels/cover_market_lifecycle' + messages: + - $ref: '#/channels/cover_market_lifecycle/messages/coverMarketLifecycle' + tags: + - name: market-data + + receiveCoverEventLifecycle: + action: send + title: Cover Event Lifecycle + summary: Receive cover event creation notifications + channel: + $ref: '#/channels/cover_market_lifecycle' + messages: + - $ref: '#/channels/cover_market_lifecycle/messages/eventLifecycle' + tags: + - name: market-data + receiveRFQCreated: action: send title: RFQ Created @@ -1461,6 +1515,13 @@ components: cmd: subscribe params: channels: ["multivariate_market_lifecycle"] + - name: subscribeCoverMarketLifecycle + summary: Subscribe to market lifecycle events for all cover markets + payload: + id: 17 + cmd: subscribe + params: + channels: ["cover_market_lifecycle"] - name: subscribeCommunications summary: Subscribe to communications (RFQs and quotes) payload: @@ -2316,6 +2377,28 @@ components: expected_expiration_ts: 1774029600 event_type: "created" + coverMarketLifecycle: + name: cover_market_lifecycle + title: Cover Market Lifecycle + summary: Cover market lifecycle events (created, activated, deactivated, close_date_updated, determined, settled) + contentType: application/json + payload: + $ref: '#/components/schemas/coverMarketLifecyclePayload' + examples: + - name: coverMarketDetermined + summary: Cover market determined event + payload: + type: cover_market_lifecycle + sending_ts_ms: 1669149841234 + sid: 16 + seq: 4 + msg: + market_ticker: "KXRFQRAINHOURS-35242N101831W-26DEC0106Z-12H-G0" + determination_ts: 1796155200 + result: "no" + settlement_value: "0.0000" + event_type: "determined" + eventLifecycle: name: event_lifecycle title: Event Lifecycle @@ -2339,6 +2422,42 @@ components: collateral_return_type: "MECNET" series_ticker: "KXQUICKSETTLE" + milestoneUpdated: + name: milestone_updated + title: Milestone Updated + summary: A public field on an existing milestone changed + description: | + Emitted when a field returned by `GET /milestones/{milestone_id}` other than `last_updated_ts` changes. + Carries the complete public milestone as returned by Get Milestone, including milestone-specific fields in `details`. + Delivery is best effort. See the [market lifecycle guide](https://docs.kalshi.com/getting_started/market_lifecycle#websocket) for revision handling and REST reconciliation. + contentType: application/json + payload: + $ref: '#/components/schemas/milestoneUpdatedPayload' + examples: + - name: correctedHomeAndAway + payload: + type: milestone_updated + sending_ts_ms: 1796140552692 + sid: 5 + seq: 11 + msg: + milestone_id: "39e357c5-c153-5faf-89a2-59d1bb1edd72" + last_updated_ts_us: 1796140552100001 + milestone: + id: "39e357c5-c153-5faf-89a2-59d1bb1edd72" + category: "Sports" + type: "football_game" + start_date: "2026-12-05T18:00:00Z" + related_event_tickers: ["KXNCAAFGAME-26DEC05TTUTAH"] + primary_event_tickers: ["KXNCAAFGAME-26DEC05TTUTAH"] + title: "Texas Tech at Utah" + notification_message: "Game starts soon" + details: + home_team_id: "721c6368-9a6a-47f1-8fdb-302f25594b6e" + away_team_id: "8c2bb3a9-6c76-47f6-8ccb-eef514f2d166" + source_ids: {} + last_updated_ts: "2026-12-01T15:55:52.100001Z" + eventFeeUpdate: name: event_fee_update title: Event Fee Override Update @@ -3022,7 +3141,7 @@ components: description: List of channels to subscribe to items: type: string - enum: ["orderbook_delta", "ticker", "trade", "fill", "market_positions", "market_lifecycle_v2", "multivariate_market_lifecycle", "communications", "order_group_updates", "user_orders", "cfbenchmarks_value", "cfbenchmarks_value_5hz", "pyth_value", "ebattle_scores"] + enum: ["orderbook_delta", "ticker", "trade", "fill", "market_positions", "market_lifecycle_v2", "multivariate_market_lifecycle", "cover_market_lifecycle", "communications", "order_group_updates", "user_orders", "cfbenchmarks_value", "cfbenchmarks_value_5hz", "pyth_value", "ebattle_scores"] minItems: 1 market_ticker: description: 'Subscribe to a single market. Type: string. Example: "KXBTCD-25AUG0517-T114999.99" (mutually exclusive with market_tickers)' @@ -4225,6 +4344,72 @@ components: sending_ts_ms: $ref: '#/components/schemas/sendingTimestampMs' + coverMarketLifecyclePayload: + type: object + required: ["type", "sid", "seq", "msg"] + properties: + type: + type: string + const: "cover_market_lifecycle" + sid: + $ref: '#/components/schemas/subscriptionId' + seq: + $ref: '#/components/schemas/sequenceNumber' + msg: + type: object + required: ["market_ticker", "event_type"] + properties: + market_ticker: + $ref: '#/components/schemas/marketTicker' + description: Unique identifier for markets. This is what you use to differentiate updates for different markets + exchange_index: + type: integer + description: Optional - This key will ONLY exist when the market is created. Identifier for the exchange shard the market lives on + x-rust-type: i32 + open_ts: + type: integer + description: Optional - This key will ONLY exist when the market is created. Unix timestamp for when the market opened (in seconds) + format: int64 + close_ts: + type: integer + description: Optional - This key will ONLY exist when the market is created OR when the close date is updated. Unix timestamp for when the market is scheduled to close (in seconds). Will be updated in case of early determination markets + format: int64 + determination_ts: + type: integer + description: Optional - This key will ONLY exist when the market is determined. Unix timestamp for when the market is determined (in seconds) + format: int64 + settled_ts: + type: integer + description: Optional - This key will ONLY exist when the market is settled. Unix timestamp for when the market is settled (in seconds) + format: int64 + result: + type: string + description: Optional - This key will ONLY exist when the market is determined. Result of the market + settlement_value: + type: string + description: Optional - This key will ONLY exist when the market is determined. Settlement value of the market in fixed-point dollars (e.g. "0.5000") + x-rust-type: common::types::Price + x-rust-serialize-with: ws::dto::serde_money::serialize_option_price_dollars + is_deactivated: + type: boolean + description: Optional - This key will ONLY exist when the market is paused/unpaused. Boolean flag to indicate if trading is paused on an open market. This should only be interpreted for an open market + event_type: + type: string + description: | + Field to annotate which of the event type this event is for: + - `created` - Market created + - `activated` - Market activated + - `deactivated` - Market deactivated + - `close_date_updated` - Market close date updated + - `determined` - Market determined + - `settled` - Market settled + enum: ["created", "deactivated", "activated", "close_date_updated", "determined", "settled"] + price_level_structure: + $ref: '#/components/schemas/lifecyclePriceLevelStructure' + description: Optional - The market price level structure on creation + sending_ts_ms: + $ref: '#/components/schemas/sendingTimestampMs' + lifecycleAdditionalMetadata: type: object required: ["name", "title", "yes_sub_title", "no_sub_title", "rules_primary", "rules_secondary", "can_close_early", "event_ticker", "expected_expiration_ts"] @@ -4352,6 +4537,34 @@ components: sending_ts_ms: $ref: '#/components/schemas/sendingTimestampMs' + milestoneUpdatedPayload: + type: object + required: ["type", "sid", "seq", "msg"] + properties: + type: + type: string + const: "milestone_updated" + sid: + $ref: '#/components/schemas/subscriptionId' + seq: + $ref: '#/components/schemas/sequenceNumber' + msg: + type: object + required: ["milestone_id", "last_updated_ts_us", "milestone"] + properties: + milestone_id: + type: string + description: ID used by Get Milestone + last_updated_ts_us: + type: integer + format: int64 + description: The milestone's last_updated_ts at this update, in Unix microseconds + milestone: + type: object + description: The complete public Milestone object from GET /milestones/{milestone_id} at this revision. + sending_ts_ms: + $ref: '#/components/schemas/sendingTimestampMs' + eventFeeUpdatePayload: type: object required: ["type", "sid", "seq", "msg"] diff --git a/specs/openapi.yaml b/specs/openapi.yaml index 1f881bc..bb3ec2c 100644 --- a/specs/openapi.yaml +++ b/specs/openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.0.0 info: title: Kalshi Trade API Manual Endpoints - version: 3.38.0 + version: 3.39.0 description: Manually defined OpenAPI spec for endpoints being migrated to spec-first approach servers: @@ -4223,7 +4223,7 @@ paths: operationId: CreateWeatherPointMarket summary: Create Weather Point Market description: | - Returns the on-request weather market for a location, time window and + Returns the weather cover market for a location, time window and 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. @@ -4319,7 +4319,7 @@ paths: operationId: GetWeatherPointAvailability summary: Get Weather Point Market Availability description: | - Returns which on-request weather markets can be created: whether + Returns which weather cover markets can be created: whether creation is on, the NOAA MRMS domains a location may lie in, and the domains each offered variable may use. A variable missing from `variables` can't be created. `max_window_days` and @@ -4347,7 +4347,7 @@ paths: operationId: CreateConcertCancellationMarket summary: Create Concert Cancellation Market description: | - Returns the on-request market on whether a concert is called off, + Returns the cover market on whether a concert is called off, creating it if it doesn't exist yet. A market is defined by the show (`jambase_event_id`), the date it is scheduled for and the `cover`: `postponed`, `cancelled` or `either`. The same request always returns @@ -4432,7 +4432,7 @@ paths: operationId: GetConcertCancellationAvailability summary: Get Concert Cancellation Market Availability description: | - Returns which on-request concert markets are offered: whether they + Returns which concert cover markets are offered: whether they are listed, the covers offered, how far ahead a show may be scheduled, and the metros whose concerts `GET /concert_cancellation_markets/concerts` lists. A cover missing @@ -4613,7 +4613,7 @@ paths: x-excluded: true summary: Create Flight Disruption Market description: | - Returns the on-request market on whether a flight is canceled or + Returns the cover market on whether a flight is canceled or delayed, creating it if it doesn't exist yet. A market is defined by the flight (`carrier`, `flight_number`, `departure_airport`, `arrival_airport` and `scheduled_date`), the `cover` (`cancelled`, @@ -4700,7 +4700,7 @@ paths: x-excluded: true summary: Get Flight Disruption Market Availability description: | - Returns which on-request flight markets can be created: whether + Returns which flight cover markets can be created: whether creation is on, the covers and delay bases offered, the delay thresholds a market may use, how soon and how far ahead a flight may be scheduled, and the countries it may depart from. A cover missing @@ -5008,6 +5008,23 @@ paths: '500': $ref: '#/components/responses/InternalServerError' + /dlp_programs: + get: + operationId: GetDlpPrograms + summary: Get DLP Programs + description: ' The public listing of the Designated Liquidity Provider (DLP) program, the one behind the DLP Rewards page: the programs taking bids, with their incentive period, the number of DLPs sought and when bidding closes; and the programs whose DLPs are selected and whose incentive period has not ended, with how many were selected. It carries no rates, makers or quoting requirements. It lists every program, in every category: the DLP Rewards page also leaves out the categories a visitor''s website restriction blocks, and this endpoint does not, as `GET /incentive_programs` does not.' + tags: + - incentive-programs + responses: + '200': + description: DLP programs retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetDlpProgramsResponse' + '500': + $ref: '#/components/responses/InternalServerError' + /fcm/fills: get: operationId: GetFCMFills @@ -8131,7 +8148,13 @@ components: value: type: integer nullable: true - description: Payout of a single yes contract in cents. + deprecated: true + description: 'DEPRECATED: Payout of a single yes contract in cents, rounded down to a whole cent. Use `value_dollars` instead.' + value_dollars: + $ref: '#/components/schemas/FixedPointDollars' + nullable: true + x-omitempty: true + description: Exact payout of a single yes contract in fixed-point dollars. A scalar market can pay a fraction of a cent, which `value` drops. Omitted, like `value`, when the market has no recorded settlement value, which is not the same as a payout of `"0.0000"`. GetPortfolioRestingOrderTotalValueResponse: type: object @@ -8790,6 +8813,102 @@ components: items: $ref: '#/components/schemas/IncentiveSchedule' + GetDlpProgramsResponse: + type: object + required: + - bidding_periods + - incentivized_series + properties: + bidding_periods: + type: array + description: Programs whose round is taking bids now. + items: + $ref: '#/components/schemas/DlpBiddingProgram' + incentivized_series: + type: array + description: Programs whose DLPs are selected and whose incentive period has not ended. + items: + $ref: '#/components/schemas/DlpIncentivizedProgram' + + DlpBiddingProgram: + type: object + required: + - id + - category + - title + - series_tickers + - period_start + - period_end + - target_dlps + - closes_ts + properties: + id: + type: string + description: The program's id. + category: + type: string + description: The program's category, as the DLP program's caps table names it. + title: + type: string + series_tickers: + type: array + description: The series the program covers. + items: + type: string + period_start: + type: string + format: date-time + description: When the incentive period starts. + period_end: + type: string + format: date-time + description: When the incentive period ends. + target_dlps: + type: integer + format: int32 + description: How many DLPs the program seeks. + closes_ts: + type: string + format: date-time + description: When bidding closes. + + DlpIncentivizedProgram: + type: object + required: + - id + - category + - title + - series_tickers + - period_start + - period_end + - selected_dlps + properties: + id: + type: string + description: The program's id. + category: + type: string + description: The program's category, as the DLP program's caps table names it. + title: + type: string + series_tickers: + type: array + description: The series the program covers. + items: + type: string + period_start: + type: string + format: date-time + description: When the incentive period starts. + period_end: + type: string + format: date-time + description: When the incentive period ends. + selected_dlps: + type: integer + format: int32 + description: How many DLPs were selected. + IncentiveSchedule: type: object required: diff --git a/specs/perps_asyncapi.yaml b/specs/perps_asyncapi.yaml index b16a313..b06e045 100644 --- a/specs/perps_asyncapi.yaml +++ b/specs/perps_asyncapi.yaml @@ -265,6 +265,10 @@ channels: and trading is open exchange-wide only while both are true. A message can repeat the current value. Per-market halts and trading-hours closes are sent on `market_lifecycle_v2`, not on this channel; a market is open only while both channels show it open. + + There is no snapshot: after subscribing, read `GET /trade-api/v2/margin/exchange/status` for + the current values, and do both again after every reconnect. A message received after + subscribing supersedes that response for the flag it carries. messages: exchangeStatus: $ref: '#/components/messages/exchangeStatus' diff --git a/specs/perps_openapi.yaml b/specs/perps_openapi.yaml index 4fe8b2e..ef7f9a2 100644 --- a/specs/perps_openapi.yaml +++ b/specs/perps_openapi.yaml @@ -472,6 +472,121 @@ paths: '500': $ref: '#/components/responses/InternalServerError' + /margin/fcm/im_cap: + get: + operationId: GetFCMIMCap + summary: Get FCM IM Cap + description: | + Returns the calling FCM member's account-level initial margin cap on the margined exchange + and `current_im`, the total the cap is checked against. `current_im` is reported with or + without a cap, and it can be above `im_cap`, since it can rise with no new order. An FCM + that has no account on the margined exchange gets 404. + x-mint: + content: | + + **Rate limit:** 200 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + tags: + - fcm + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + responses: + '200': + description: Initial margin cap retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetFCMIMCapResponse' + '401': + $ref: '#/components/responses/UnauthorizedError' + '403': + $ref: '#/components/responses/ForbiddenError' + '404': + $ref: '#/components/responses/NotFoundError' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + put: + operationId: UpdateFCMIMCap + summary: Update FCM IM Cap + description: | + Sets the calling FCM member's account-level initial margin cap on the margined exchange. An + order that adds risk is rejected with `FCM_ACCOUNT_IM_CAP_EXCEEDED` when it would take the + account's `current_im` (see `GET /margin/fcm/im_cap`) above the cap. Orders that only reduce + risk are still accepted, liquidations are never blocked, and setting or lowering the cap + cancels no order. A cap of zero refuses all new risk. A 500 or a timeout does not say + whether the cap was set, and Kalshi does not resend the request: read the cap back, and send + it again only if you still want to replace the value it returns. + tags: + - fcm + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateFCMIMCapRequest' + responses: + '200': + description: Initial margin cap updated successfully + content: + application/json: + schema: + $ref: '#/components/schemas/EmptyResponse' + '400': + $ref: '#/components/responses/BadRequestError' + '401': + $ref: '#/components/responses/UnauthorizedError' + '403': + $ref: '#/components/responses/ForbiddenError' + '404': + $ref: '#/components/responses/NotFoundError' + '409': + $ref: '#/components/responses/ConflictError' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + delete: + operationId: DeleteFCMIMCap + summary: Delete FCM IM Cap + description: | + Clears the calling FCM member's account-level initial margin cap on the margined exchange. + Orders are then checked as if the account had no cap, and no order is cancelled. A 500 or a + timeout does not say whether the cap was cleared: read the cap back before sending the + request again, since a second delete also clears a cap set in between. + tags: + - fcm + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + responses: + '200': + description: Initial margin cap deleted successfully + content: + application/json: + schema: + $ref: '#/components/schemas/EmptyResponse' + '401': + $ref: '#/components/responses/UnauthorizedError' + '403': + $ref: '#/components/responses/ForbiddenError' + '404': + $ref: '#/components/responses/NotFoundError' + '409': + $ref: '#/components/responses/ConflictError' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + /account/limits/perps: get: operationId: GetPerpsAccountApiLimits @@ -3959,6 +4074,37 @@ components: set. example: "5000.0000" + UpdateFCMIMCapRequest: + type: object + required: + - im_cap + properties: + im_cap: + allOf: + - $ref: '#/components/schemas/FixedPointDollars' + description: A non-negative fixed-point US dollar amount with up to 4 decimal places, at most 92233720368.5477. Zero is allowed and freezes new risk. + pattern: '^[0-9]+(\.[0-9]{1,4})?$' + maxLength: 20 + example: "10000000.0000" + + GetFCMIMCapResponse: + type: object + properties: + im_cap: + allOf: + - $ref: '#/components/schemas/FixedPointDollars' + description: The account-level initial margin cap, as a fixed-point US dollar string with 4 decimal places. Absent when no cap is set. + example: "10000000.0000" + current_im: + allOf: + - $ref: '#/components/schemas/FixedPointDollars' + description: >- + The total the cap is checked against, as a fixed-point US dollar string with 4 decimal places: the sum of + each customer account's initial margin, with open orders counted in full and no netting between customer + accounts, rounded up. Absent while the total is unavailable; while a cap is set, orders that add risk are + then rejected. + example: "1312.4500" + MarginSubaccountBalance: type: object required: diff --git a/specs/perps_scm_openapi.yaml b/specs/perps_scm_openapi.yaml index 5088926..ed710ed 100644 --- a/specs/perps_scm_openapi.yaml +++ b/specs/perps_scm_openapi.yaml @@ -55,11 +55,10 @@ paths: operationId: GetActiveMarginObligations summary: Get Active Margin Obligations description: | - Returns the clearing member's outstanding settlement obligations for - the current cycle across all asset classes, ordered by asset class - then obligation ID. A negative amount indicates a net payable to - Kalshi Klear; a positive amount indicates a net receivable. Empty - when no obligation is pending. + Returns the clearing member's incomplete obligations across all settlement cycles, + ordered by asset class then obligation ID. Group by asset_class and execution_time + to reconcile one cycle. Each signed amount is the obligation's face value. Applied + receipts may have already paid part of a collection. responses: '200': @@ -77,10 +76,9 @@ paths: summary: Get Obligation History description: >- Completed obligations from previous settlements, ordered by most recent - first. Each settlement cycle produces at most one obligation per asset - class, and none when nothing settles in it (no PnL in any market, no - fees and no maintenance margin change). Markets whose PnL offsets still - produce an obligation, at $0. + first. Each asset class can have a settlement obligation and a separate + tax withholding debit. Sum their signed amounts to get net cash. Markets whose PnL offsets still produce + a settlement obligation at $0. parameters: - { name: limit, in: query, required: false, schema: { type: integer, default: 20, maximum: 100 }, description: Number of results per page. } @@ -154,11 +152,12 @@ paths: summary: Get Obligation Corporate Action Payments description: >- Pages the cash and split corporate-action payments settled by one - obligation owned by the authenticated clearing member. The inline + obligation owned by the authenticated clearing member. For a withholding + obligation, only payments with tax withheld are returned. The inline corporate_action_payments array is capped at 1000 rows; corporate_action_payments_truncated indicates when to use this endpoint - for the complete set. These rows explain amounts already included in - settlement PnL and must not be added to the obligation total again. + for the complete set. Settlement PnL includes the gross payments. + The separate InstitutionalWithholding obligation collects the tax on those payments. parameters: - { name: obligation_id, in: path, required: true, schema: { type: string, format: uuid } } - { name: limit, in: query, required: false, schema: { type: integer, default: 1000, maximum: 1000 }, description: Number of rows per page. } @@ -424,7 +423,9 @@ paths: get: operationId: GetSettlementBalanceHistory summary: Get Settlement Balance History - description: Settlement balance changes for the authenticated clearing member, ordered by most recent first. + description: | + Settlement balance changes for the authenticated clearing member, most recent first. + When tax is withheld, the gross settlement entry carries the settlement obligation ID and the tax debit carries the withholding obligation ID. parameters: - { name: limit, in: query, required: false, schema: { type: integer, default: 100, maximum: 500 }, description: Number of results per page. } @@ -446,7 +447,7 @@ paths: post: operationId: WithdrawSettlementBalance summary: Withdraw Settlement Balance - description: Initiate a wire withdrawal from the clearing member's settlement buffer. The withdrawal is processed asynchronously. + description: Initiate a wire withdrawal from the clearing member's settlement buffer. Retry after settlement completes if the member has an active obligation. Accepted withdrawals are processed asynchronously. requestBody: required: true @@ -462,6 +463,11 @@ paths: '400': { $ref: '#/components/responses/BadRequestError' } '401': { $ref: '#/components/responses/UnauthorizedError' } '403': { $ref: '#/components/responses/ForbiddenError' } + '409': + description: An open settlement obligation blocks the withdrawal. The error message tells the member to retry after completion for an in-progress obligation or to contact clearing operations for a failed obligation. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } '500': { $ref: '#/components/responses/InternalServerError' } get: @@ -804,6 +810,7 @@ components: required: - id - user_id + - obligation_type - amount_centicents - amount_fp - fees_centicents @@ -816,18 +823,23 @@ components: properties: id: { type: string } user_id: { type: string } + obligation_type: + type: string + description: InstitutionalPay and InstitutionalReceive settle cash before tax. InstitutionalWithholding settles the separate tax debit. amount_centicents: type: integer format: int64 description: | - Net settlement amount in USD as centicents (1 USD = 10,000 + Signed obligation amount in USD as centicents (1 USD = 10,000 centicents). Monetary fields ending in `_centicents` are integer centicents; where an `_fp` counterpart exists, it carries the same amount as a fixed-point dollar string with 6 decimal places. Total - the clearing member owes or is owed, inclusive of PnL, fees, and - maintenance margin changes. Negative means the clearing member pays + the clearing member owes or is owed, including PnL, fees, and + maintenance margin changes, before tax withholding. + For a withholding obligation, the amount is the tax debit. + Negative means the clearing member pays Kalshi Klear; positive means Kalshi Klear pays the clearing member. - amount_fp: { type: string, description: "amount_centicents as a fixed-point dollar string with 6 decimal places (e.g. \"10005.000000\")." } + amount_fp: { type: string, description: "Signed amount of this obligation as a fixed-point dollar string with 6 decimal places (e.g. \"10005.000000\")." } fees_centicents: { type: integer, format: int64, description: Trading fees incurred during the settlement period. } maintenance_margin_centicents: type: integer @@ -841,8 +853,8 @@ components: member; negative means additional margin the clearing member owes. This is not the requirement: per-subtrader requirements are the `maintenance_margin_centicents` values in the details. - pnl_centicents: { type: integer, format: int64, description: "Total PnL for this settlement period; the sum of the settlement details for this settlement cycle." } - pnl_fp: { type: string, description: pnl_centicents as a fixed-point dollar string with 6 decimal places. } + pnl_centicents: { type: integer, format: int64, description: Sum of the settlement details’ PnL for this cycle before tax withholding. } + pnl_fp: { type: string, description: Total PnL before tax withholding as a fixed-point dollar string with 6 decimal places. } execution_time: { type: string, format: date-time, description: Settlement cycle time this obligation belongs to. } last_updated_ts: { type: string, format: date-time, description: Timestamp of the last status change on this obligation. } asset_class: { $ref: '#/components/schemas/AssetClass' } @@ -922,6 +934,9 @@ components: - payment_time - settlement_execution_time - created_ts + - withholding_fp + - withholding_rate_bps + - withholding_reason properties: id: { type: string } type: { type: string, description: Corporate-action type. } @@ -932,14 +947,17 @@ components: subtrader_id: { type: string } position_quantity_fp: { type: string, description: Signed position before the action as a fixed-point contract count. } post_position_quantity_fp: { type: string, description: Signed position after the action as a fixed-point contract count; unchanged for cash distributions. } - payment_amount_centicents: { type: integer, format: int64, description: Signed cash amount; positive when received and negative when paid. For splits this is cash in lieu and excludes position revaluation. } - payment_amount_fp: { type: string, description: payment_amount_centicents as a fixed-point dollar string with 6 decimal places. } + payment_amount_centicents: { type: integer, format: int64, description: "Signed gross cash amount before withholding, positive when received and negative when paid. For splits this is cash in lieu and excludes position revaluation." } + payment_amount_fp: { type: string, description: Gross cash amount before withholding as a fixed-point dollar string with 6 decimal places. } payment_time: { type: string, format: date-time, nullable: true, description: Scheduled cash payment time; null for splits. } settlement_execution_time: { type: string, format: date-time, description: Settlement cycle that carries this payment. } pre_split_price_centicents: { type: integer, format: int64, description: Mark price before the split; omitted when not applicable. } post_split_price_centicents: { type: integer, format: int64, description: Mark price after the split; omitted when not applicable. } exchange_ts: { type: string, format: date-time, description: Exchange event timestamp when available. } created_ts: { type: string, format: date-time, description: Time the payment row was created. } + withholding_fp: { type: string, description: Tax withheld from this payment as a fixed-point dollar string with 6 decimal places. } + withholding_rate_bps: { type: integer, format: int32, description: Tax rate applied at issuance in basis points. } + withholding_reason: { type: string, description: Reason for tax withheld when the payment was issued. } MaintenanceMarginDetail: type: object @@ -1017,7 +1035,7 @@ components: properties: obligations: type: array - description: Outstanding settlement obligations for the current cycle across all asset classes, ordered by asset class then obligation ID. Empty when no obligation is pending. + description: Incomplete settlement obligations across all cycles and asset classes, ordered by asset class then obligation ID. items: { $ref: '#/components/schemas/ObligationEntry' } GetLargeTraderPositionsResponse: From a07e409970bd8938f2f37ea464b34a4ef462c43b Mon Sep 17 00:00:00 2001 From: Jeff West Date: Wed, 2 Dec 2026 09:58:43 -0600 Subject: [PATCH 2/4] feat: reconcile OpenAPI 3.39.0 spec drift (#594) Add perps FCM account-level IM cap (GET/PUT/DELETE /margin/fcm/im_cap), core GET /dlp_programs, Settlement.value_dollars, Klear obligation_type and withholding fields, WebSocket cover_market_lifecycle plus milestone_updated on market_lifecycle_v2. Additive only; PUT/DELETE remain non-retried. --- CLAUDE.md | 4 +- README.md | 7 +- docs/index.md | 6 +- docs/perps.md | 15 ++- docs/resources/incentive-programs.md | 19 +++ docs/resources/portfolio.md | 6 +- docs/websockets.md | 35 +++++- kalshi/__init__.py | 6 + kalshi/_contract_map.py | 30 +++++ kalshi/models/__init__.py | 6 + kalshi/models/incentive_programs.py | 38 ++++++ kalshi/models/portfolio.py | 2 + kalshi/perps/__init__.py | 4 + kalshi/perps/klear/models/margin.py | 4 + kalshi/perps/models/__init__.py | 4 + kalshi/perps/models/fcm.py | 25 ++++ kalshi/perps/resources/fcm.py | 107 +++++++++++++++++ kalshi/resources/incentive_programs.py | 15 +++ kalshi/ws/channels.py | 1 + kalshi/ws/client.py | 26 +++- kalshi/ws/dispatch.py | 4 + kalshi/ws/models/__init__.py | 14 +++ kalshi/ws/models/cover.py | 25 ++++ kalshi/ws/models/milestone.py | 35 ++++++ tests/_contract_support.py | 84 +++++++++++++ tests/perps/klear/test_margin.py | 22 ++++ tests/perps/test_fcm.py | 160 +++++++++++++++++++++++++ tests/test_contracts.py | 11 +- tests/test_incentive_programs.py | 157 +++++++++++++++++++++++- tests/test_models.py | 20 ++++ tests/ws/test_channels.py | 17 +++ tests/ws/test_client.py | 60 ++++++++++ tests/ws/test_dispatch.py | 58 +++++++++ tests/ws/test_models.py | 87 ++++++++++++++ 34 files changed, 1088 insertions(+), 26 deletions(-) create mode 100644 kalshi/ws/models/cover.py create mode 100644 kalshi/ws/models/milestone.py diff --git a/CLAUDE.md b/CLAUDE.md index b5cf2a7..7e771d1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/README.md b/README.md index 3fba1ef..06fdb51 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 (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. @@ -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 diff --git a/docs/index.md b/docs/index.md index 9c5a3b8..bf9f802 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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`. diff --git a/docs/perps.md b/docs/perps.md index 75fe994..aac31f3 100644 --- a/docs/perps.md +++ b/docs/perps.md @@ -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 @@ -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 @@ -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): diff --git a/docs/resources/incentive-programs.md b/docs/resources/incentive-programs.md index 473da42..b40d41f 100644 --- a/docs/resources/incentive-programs.md +++ b/docs/resources/incentive-programs.md @@ -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 @@ -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 diff --git a/docs/resources/portfolio.md b/docs/resources/portfolio.md index e89e735..286d9b6 100644 --- a/docs/resources/portfolio.md +++ b/docs/resources/portfolio.md @@ -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 diff --git a/docs/websockets.md b/docs/websockets.md index 84731b6..bc7ddf6 100644 --- a/docs/websockets.md +++ b/docs/websockets.md @@ -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 @@ -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 | @@ -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`: @@ -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) ``` @@ -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 diff --git a/kalshi/__init__.py b/kalshi/__init__.py index f937534..4b012cc 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -97,6 +97,8 @@ DecreaseOrderV2Request, DecreaseOrderV2Response, Deposit, + DlpBiddingProgram, + DlpIncentivizedProgram, EndpointTokenCost, Event, EventCandlesticks, @@ -130,6 +132,7 @@ GetCommunicationsIDResponse, GetConcertCancellationAvailabilityResponse, GetConcertsResponse, + GetDlpProgramsResponse, GetEventContractExitTriggersResponse, GetEventLiveDataResponse, GetFCMEventContractDailyCapResponse, @@ -359,6 +362,8 @@ "DecreaseOrderV2Request", "DecreaseOrderV2Response", "Deposit", + "DlpBiddingProgram", + "DlpIncentivizedProgram", "EndpointTokenCost", "Event", "EventCandlesticks", @@ -396,6 +401,7 @@ "GetCommunicationsIDResponse", "GetConcertCancellationAvailabilityResponse", "GetConcertsResponse", + "GetDlpProgramsResponse", "GetEventContractExitTriggersResponse", "GetEventLiveDataResponse", "GetFCMEventContractDailyCapResponse", diff --git a/kalshi/_contract_map.py b/kalshi/_contract_map.py index f6e15b3..bdf187d 100644 --- a/kalshi/_contract_map.py +++ b/kalshi/_contract_map.py @@ -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", @@ -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", @@ -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", diff --git a/kalshi/models/__init__.py b/kalshi/models/__init__.py index 282f98e..5d2806b 100644 --- a/kalshi/models/__init__.py +++ b/kalshi/models/__init__.py @@ -97,6 +97,9 @@ ) from kalshi.models.historical import HistoricalCutoff, MveHistoricalFilterLiteral, Trade from kalshi.models.incentive_programs import ( + DlpBiddingProgram, + DlpIncentivizedProgram, + GetDlpProgramsResponse, GetIncentiveProgramsResponse, GetIncentiveSchedulesResponse, IncentiveProgram, @@ -336,6 +339,8 @@ "DecreaseOrderV2Request", "DecreaseOrderV2Response", "Deposit", + "DlpBiddingProgram", + "DlpIncentivizedProgram", "EndpointTokenCost", "Event", "EventCandlesticks", @@ -369,6 +374,7 @@ "GetCommunicationsIDResponse", "GetConcertCancellationAvailabilityResponse", "GetConcertsResponse", + "GetDlpProgramsResponse", "GetEventContractExitTriggersResponse", "GetEventLiveDataResponse", "GetFCMEventContractDailyCapResponse", diff --git a/kalshi/models/incentive_programs.py b/kalshi/models/incentive_programs.py index 3938d67..2192e36 100644 --- a/kalshi/models/incentive_programs.py +++ b/kalshi/models/incentive_programs.py @@ -90,3 +90,41 @@ class GetIncentiveSchedulesResponse(BaseModel): schedules: NullableList[IncentiveSchedule] = [] model_config = {"extra": "allow"} + + +class DlpBiddingProgram(BaseModel): + """A DLP program whose round is taking bids now.""" + + id: str + category: str + title: str + series_tickers: list[str] + period_start: AwareDatetime + period_end: AwareDatetime + target_dlps: int + closes_ts: AwareDatetime + + model_config = {"extra": "allow"} + + +class DlpIncentivizedProgram(BaseModel): + """A DLP program whose DLPs are selected and whose incentive period has not ended.""" + + id: str + category: str + title: str + series_tickers: list[str] + period_start: AwareDatetime + period_end: AwareDatetime + selected_dlps: int + + model_config = {"extra": "allow"} + + +class GetDlpProgramsResponse(BaseModel): + """Response for GET /dlp_programs.""" + + bidding_periods: NullableList[DlpBiddingProgram] = [] + incentivized_series: NullableList[DlpIncentivizedProgram] = [] + + model_config = {"extra": "allow"} diff --git a/kalshi/models/portfolio.py b/kalshi/models/portfolio.py index 52f78fe..224f319 100644 --- a/kalshi/models/portfolio.py +++ b/kalshi/models/portfolio.py @@ -216,7 +216,9 @@ class Settlement(BaseModel): # v3.18.0 backfill (#160). `value` is integer cents per spec # ("Payout of a single yes contract in cents") — plain int, NOT DollarDecimal. + # Deprecated; prefer `value_dollars` for the exact fixed-point payout. value: int | None = None + value_dollars: DollarDecimal | None = None model_config = {"extra": "allow", "populate_by_name": True} diff --git a/kalshi/perps/__init__.py b/kalshi/perps/__init__.py index c396f47..a968f3b 100644 --- a/kalshi/perps/__init__.py +++ b/kalshi/perps/__init__.py @@ -88,7 +88,9 @@ FCMPositionTransferSideLiteral, FCMSubtraderNotionalRiskLimit, FCMSubtraderRiskControls, + GetFCMIMCapResponse, GetFCMSubtraderRiskControlsResponse, + UpdateFCMIMCapRequest, UpdateFCMNotionalRiskLimitRequest, UpdateFCMSubtraderRiskControlsRequest, ) @@ -309,6 +311,7 @@ "FundingResource", "GetActiveMarginObligationsResponse", "GetExitTriggersResponse", + "GetFCMIMCapResponse", "GetFCMSubtraderRiskControlsResponse", "GetGuarantyFundBalanceResponse", "GetMarginBalanceResponse", @@ -435,6 +438,7 @@ "TimeInForceLiteral", "TransfersResource", "UpdateExitTriggerRequest", + "UpdateFCMIMCapRequest", "UpdateFCMNotionalRiskLimitRequest", "UpdateFCMSubtraderRiskControlsRequest", "UpdateOrderGroupLimitRequest", diff --git a/kalshi/perps/klear/models/margin.py b/kalshi/perps/klear/models/margin.py index cce4b6b..2748012 100644 --- a/kalshi/perps/klear/models/margin.py +++ b/kalshi/perps/klear/models/margin.py @@ -248,6 +248,9 @@ class CorporateActionPaymentDetail(BaseModel): pre_split_price_centicents: int | None = None post_split_price_centicents: int | None = None exchange_ts: AwareDatetime | None = None + withholding_fp: DollarDecimal | None = None + withholding_rate_bps: int | None = None + withholding_reason: str | None = None model_config = {"extra": "allow", "populate_by_name": True} @@ -283,6 +286,7 @@ class ObligationEntry(BaseModel): last_updated_ts: AwareDatetime # Spec (perps SCM) added a required ``asset_class`` on ``ObligationInfo``. asset_class: AssetClassLiteral + obligation_type: str | None = None # From the inline allOf object. receives: NullableList[ObligationReceiveInfo] settlement_details: NullableList[SettlementDetail] diff --git a/kalshi/perps/models/__init__.py b/kalshi/perps/models/__init__.py index afe74ad..b36c45d 100644 --- a/kalshi/perps/models/__init__.py +++ b/kalshi/perps/models/__init__.py @@ -34,7 +34,9 @@ FCMPositionTransferSideLiteral, FCMSubtraderNotionalRiskLimit, FCMSubtraderRiskControls, + GetFCMIMCapResponse, GetFCMSubtraderRiskControlsResponse, + UpdateFCMIMCapRequest, UpdateFCMNotionalRiskLimitRequest, UpdateFCMSubtraderRiskControlsRequest, ) @@ -165,6 +167,7 @@ "FCMSubtraderRiskControls", "FeeScheduleLiteral", "GetExitTriggersResponse", + "GetFCMIMCapResponse", "GetFCMSubtraderRiskControlsResponse", "GetMarginBalanceResponse", "GetMarginCorporateActionPaymentHistoryResponse", @@ -229,6 +232,7 @@ "SubaccountTypeLiteral", "TimeInForceLiteral", "UpdateExitTriggerRequest", + "UpdateFCMIMCapRequest", "UpdateFCMNotionalRiskLimitRequest", "UpdateFCMSubtraderRiskControlsRequest", "UpdateOrderGroupLimitRequest", diff --git a/kalshi/perps/models/fcm.py b/kalshi/perps/models/fcm.py index 8012f28..8c22217 100644 --- a/kalshi/perps/models/fcm.py +++ b/kalshi/perps/models/fcm.py @@ -118,6 +118,31 @@ class UpdateFCMNotionalRiskLimitRequest(BaseModel): model_config = {"extra": "forbid"} +class UpdateFCMIMCapRequest(BaseModel): + """Body for PUT /margin/fcm/im_cap. + + ``im_cap`` is a non-negative fixed-point dollar amount (max 4 decimals). + Zero is allowed and freezes new risk. + """ + + im_cap: OrderPrice + + model_config = {"extra": "forbid"} + + +class GetFCMIMCapResponse(BaseModel): + """Response from GET /margin/fcm/im_cap. + + Wire names are ``im_cap`` and ``current_im`` (no ``_dollars`` suffix). + Both are absent when unset or unavailable. + """ + + im_cap: DollarDecimal | None = None + current_im: DollarDecimal | None = None + + model_config = {"extra": "allow"} + + FCMPositionTransferSideLiteral = Literal["long", "short"] """Side of a position being moved. Spec inline enum on ``CreateMarginFCMPositionTransferRequest.side``. diff --git a/kalshi/perps/resources/fcm.py b/kalshi/perps/resources/fcm.py index c4ddfb4..5ede673 100644 --- a/kalshi/perps/resources/fcm.py +++ b/kalshi/perps/resources/fcm.py @@ -19,7 +19,9 @@ CreateMarginFCMSubtraderResponse, FCMAssetClassLiteral, FCMPositionTransferSideLiteral, + GetFCMIMCapResponse, GetFCMSubtraderRiskControlsResponse, + UpdateFCMIMCapRequest, UpdateFCMNotionalRiskLimitRequest, UpdateFCMSubtraderRiskControlsRequest, ) @@ -33,6 +35,7 @@ _RISK_CONTROLS_PATH = "/margin/fcm/subtraders/risk_controls" _NOTIONAL_RISK_LIMIT_PATH = "/margin/fcm/notional_risk_limit" +_IM_CAP_PATH = "/margin/fcm/im_cap" _POSITION_TRANSFER_PATH = "/margin/fcm/positions/transfers" @@ -108,6 +111,21 @@ def _build_update_notional_risk_limit_body( return request.model_dump(exclude_none=True, by_alias=True, mode="json") +def _build_update_im_cap_body( + request: UpdateFCMIMCapRequest | None, + *, + im_cap: Decimal | None, +) -> dict[str, object]: + _check_request_exclusive(request, im_cap=im_cap) + if request is None: + if im_cap is None: + raise TypeError( + "update_im_cap() requires `im_cap` (or pass `request=...`)" + ) + request = UpdateFCMIMCapRequest(im_cap=im_cap) + return request.model_dump(exclude_none=True, by_alias=True, mode="json") + + def _build_transfer_position_body( request: CreateMarginFCMPositionTransferRequest | None, *, @@ -318,6 +336,54 @@ def delete_notional_risk_limit( self._require_auth() self._delete(_NOTIONAL_RISK_LIMIT_PATH, extra_headers=extra_headers) + def get_im_cap( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetFCMIMCapResponse: + """``GET /margin/fcm/im_cap`` — account-level initial margin cap. + + ``im_cap`` and ``current_im`` are omitted when unset or unavailable. + """ + self._require_auth() + data = self._get(_IM_CAP_PATH, extra_headers=extra_headers) + return GetFCMIMCapResponse.model_validate(data) + + @overload + def update_im_cap( + self, + *, + request: UpdateFCMIMCapRequest, + extra_headers: dict[str, str] | None = None, + ) -> None: ... + @overload + def update_im_cap( + self, + *, + im_cap: Decimal, + extra_headers: dict[str, str] | None = None, + ) -> None: ... + def update_im_cap( + self, + *, + request: UpdateFCMIMCapRequest | None = None, + im_cap: Decimal | None = None, + extra_headers: dict[str, str] | None = None, + ) -> None: + """``PUT /margin/fcm/im_cap`` — set the member's account-level IM cap. + + Not retried. Returns no body (``EmptyResponse``). + """ + self._require_auth() + body = _build_update_im_cap_body(request, im_cap=im_cap) + self._put(_IM_CAP_PATH, json=body, extra_headers=extra_headers) + + def delete_im_cap(self, *, extra_headers: dict[str, str] | None = None) -> None: + """``DELETE /margin/fcm/im_cap`` — clear the account-level IM cap. + + Not retried. Orders are then checked as if the account had no cap. + """ + self._require_auth() + self._delete(_IM_CAP_PATH, extra_headers=extra_headers) + @overload def transfer_position( self, @@ -521,6 +587,47 @@ async def delete_notional_risk_limit( self._require_auth() await self._delete(_NOTIONAL_RISK_LIMIT_PATH, extra_headers=extra_headers) + async def get_im_cap( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetFCMIMCapResponse: + """Async :meth:`FcmResource.get_im_cap`.""" + self._require_auth() + data = await self._get(_IM_CAP_PATH, extra_headers=extra_headers) + return GetFCMIMCapResponse.model_validate(data) + + @overload + async def update_im_cap( + self, + *, + request: UpdateFCMIMCapRequest, + extra_headers: dict[str, str] | None = None, + ) -> None: ... + @overload + async def update_im_cap( + self, + *, + im_cap: Decimal, + extra_headers: dict[str, str] | None = None, + ) -> None: ... + async def update_im_cap( + self, + *, + request: UpdateFCMIMCapRequest | None = None, + im_cap: Decimal | None = None, + extra_headers: dict[str, str] | None = None, + ) -> None: + """Async :meth:`FcmResource.update_im_cap`.""" + self._require_auth() + body = _build_update_im_cap_body(request, im_cap=im_cap) + await self._put(_IM_CAP_PATH, json=body, extra_headers=extra_headers) + + async def delete_im_cap( + self, *, extra_headers: dict[str, str] | None = None + ) -> None: + """Async :meth:`FcmResource.delete_im_cap`.""" + self._require_auth() + await self._delete(_IM_CAP_PATH, extra_headers=extra_headers) + @overload async def transfer_position( self, diff --git a/kalshi/resources/incentive_programs.py b/kalshi/resources/incentive_programs.py index 8410e70..7f9e85e 100644 --- a/kalshi/resources/incentive_programs.py +++ b/kalshi/resources/incentive_programs.py @@ -12,6 +12,7 @@ from kalshi.models.common import Page from kalshi.models.incentive_programs import ( + GetDlpProgramsResponse, GetIncentiveSchedulesResponse, IncentiveProgram, IncentiveProgramStatusLiteral, @@ -104,6 +105,13 @@ def list_schedules( data = self._get("/incentive_schedules", extra_headers=extra_headers) return GetIncentiveSchedulesResponse.model_validate(data).schedules + def dlp_programs( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetDlpProgramsResponse: + """``GET /dlp_programs``. Public. No pagination.""" + data = self._get("/dlp_programs", extra_headers=extra_headers) + return GetDlpProgramsResponse.model_validate(data) + class AsyncIncentiveProgramsResource(AsyncResource): """Async incentive programs API.""" @@ -178,3 +186,10 @@ async def list_schedules( """Async :meth:`IncentiveProgramsResource.list_schedules`.""" data = await self._get("/incentive_schedules", extra_headers=extra_headers) return GetIncentiveSchedulesResponse.model_validate(data).schedules + + async def dlp_programs( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetDlpProgramsResponse: + """Async :meth:`IncentiveProgramsResource.dlp_programs`.""" + data = await self._get("/dlp_programs", extra_headers=extra_headers) + return GetDlpProgramsResponse.model_validate(data) diff --git a/kalshi/ws/channels.py b/kalshi/ws/channels.py index d332aae..245dd94 100644 --- a/kalshi/ws/channels.py +++ b/kalshi/ws/channels.py @@ -67,6 +67,7 @@ } ), "multivariate_market_lifecycle": frozenset(), + "cover_market_lifecycle": frozenset(), "communications": frozenset({"shard_factor", "shard_key"}), # CF Benchmarks index value feed: seeded with index_ids only — market_* # params are not supported on this channel. diff --git a/kalshi/ws/client.py b/kalshi/ws/client.py index 87c3e67..96240e8 100644 --- a/kalshi/ws/client.py +++ b/kalshi/ws/client.py @@ -34,11 +34,13 @@ CFBenchmarksValueMessage, ) from kalshi.ws.models.communications import CommunicationsMessage +from kalshi.ws.models.cover import CoverMarketLifecycleMessage from kalshi.ws.models.ebattle import EbattleScoresMatchlistMessage, EbattleScoresMessage from kalshi.ws.models.event_fee import EventFeeUpdateMessage from kalshi.ws.models.fill import FillMessage from kalshi.ws.models.market_lifecycle import MarketLifecycleMessage from kalshi.ws.models.market_positions import MarketPositionsMessage +from kalshi.ws.models.milestone import MilestoneUpdatedMessage from kalshi.ws.models.multivariate import MultivariateLifecycleMessage from kalshi.ws.models.order_group import OrderGroupMessage from kalshi.ws.models.orderbook_delta import OrderbookDeltaMessage, OrderbookSnapshotMessage @@ -843,12 +845,15 @@ async def subscribe_order_group( async def subscribe_market_lifecycle( self, *, tickers: list[str] | None = None, maxsize: int = 1000, - ) -> AsyncIterator[MarketLifecycleMessage | EventFeeUpdateMessage]: + ) -> AsyncIterator[ + MarketLifecycleMessage | EventFeeUpdateMessage | MilestoneUpdatedMessage + ]: """Subscribe to the market_lifecycle_v2 channel. - Yields :class:`MarketLifecycleMessage` for lifecycle events and - :class:`EventFeeUpdateMessage` for ``event_fee_update`` frames — both - ride this channel. Discriminate on the ``.type`` field. + Yields :class:`MarketLifecycleMessage` for lifecycle events, + :class:`EventFeeUpdateMessage` for ``event_fee_update`` frames, and + :class:`MilestoneUpdatedMessage` for ``milestone_updated`` frames — + all ride this channel. Discriminate on the ``.type`` field. """ params: dict[str, Any] = {} if tickers: @@ -866,6 +871,19 @@ async def subscribe_multivariate_lifecycle( overflow=OverflowStrategy.DROP_OLDEST, maxsize=maxsize, ) + async def subscribe_cover_market_lifecycle( + self, *, maxsize: int = 1000, + ) -> AsyncIterator[CoverMarketLifecycleMessage]: + """Subscribe to the cover_market_lifecycle channel (KXRFQ cover markets). + + Cover markets (tickers starting with ``KXRFQ``) are omitted from + ``market_lifecycle_v2``. ``market_ticker`` filters are not supported. + """ + return await self._do_subscribe( + "cover_market_lifecycle", + overflow=OverflowStrategy.DROP_OLDEST, maxsize=maxsize, + ) + async def subscribe_communications( self, *, diff --git a/kalshi/ws/dispatch.py b/kalshi/ws/dispatch.py index 9b93d4e..46b51c7 100644 --- a/kalshi/ws/dispatch.py +++ b/kalshi/ws/dispatch.py @@ -16,11 +16,13 @@ CFBenchmarksValueMessage, ) from kalshi.ws.models.communications import CommunicationsMessage +from kalshi.ws.models.cover import CoverMarketLifecycleMessage from kalshi.ws.models.ebattle import EbattleScoresMatchlistMessage, EbattleScoresMessage from kalshi.ws.models.event_fee import EventFeeUpdateMessage from kalshi.ws.models.fill import FillMessage from kalshi.ws.models.market_lifecycle import MarketLifecycleMessage from kalshi.ws.models.market_positions import MarketPositionsMessage +from kalshi.ws.models.milestone import MilestoneUpdatedMessage from kalshi.ws.models.multivariate import MultivariateLifecycleMessage from kalshi.ws.models.order_group import OrderGroupMessage from kalshi.ws.models.orderbook_delta import OrderbookDeltaMessage, OrderbookSnapshotMessage @@ -44,7 +46,9 @@ "order_group_updates": OrderGroupMessage, "market_lifecycle_v2": MarketLifecycleMessage, "event_fee_update": EventFeeUpdateMessage, + "milestone_updated": MilestoneUpdatedMessage, "multivariate_market_lifecycle": MultivariateLifecycleMessage, + "cover_market_lifecycle": CoverMarketLifecycleMessage, "communications": CommunicationsMessage, "cfbenchmarks_value": CFBenchmarksValueMessage, "cfbenchmarks_value_indexlist": CFBenchmarksIndexListMessage, diff --git a/kalshi/ws/models/__init__.py b/kalshi/ws/models/__init__.py index a6950ad..6af5441 100644 --- a/kalshi/ws/models/__init__.py +++ b/kalshi/ws/models/__init__.py @@ -28,6 +28,10 @@ RfqCreatedPayload, RfqDeletedPayload, ) +from kalshi.ws.models.cover import ( + CoverMarketLifecycleMessage, + CoverMarketLifecyclePayload, +) from kalshi.ws.models.ebattle import ( EbattleScoresMatchlistMessage, EbattleScoresMatchlistPayload, @@ -47,6 +51,10 @@ MarketPositionsMessage, MarketPositionsPayload, ) +from kalshi.ws.models.milestone import ( + MilestoneUpdatedMessage, + MilestoneUpdatedPayload, +) from kalshi.ws.models.multivariate import ( MultivariateLifecycleMessage, ) @@ -79,6 +87,9 @@ "CFBenchmarksValuePayload", # Communications "CommunicationsMessage", + # Cover market lifecycle + "CoverMarketLifecycleMessage", + "CoverMarketLifecyclePayload", # eBattle scores "EbattleScoresMatchlistMessage", "EbattleScoresMatchlistPayload", @@ -98,6 +109,9 @@ # Market positions "MarketPositionsMessage", "MarketPositionsPayload", + # Milestone updated + "MilestoneUpdatedMessage", + "MilestoneUpdatedPayload", # Multivariate "MultivariateLifecycleMessage", "OkMessage", diff --git a/kalshi/ws/models/cover.py b/kalshi/ws/models/cover.py new file mode 100644 index 0000000..904453e --- /dev/null +++ b/kalshi/ws/models/cover.py @@ -0,0 +1,25 @@ +"""Cover market lifecycle channel message models. + +``cover_market_lifecycle`` reports lifecycle events for KXRFQ cover markets +(weather and concert cover markets). ``market_lifecycle_v2`` leaves them out. +The inner ``msg`` has the same shape as :class:`MarketLifecyclePayload`. +""" +from __future__ import annotations + +from pydantic import BaseModel + +from kalshi.ws.models.market_lifecycle import MarketLifecyclePayload + + +class CoverMarketLifecyclePayload(MarketLifecyclePayload): + """Inner ``msg`` for ``cover_market_lifecycle`` (same shape as market_lifecycle_v2).""" + + +class CoverMarketLifecycleMessage(BaseModel): + """Cover market lifecycle message. Same payload as MarketLifecycleMessage.""" + + type: str = "cover_market_lifecycle" + sid: int + seq: int | None = None + msg: CoverMarketLifecyclePayload + model_config = {"extra": "allow", "populate_by_name": True} diff --git a/kalshi/ws/models/milestone.py b/kalshi/ws/models/milestone.py new file mode 100644 index 0000000..9443a8f --- /dev/null +++ b/kalshi/ws/models/milestone.py @@ -0,0 +1,35 @@ +"""Milestone updated message model (market_lifecycle_v2 channel).""" + +from __future__ import annotations + +from typing import Any, Literal + +from pydantic import BaseModel + + +class MilestoneUpdatedPayload(BaseModel): + """Payload for ``milestone_updated`` messages (market_lifecycle_v2 channel). + + Emitted when a public field on an existing milestone changes. ``milestone`` + is the complete public milestone object from ``GET /milestones/{milestone_id}``. + """ + + milestone_id: str + last_updated_ts_us: int + milestone: dict[str, Any] + + model_config = {"extra": "allow", "populate_by_name": True} + + +class MilestoneUpdatedMessage(BaseModel): + """``milestone_updated`` message delivered on the market_lifecycle_v2 channel. + + Rides the same channel as :class:`MarketLifecycleMessage`; subscribers to + ``subscribe_market_lifecycle`` receive this message type as well. + """ + + type: Literal["milestone_updated"] = "milestone_updated" + sid: int + seq: int | None = None + msg: MilestoneUpdatedPayload + model_config = {"extra": "allow", "populate_by_name": True} diff --git a/tests/_contract_support.py b/tests/_contract_support.py index 78f6097..0362d0a 100644 --- a/tests/_contract_support.py +++ b/tests/_contract_support.py @@ -1066,6 +1066,11 @@ class Exclusion: http_method="GET", path_template="/incentive_schedules", ), + MethodEndpointEntry( + sdk_method="kalshi.resources.incentive_programs.IncentiveProgramsResource.dlp_programs", + http_method="GET", + path_template="/dlp_programs", + ), # ── search ────────────────────────────────────────────────────────────── MethodEndpointEntry( sdk_method="kalshi.resources.search.SearchResource.tags_by_categories", @@ -1542,6 +1547,28 @@ class Exclusion: ), kind="server_omits_despite_required", ), + ( + "kalshi.models.incentive_programs.GetDlpProgramsResponse", + "bidding_periods", + ): Exclusion( + reason=( + "spec marks bidding_periods required; SDK defaults to [] so a " + "missing or null array parses as an empty list, matching " + "GetIncentiveSchedulesResponse (22.19.0)." + ), + kind="server_omits_despite_required", + ), + ( + "kalshi.models.incentive_programs.GetDlpProgramsResponse", + "incentivized_series", + ): Exclusion( + reason=( + "spec marks incentivized_series required; SDK defaults to [] so a " + "missing or null array parses as an empty list, matching " + "GetIncentiveSchedulesResponse (22.19.0)." + ), + kind="server_omits_despite_required", + ), ( "kalshi.models.markets.GetWeatherPointAvailabilityResponse", "max_window_days", @@ -1949,6 +1976,22 @@ class Exclusion: http_method="DELETE", path_template="/margin/fcm/notional_risk_limit", ), + MethodEndpointEntry( + sdk_method="kalshi.perps.resources.fcm.FcmResource.get_im_cap", + http_method="GET", + path_template="/margin/fcm/im_cap", + ), + MethodEndpointEntry( + sdk_method="kalshi.perps.resources.fcm.FcmResource.update_im_cap", + http_method="PUT", + path_template="/margin/fcm/im_cap", + request_body_schema="#/components/schemas/UpdateFCMIMCapRequest", + ), + MethodEndpointEntry( + sdk_method="kalshi.perps.resources.fcm.FcmResource.delete_im_cap", + http_method="DELETE", + path_template="/margin/fcm/im_cap", + ), MethodEndpointEntry( sdk_method="kalshi.perps.resources.fcm.FcmResource.transfer_position", http_method="POST", @@ -2445,6 +2488,47 @@ class Exclusion: reason="client-side page cap, no wire counterpart", kind="client_only", ), + ("kalshi.perps.klear.models.margin.ObligationEntry", "obligation_type"): Exclusion( + reason=( + "spec marks obligation_type required; the SDK keeps it optional " + "(None when absent) so payloads and fixtures predating the field " + "still validate and the change ships as a minor release (22.19.0)." + ), + kind="server_omits_despite_required", + ), + ( + "kalshi.perps.klear.models.margin.CorporateActionPaymentDetail", + "withholding_fp", + ): Exclusion( + reason=( + "spec marks withholding_fp required; the SDK keeps it optional " + "(None when absent) so payloads and fixtures predating the field " + "still validate and the change ships as a minor release (22.19.0)." + ), + kind="server_omits_despite_required", + ), + ( + "kalshi.perps.klear.models.margin.CorporateActionPaymentDetail", + "withholding_rate_bps", + ): Exclusion( + reason=( + "spec marks withholding_rate_bps required; the SDK keeps it optional " + "(None when absent) so payloads and fixtures predating the field " + "still validate and the change ships as a minor release (22.19.0)." + ), + kind="server_omits_despite_required", + ), + ( + "kalshi.perps.klear.models.margin.CorporateActionPaymentDetail", + "withholding_reason", + ): Exclusion( + reason=( + "spec marks withholding_reason required; the SDK keeps it optional " + "(None when absent) so payloads and fixtures predating the field " + "still validate and the change ships as a minor release (22.19.0)." + ), + kind="server_omits_despite_required", + ), # Spec marks each additive *_fp dollar string required next to its integer # *_centicents field. The SDK keeps *_fp optional so a centicents-only # payload still parses. The two attributes are separate; there is no alias. diff --git a/tests/perps/klear/test_margin.py b/tests/perps/klear/test_margin.py index eee9795..e1f4d5b 100644 --- a/tests/perps/klear/test_margin.py +++ b/tests/perps/klear/test_margin.py @@ -1947,6 +1947,9 @@ def test_corporate_action_payment_centicents_only_and_both(self) -> None: assert old.payment_amount_centicents == 400 assert isinstance(old.payment_amount_centicents, int) assert old.payment_amount_fp is None + assert old.withholding_fp is None + assert old.withholding_rate_bps is None + assert old.withholding_reason is None both = CorporateActionPaymentDetail.model_validate( _corporate_action_payment(payment_amount_fp="0.040000") @@ -1957,6 +1960,18 @@ def test_corporate_action_payment_centicents_only_and_both(self) -> None: assert dumped["payment_amount_centicents"] == 400 assert dumped["payment_amount_fp"] == "0.040000" + def test_corporate_action_payment_withholding_fields(self) -> None: + parsed = CorporateActionPaymentDetail.model_validate( + _corporate_action_payment( + withholding_fp="0.004000", + withholding_rate_bps=100, + withholding_reason="US withholding", + ) + ) + assert parsed.withholding_fp == Decimal("0.004") + assert parsed.withholding_rate_bps == 100 + assert parsed.withholding_reason == "US withholding" + def test_obligation_entry_centicents_only_and_both(self) -> None: old = ObligationEntry.model_validate(_obligation()) assert old.amount_centicents == -12345 @@ -1964,6 +1979,7 @@ def test_obligation_entry_centicents_only_and_both(self) -> None: assert old.amount_fp is None assert old.pnl_centicents == -200 assert old.pnl_fp is None + assert old.obligation_type is None both = ObligationEntry.model_validate( _obligation(amount=12345) | {"amount_fp": "1.234500", "pnl_fp": "-0.020000"} @@ -1978,6 +1994,12 @@ def test_obligation_entry_centicents_only_and_both(self) -> None: assert dumped["pnl_centicents"] == -200 assert dumped["pnl_fp"] == "-0.020000" + def test_obligation_entry_obligation_type(self) -> None: + parsed = ObligationEntry.model_validate( + _obligation() | {"obligation_type": "settlement"} + ) + assert parsed.obligation_type == "settlement" + def test_market_settlement_estimate_centicents_only_and_both(self) -> None: centicents = { "quantity_centicount": 1, diff --git a/tests/perps/test_fcm.py b/tests/perps/test_fcm.py index 2542bad..d9eff7a 100644 --- a/tests/perps/test_fcm.py +++ b/tests/perps/test_fcm.py @@ -23,6 +23,8 @@ CreateMarginFCMPositionTransferResponse, CreateMarginFCMSubtraderRequest, CreateMarginFCMSubtraderResponse, + GetFCMIMCapResponse, + UpdateFCMIMCapRequest, UpdateFCMNotionalRiskLimitRequest, UpdateFCMSubtraderRiskControlsRequest, ) @@ -493,6 +495,164 @@ async def test_async_roundtrip(self, async_perps_client: AsyncPerpsClient) -> No assert delete.called +class TestUpdateFCMIMCapRequest: + def test_serializes(self) -> None: + req = UpdateFCMIMCapRequest(im_cap=Decimal("10000000.0000")) + assert req.model_dump(exclude_none=True, by_alias=True, mode="json") == { + "im_cap": "10000000.0000", + } + + def test_zero_allowed(self) -> None: + req = UpdateFCMIMCapRequest(im_cap=Decimal("0")) + assert req.model_dump(exclude_none=True, by_alias=True, mode="json") == { + "im_cap": "0", + } + + def test_rejects_negative(self) -> None: + with pytest.raises(ValidationError): + UpdateFCMIMCapRequest(im_cap=Decimal("-1.00")) + + def test_forbids_extra(self) -> None: + with pytest.raises(ValidationError): + UpdateFCMIMCapRequest( # type: ignore[call-arg] + im_cap=Decimal("1.00"), + phantom=1, + ) + + +class TestGetFCMIMCapResponse: + def test_parses_both_fields(self) -> None: + resp = GetFCMIMCapResponse.model_validate( + {"im_cap": "10000000.0000", "current_im": "1312.4500"} + ) + assert resp.im_cap == Decimal("10000000.0000") + assert resp.current_im == Decimal("1312.4500") + + def test_omitted_fields_are_none(self) -> None: + resp = GetFCMIMCapResponse.model_validate({}) + assert resp.im_cap is None + assert resp.current_im is None + + +class TestFcmImCap: + @respx.mock + def test_get(self, perps_client: PerpsClient) -> None: + route = respx.get(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response( + 200, + json={"im_cap": "10000000.0000", "current_im": "1312.4500"}, + ) + ) + resp = perps_client.fcm.get_im_cap() + assert resp.im_cap == Decimal("10000000.0000") + assert resp.current_im == Decimal("1312.4500") + assert route.called + + @respx.mock + def test_get_omitted_fields(self, perps_client: PerpsClient) -> None: + respx.get(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(200, json={}) + ) + resp = perps_client.fcm.get_im_cap() + assert resp.im_cap is None + assert resp.current_im is None + + @respx.mock + def test_get_server_404(self, perps_client: PerpsClient) -> None: + respx.get(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(404, json={"message": "no margined account"}) + ) + with pytest.raises(Exception): # noqa: B017 — mapped not-found error + perps_client.fcm.get_im_cap() + + def test_get_unauthenticated(self) -> None: + client = PerpsClient(config=PerpsConfig.demo(max_retries=0)) + with pytest.raises(AuthRequiredError): + client.fcm.get_im_cap() + + @respx.mock + def test_update_kwargs(self, perps_client: PerpsClient) -> None: + route = respx.put(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(200, json={}) + ) + assert perps_client.fcm.update_im_cap(im_cap=Decimal("10000000.0000")) is None + assert json.loads(route.calls[0].request.content) == { + "im_cap": "10000000.0000", + } + + @respx.mock + def test_update_request_model(self, perps_client: PerpsClient) -> None: + route = respx.put(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(200, json={}) + ) + req = UpdateFCMIMCapRequest(im_cap=Decimal("10.00")) + perps_client.fcm.update_im_cap(request=req) + assert json.loads(route.calls[0].request.content) == { + "im_cap": "10.00", + } + + def test_update_requires_args(self, perps_client: PerpsClient) -> None: + with pytest.raises(TypeError, match="update_im_cap"): + perps_client.fcm.update_im_cap() # type: ignore[call-overload] + + @respx.mock + def test_update_server_400(self, perps_client: PerpsClient) -> None: + respx.put(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(400, json={"message": "above Kalshi ceiling"}) + ) + with pytest.raises(Exception): # noqa: B017 — mapped validation error + perps_client.fcm.update_im_cap(im_cap=Decimal("999999.0000")) + + def test_update_unauthenticated(self) -> None: + client = PerpsClient(config=PerpsConfig.demo(max_retries=0)) + with pytest.raises(AuthRequiredError): + client.fcm.update_im_cap(im_cap=Decimal("1")) + + @respx.mock + def test_delete(self, perps_client: PerpsClient) -> None: + route = respx.delete(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(200, json={}) + ) + assert perps_client.fcm.delete_im_cap() is None + assert route.called + assert route.calls[0].request.content == b"" + + @respx.mock + def test_delete_server_401(self, perps_client: PerpsClient) -> None: + respx.delete(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(401, json={"message": "unauthorized"}) + ) + with pytest.raises(Exception): # noqa: B017 — mapped auth error + perps_client.fcm.delete_im_cap() + + def test_delete_unauthenticated(self) -> None: + client = PerpsClient(config=PerpsConfig.demo(max_retries=0)) + with pytest.raises(AuthRequiredError): + client.fcm.delete_im_cap() + + @respx.mock + async def test_async_roundtrip(self, async_perps_client: AsyncPerpsClient) -> None: + get = respx.get(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(200, json={"im_cap": "5.0000"}) + ) + put = respx.put(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(200, json={}) + ) + delete = respx.delete(f"{BASE}/margin/fcm/im_cap").mock( + return_value=httpx.Response(200, json={}) + ) + resp = await async_perps_client.fcm.get_im_cap() + assert resp.im_cap == Decimal("5.0000") + assert resp.current_im is None + await async_perps_client.fcm.update_im_cap(im_cap=Decimal("2.00")) + await async_perps_client.fcm.delete_im_cap() + assert get.called + assert json.loads(put.calls[0].request.content) == { + "im_cap": "2.00", + } + assert delete.called + + _TRANSFER_ID = "6d1f0c5a-2b3e-4f7a-9c8d-0e1f2a3b4c5d" _TRANSFER_PATH = f"{BASE}/margin/fcm/positions/transfers" _SOURCE = "3f2a8c1e-5b7d-4e9a-8c6f-1d2b3a4e5f60_CUST123" diff --git a/tests/test_contracts.py b/tests/test_contracts.py index 8eaceac..2204a03 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -1094,14 +1094,16 @@ def test_ws_schema_coverage(self) -> None: def test_batch_communications_channel_removed(self) -> None: """#556 dropped ``batch_communications`` (16 → 15); #575 added - ``ebattle_scores`` (15 → 16). ``batch_communications`` stays gone; - ``communications`` and the new ``ebattle_scores`` channel are present. + ``ebattle_scores`` (15 → 16). #594 added ``cover_market_lifecycle`` + (16 → 17). ``batch_communications`` stays gone; ``communications``, + ``ebattle_scores``, and ``cover_market_lifecycle`` are present. """ channels = self.spec.get("channels", {}) assert "batch_communications" not in channels assert "communications" in channels assert "ebattle_scores" in channels - assert len(channels) == 16 + assert "cover_market_lifecycle" in channels + assert len(channels) == 17 def test_ws_envelope_type_drift(self) -> None: """Warn if spec type const values differ from SDK message envelope type defaults.""" @@ -1563,6 +1565,9 @@ def _assert_params_match( "#/components/schemas/UpdateFCMNotionalRiskLimitRequest": ( "kalshi.perps.models.fcm.UpdateFCMNotionalRiskLimitRequest" ), + "#/components/schemas/UpdateFCMIMCapRequest": ( + "kalshi.perps.models.fcm.UpdateFCMIMCapRequest" + ), "#/components/schemas/CreateMarginFCMPositionTransferRequest": ( "kalshi.perps.models.fcm.CreateMarginFCMPositionTransferRequest" ), diff --git a/tests/test_incentive_programs.py b/tests/test_incentive_programs.py index 4d666ef..0b726c2 100644 --- a/tests/test_incentive_programs.py +++ b/tests/test_incentive_programs.py @@ -13,7 +13,12 @@ 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.models.incentive_programs import ( + DlpBiddingProgram, + GetDlpProgramsResponse, + IncentiveProgram, + IncentiveSchedule, +) from kalshi.resources.incentive_programs import ( AsyncIncentiveProgramsResource, IncentiveProgramsResource, @@ -547,3 +552,153 @@ async def test_async_server_error( ) with pytest.raises(KalshiServerError): await async_resource.list_schedules() + + +_SAMPLE_BIDDING = { + "id": "dlp-bid-1", + "category": "Climate and Weather", + "title": "NYC high temperature DLP", + "series_tickers": ["KXHIGHNY"], + "period_start": "2026-06-01T00:00:00Z", + "period_end": "2026-09-01T00:00:00Z", + "target_dlps": 3, + "closes_ts": "2026-05-15T00:00:00Z", +} + +_SAMPLE_INCENTIVIZED = { + "id": "dlp-inc-1", + "category": "Climate and Weather", + "title": "NYC high temperature DLP", + "series_tickers": ["KXHIGHNY"], + "period_start": "2026-01-01T00:00:00Z", + "period_end": "2026-04-01T00:00:00Z", + "selected_dlps": 2, +} + + +class TestDlpPrograms: + @respx.mock + def test_happy_path(self, resource: IncentiveProgramsResource) -> None: + route = respx.get(f"{_BASE}/dlp_programs").mock( + return_value=httpx.Response( + 200, + json={ + "bidding_periods": [_SAMPLE_BIDDING], + "incentivized_series": [_SAMPLE_INCENTIVIZED], + }, + ) + ) + resp = resource.dlp_programs() + assert route.calls[0].request.method == "GET" + assert str(route.calls[0].request.url) == f"{_BASE}/dlp_programs" + assert len(resp.bidding_periods) == 1 + first = resp.bidding_periods[0] + assert first.id == "dlp-bid-1" + assert first.category == "Climate and Weather" + assert first.series_tickers == ["KXHIGHNY"] + assert first.target_dlps == 3 + assert isinstance(first.period_start, datetime) + assert first.period_start.tzinfo is not None + assert isinstance(first.closes_ts, datetime) + assert len(resp.incentivized_series) == 1 + inc = resp.incentivized_series[0] + assert inc.selected_dlps == 2 + assert inc.id == "dlp-inc-1" + + @respx.mock + def test_empty_lists(self, resource: IncentiveProgramsResource) -> None: + respx.get(f"{_BASE}/dlp_programs").mock( + return_value=httpx.Response( + 200, json={"bidding_periods": [], "incentivized_series": []} + ) + ) + resp = resource.dlp_programs() + assert resp.bidding_periods == [] + assert resp.incentivized_series == [] + + @respx.mock + def test_null_lists_coerced_to_empty( + self, resource: IncentiveProgramsResource + ) -> None: + respx.get(f"{_BASE}/dlp_programs").mock( + return_value=httpx.Response( + 200, json={"bidding_periods": None, "incentivized_series": None} + ) + ) + resp = resource.dlp_programs() + assert resp.bidding_periods == [] + assert resp.incentivized_series == [] + + @respx.mock + def test_missing_lists_coerced_to_empty( + self, resource: IncentiveProgramsResource + ) -> None: + respx.get(f"{_BASE}/dlp_programs").mock( + return_value=httpx.Response(200, json={}) + ) + resp = resource.dlp_programs() + assert resp.bidding_periods == [] + assert resp.incentivized_series == [] + + def test_omitted_lists_parse_on_model(self) -> None: + resp = GetDlpProgramsResponse.model_validate({}) + assert resp.bidding_periods == [] + assert resp.incentivized_series == [] + + def test_bidding_program_parses(self) -> None: + prog = DlpBiddingProgram.model_validate(_SAMPLE_BIDDING) + assert prog.target_dlps == 3 + assert isinstance(prog.closes_ts, datetime) + + @respx.mock + def test_server_error(self, resource: IncentiveProgramsResource) -> None: + respx.get(f"{_BASE}/dlp_programs").mock( + return_value=httpx.Response(500, json={"error": {"code": "internal"}}) + ) + with pytest.raises(KalshiServerError): + resource.dlp_programs() + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path( + self, async_resource: AsyncIncentiveProgramsResource + ) -> None: + route = respx.get(f"{_BASE}/dlp_programs").mock( + return_value=httpx.Response( + 200, + json={ + "bidding_periods": [_SAMPLE_BIDDING], + "incentivized_series": [], + }, + ) + ) + resp = await async_resource.dlp_programs() + assert route.calls[0].request.method == "GET" + assert len(resp.bidding_periods) == 1 + assert resp.incentivized_series == [] + assert resp.bidding_periods[0].title == "NYC high temperature DLP" + + @respx.mock + @pytest.mark.asyncio + async def test_async_null_and_empty( + self, async_resource: AsyncIncentiveProgramsResource + ) -> None: + respx.get(f"{_BASE}/dlp_programs").mock( + return_value=httpx.Response( + 200, json={"bidding_periods": None, "incentivized_series": None} + ) + ) + resp = await async_resource.dlp_programs() + assert resp.bidding_periods == [] + assert resp.incentivized_series == [] + + @respx.mock + @pytest.mark.asyncio + async def test_async_server_error( + self, async_resource: AsyncIncentiveProgramsResource + ) -> None: + respx.get(f"{_BASE}/dlp_programs").mock( + return_value=httpx.Response(500, json={"error": {"code": "internal"}}) + ) + with pytest.raises(KalshiServerError): + await async_resource.dlp_programs() diff --git a/tests/test_models.py b/tests/test_models.py index 514dbc6..7aab442 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -527,6 +527,26 @@ def test_value_defaults_to_none(self) -> None: s = Settlement.model_validate(settlement_dict(ticker="T")) assert s.value is None + def test_value_dollars_parses(self) -> None: + s = Settlement.model_validate( + settlement_dict(ticker="T", value=100, value_dollars="1.0000") + ) + assert s.value == 100 + assert isinstance(s.value, int) + assert s.value_dollars == Decimal("1.0000") + + def test_value_dollars_omitted(self) -> None: + s = Settlement.model_validate(settlement_dict(ticker="T", value=50)) + assert s.value == 50 + assert s.value_dollars is None + + def test_value_dollars_null(self) -> None: + s = Settlement.model_validate( + settlement_dict(ticker="T", value=None, value_dollars=None) + ) + assert s.value is None + assert s.value_dollars is None + class TestTradeV3180Fields: """v3.18.0 backfill (issue #160): 2 new optional fields on ``Trade``. diff --git a/tests/ws/test_channels.py b/tests/ws/test_channels.py index 43b2bed..eed7dfa 100644 --- a/tests/ws/test_channels.py +++ b/tests/ws/test_channels.py @@ -100,6 +100,23 @@ def test_to_subscribe_params_communications_shard_keys(self) -> None: result = sub.to_subscribe_params() assert result == {"channels": ["communications"], "shard_factor": 2, "shard_key": 1} + def test_to_subscribe_params_cover_market_lifecycle_no_filters(self) -> None: + queue: MessageQueue[object] = MessageQueue(maxsize=10) + sub = Subscription( + client_id=1, channel="cover_market_lifecycle", params={}, queue=queue, + ) + result = sub.to_subscribe_params() + assert result == {"channels": ["cover_market_lifecycle"]} + + rejected = Subscription( + client_id=1, + channel="cover_market_lifecycle", + params={"market_tickers": ["KXRFQ-1"]}, + queue=queue, + ) + with pytest.raises(KalshiSubscriptionError, match="Unknown param key"): + rejected.to_subscribe_params() + def test_to_subscribe_params_unmodeled_channel_falls_back(self) -> None: """Generic subscribe escape hatch: unmodeled channels accept any forward key.""" queue: MessageQueue[object] = MessageQueue(maxsize=10) diff --git a/tests/ws/test_client.py b/tests/ws/test_client.py index 16f744c..bdc5768 100644 --- a/tests/ws/test_client.py +++ b/tests/ws/test_client.py @@ -335,6 +335,66 @@ async def test_receives_matchlist_message(self, fake_ws, test_auth) -> None: # assert msg.msg.match_ids == ["milestone-abc"] +class TestSubscribeCoverMarketLifecycle: + async def test_subscribe_sends_channel(self, fake_ws, test_auth) -> None: # type: ignore[no-untyped-def] + config = KalshiConfig(ws_base_url=fake_ws.url, timeout=5.0) + ws = KalshiWebSocket(auth=test_auth, config=config) + async with ws.connect() as session: + await session.subscribe_cover_market_lifecycle() + cmd = fake_ws.received_commands[0] + assert cmd["cmd"] == "subscribe" + assert cmd["params"]["channels"] == ["cover_market_lifecycle"] + assert "market_tickers" not in cmd["params"] + + async def test_receives_cover_lifecycle(self, fake_ws, test_auth) -> None: # type: ignore[no-untyped-def] + from kalshi.ws.models.cover import CoverMarketLifecycleMessage + + config = KalshiConfig(ws_base_url=fake_ws.url, timeout=5.0) + ws = KalshiWebSocket(auth=test_auth, config=config) + async with ws.connect() as session: + stream = await session.subscribe_cover_market_lifecycle() + await fake_ws.send_to_all( + { + "type": "cover_market_lifecycle", + "sid": 1, + "seq": 1, + "msg": { + "market_ticker": "KXRFQ-1", + "event_type": "created", + }, + } + ) + msg = await asyncio.wait_for(stream.__anext__(), timeout=2.0) + assert isinstance(msg, CoverMarketLifecycleMessage) + assert msg.msg.event_type == "created" + assert msg.msg.market_ticker == "KXRFQ-1" + + async def test_market_lifecycle_receives_milestone_updated( + self, fake_ws, test_auth + ) -> None: # type: ignore[no-untyped-def] + from kalshi.ws.models.milestone import MilestoneUpdatedMessage + + config = KalshiConfig(ws_base_url=fake_ws.url, timeout=5.0) + ws = KalshiWebSocket(auth=test_auth, config=config) + async with ws.connect() as session: + stream = await session.subscribe_market_lifecycle() + await fake_ws.send_to_all( + { + "type": "milestone_updated", + "sid": 1, + "seq": 2, + "msg": { + "milestone_id": "m1", + "last_updated_ts_us": 1, + "milestone": {"id": "m1"}, + }, + } + ) + msg = await asyncio.wait_for(stream.__anext__(), timeout=2.0) + assert isinstance(msg, MilestoneUpdatedMessage) + assert msg.msg.milestone_id == "m1" + + class TestSubscribeOrderbookDelta: async def test_sets_snapshot_flag(self, fake_ws, test_auth) -> None: # type: ignore[no-untyped-def] config = KalshiConfig(ws_base_url=fake_ws.url, timeout=5.0) diff --git a/tests/ws/test_dispatch.py b/tests/ws/test_dispatch.py index 5324a12..4f9c91e 100644 --- a/tests/ws/test_dispatch.py +++ b/tests/ws/test_dispatch.py @@ -11,12 +11,14 @@ from kalshi.ws.backpressure import MessageQueue from kalshi.ws.channels import Subscription from kalshi.ws.dispatch import CONTROL_TYPES, MESSAGE_MODELS, MessageDispatcher +from kalshi.ws.models.cover import CoverMarketLifecycleMessage from kalshi.ws.models.ebattle import ( EbattleScoresMatchlistMessage, EbattleScoresMessage, ) from kalshi.ws.models.event_fee import EventFeeUpdateMessage from kalshi.ws.models.market_positions import MarketPositionsMessage +from kalshi.ws.models.milestone import MilestoneUpdatedMessage from kalshi.ws.models.user_orders import UserOrdersMessage from kalshi.ws.sequence import SequenceTracker from tests._model_fixtures import ( @@ -148,6 +150,60 @@ async def test_dispatch_event_fee_update(self) -> None: assert msg.msg.event_ticker == "KXBTCD-26MAY2018" assert msg.msg.fee_type_override == "quadratic" + async def test_dispatch_milestone_updated(self) -> None: + """#594: milestone_updated rides the market_lifecycle_v2 channel.""" + mgr = FakeSubManager() + sub = mgr.add(5, "market_lifecycle_v2") + dispatcher = MessageDispatcher(sub_mgr=mgr) # type: ignore[arg-type] + raw = json.dumps( + { + "type": "milestone_updated", + "sid": 5, + "seq": 11, + "msg": { + "milestone_id": "39e357c5-c153-5faf-89a2-59d1bb1edd72", + "last_updated_ts_us": 1796140552100001, + "milestone": { + "id": "39e357c5-c153-5faf-89a2-59d1bb1edd72", + "category": "Sports", + }, + }, + } + ) + await dispatcher.dispatch(json.loads(raw)) + msg = await sub.queue.get() + assert isinstance(msg, MilestoneUpdatedMessage) + assert msg.type == "milestone_updated" + assert msg.msg.milestone_id == "39e357c5-c153-5faf-89a2-59d1bb1edd72" + assert msg.msg.last_updated_ts_us == 1796140552100001 + assert msg.msg.milestone["category"] == "Sports" + + async def test_dispatch_cover_market_lifecycle(self) -> None: + """#594: cover_market_lifecycle is its own channel.""" + mgr = FakeSubManager() + sub = mgr.add(16, "cover_market_lifecycle") + dispatcher = MessageDispatcher(sub_mgr=mgr) # type: ignore[arg-type] + raw = json.dumps( + { + "type": "cover_market_lifecycle", + "sid": 16, + "seq": 4, + "msg": { + "market_ticker": "KXRFQRAINHOURS-35242N101831W-26DEC0106Z-12H-G0", + "determination_ts": 1796155200, + "result": "no", + "settlement_value": "0.0000", + "event_type": "determined", + }, + } + ) + await dispatcher.dispatch(json.loads(raw)) + msg = await sub.queue.get() + assert isinstance(msg, CoverMarketLifecycleMessage) + assert msg.type == "cover_market_lifecycle" + assert msg.msg.event_type == "determined" + assert msg.msg.result == "no" + async def test_dispatch_event_fee_update_cleared(self) -> None: """Override cleared: both override fields arrive present-but-null.""" mgr = FakeSubManager() @@ -393,7 +449,9 @@ async def test_all_channel_types_have_models(self) -> None: "order_group_updates", "market_lifecycle_v2", "event_fee_update", + "milestone_updated", "multivariate_market_lifecycle", + "cover_market_lifecycle", "communications", "cfbenchmarks_value", "cfbenchmarks_value_indexlist", diff --git a/tests/ws/test_models.py b/tests/ws/test_models.py index 8792e98..a80adfb 100644 --- a/tests/ws/test_models.py +++ b/tests/ws/test_models.py @@ -30,6 +30,7 @@ RfqBatchCreatedPayload, RfqCreatedPayload, ) +from kalshi.ws.models.cover import CoverMarketLifecycleMessage from kalshi.ws.models.ebattle import ( EbattleScoresMatchlistMessage, EbattleScoresMessage, @@ -37,6 +38,7 @@ from kalshi.ws.models.fill import FillMessage, FillPayload from kalshi.ws.models.market_lifecycle import MarketLifecycleMessage from kalshi.ws.models.market_positions import MarketPositionsMessage, MarketPositionsPayload +from kalshi.ws.models.milestone import MilestoneUpdatedMessage from kalshi.ws.models.multivariate import ( MultivariateLifecycleMessage, ) @@ -833,6 +835,91 @@ def test_multivariate_lifecycle(self) -> None: assert msg.msg.title == "Test Market" +# ---------- Cover market lifecycle ---------- + + +class TestCoverMarketLifecycleModel: + def test_cover_market_lifecycle_determined(self) -> None: + raw = { + "type": "cover_market_lifecycle", + "sid": 16, + "seq": 4, + "msg": { + "market_ticker": "KXRFQRAINHOURS-35242N101831W-26DEC0106Z-12H-G0", + "determination_ts": 1796155200, + "result": "no", + "settlement_value": "0.0000", + "event_type": "determined", + }, + } + msg = CoverMarketLifecycleMessage.model_validate(raw) + assert msg.type == "cover_market_lifecycle" + assert msg.msg.event_type == "determined" + assert msg.msg.result == "no" + assert msg.msg.settlement_value == Decimal("0.0000") + assert msg.msg.additional_metadata is None + + def test_cover_market_lifecycle_created_omits_additional_metadata(self) -> None: + raw = { + "type": "cover_market_lifecycle", + "sid": 16, + "msg": { + "event_type": "created", + "market_ticker": "KXRFQ-1", + "exchange_index": 1, + "open_ts": 1700000000, + "close_ts": 1700100000, + "price_level_structure": "linear_cent", + }, + } + msg = CoverMarketLifecycleMessage.model_validate(raw) + assert msg.seq is None + assert msg.msg.exchange_index == 1 + assert msg.msg.additional_metadata is None + + +# ---------- Milestone updated ---------- + + +class TestMilestoneUpdatedModel: + def test_parse_milestone_updated(self) -> None: + raw = { + "type": "milestone_updated", + "sid": 5, + "seq": 11, + "msg": { + "milestone_id": "39e357c5-c153-5faf-89a2-59d1bb1edd72", + "last_updated_ts_us": 1796140552100001, + "milestone": { + "id": "39e357c5-c153-5faf-89a2-59d1bb1edd72", + "category": "Sports", + "type": "football_game", + "details": {"home_team_id": "abc"}, + }, + }, + } + msg = MilestoneUpdatedMessage.model_validate(raw) + assert msg.type == "milestone_updated" + assert msg.msg.milestone_id == "39e357c5-c153-5faf-89a2-59d1bb1edd72" + assert msg.msg.last_updated_ts_us == 1796140552100001 + assert msg.msg.milestone["type"] == "football_game" + assert msg.msg.milestone["details"]["home_team_id"] == "abc" + + def test_milestone_updated_no_seq(self) -> None: + raw = { + "type": "milestone_updated", + "sid": 5, + "msg": { + "milestone_id": "m1", + "last_updated_ts_us": 1, + "milestone": {}, + }, + } + msg = MilestoneUpdatedMessage.model_validate(raw) + assert msg.seq is None + assert msg.msg.milestone == {} + + # ---------- Communications ---------- From e54c2a5459dc8bbf7e25bea9e4c2c752f94c6bde Mon Sep 17 00:00:00 2001 From: Jeff West Date: Wed, 2 Dec 2026 09:58:51 -0600 Subject: [PATCH 3/4] chore(release): 22.19.0 (#594) Minor bump for the additive OpenAPI 3.39.0 spec-drift work. --- CHANGELOG.md | 37 +++++++++++++++++++++++++++++++++++++ kalshi/__init__.py | 2 +- pyproject.toml | 2 +- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc888ef..5018c6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/kalshi/__init__.py b/kalshi/__init__.py index 4b012cc..da27e08 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -559,4 +559,4 @@ "Withdrawal", ] -__version__ = "22.18.0" +__version__ = "22.19.0" diff --git a/pyproject.toml b/pyproject.toml index da93f1b..a4f6649 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "22.18.0" +version = "22.19.0" description = "A professional Python SDK for the Kalshi prediction markets and Perps (margin) APIs" readme = "README.md" license = { text = "MIT" } From 4fe0cd62d2f4afd19f95605e1d6bc0c56bb6176f Mon Sep 17 00:00:00 2001 From: Jeff West Date: Wed, 2 Dec 2026 10:24:54 -0600 Subject: [PATCH 4/4] ci: retrigger Actions on #595 Workflows did not queue on the initial PR open or reopen.