From b0a8da8d412f4cb1e7c79bfa19c098c6fc53f598 Mon Sep 17 00:00:00 2001 From: Jeff West Date: Tue, 1 Dec 2026 09:04:18 -0600 Subject: [PATCH 1/2] chore(spec): sync specs 2026-12-01 (#592) --- specs/asyncapi.yaml | 89 ++++++++++++++++++++++++++++++--------- specs/openapi.yaml | 61 ++++++++++++++++++++++++--- specs/perps_asyncapi.yaml | 41 +++++++++++++----- specs/perps_openapi.yaml | 17 +++++++- 4 files changed, 170 insertions(+), 38 deletions(-) diff --git a/specs/asyncapi.yaml b/specs/asyncapi.yaml index 2642046..6c9c162 100644 --- a/specs/asyncapi.yaml +++ b/specs/asyncapi.yaml @@ -8,7 +8,11 @@ info: This API provides multiple channels of information over a single connection. After establishing a WebSocket connection, clients can subscribe to specific channels and markets of interest. - All messages are encoded in JSON format and the communication is asynchronous. + The default connection uses JSON. The optional `kalshi.predictions.sbe.v1` subprotocol + delivers binary order book, trade, ticker, fill, user order, position, order group, RFQ, CF Benchmarks and Pyth updates. + Commands and responses to commands use JSON text on SBE connections, with requested + order book snapshots delivered in binary. See [Binary Predictions WebSocket data](https://docs.kalshi.com/websockets/binary-data) + for the XML schema and connection examples. ## Error Codes Reference @@ -169,7 +173,7 @@ channels: description: | WebSocket control frames for connection management. - Kalshi sends a Ping frame (`0x9`) with body `heartbeat` after 10 seconds without sending a data message (a JSON text frame) on the connection. + Kalshi sends a Ping frame (`0x9`) with body `heartbeat` after 10 seconds without sending a data message (text or binary) on the connection. Every data message Kalshi sends, and each heartbeat Ping, restarts that 10 seconds, so a connection that is receiving data can go a long time without a Ping. Pong frames Kalshi sends in reply to your Pings do not restart it. Do not treat a missing Ping as a dead connection; treat the connection as idle only when neither messages nor Pings arrive. @@ -2490,6 +2494,7 @@ components: target_cost_dollars: "100.0000" created_ts: "2024-12-01T10:00:00Z" mve_collection_ticker: "KXMVE-24DEC" + allowed_leg_misses: 0 mve_selected_legs: - event_ticker: "KXEVENTA-24DEC" market_ticker: "KXEVENTA-24DEC-YES" @@ -2637,6 +2642,7 @@ components: id: "rfq_batch_123" creator_id: "43fc3733603f4830a8c3b2986011a5f78d67b03b473dbfd3a3847abd85b63a51" created_ts: "2024-12-01T10:00:00Z" + allowed_leg_misses: 0 legs: - event_ticker: "KXEVENTA-24DEC" market_ticker: "KXEVENTA-24DEC-YES" @@ -4397,8 +4403,8 @@ components: position_fp: type: string description: Fixed-point net position (2 decimals) - x-rust-type: common::types::Position - x-rust-serialize-with: ws::dto::serde_money::serialize_position_fixed_point_count + x-rust-type: i64 + x-rust-serialize-with: ws::dto::serde_money::serialize_centicount_fixed_point_count position_cost_dollars: type: string description: Current cost basis of the position as a fixed-point dollar string @@ -4572,16 +4578,22 @@ components: enum: ["taker_at_cross", "maker"] created_time: type: [string, "null"] + x-rust-type: common::types::Timestamp + x-rust-serialize-with: crate::wire::serialize_optional_order_time deprecated: true description: Deprecated - Order creation time in RFC3339 format, truncated to milliseconds. Use created_ts_ms instead. format: date-time last_update_time: type: string + x-rust-type: common::types::Timestamp + x-rust-serialize-with: crate::wire::serialize_optional_order_time deprecated: true description: Deprecated - Last update time in RFC3339 format, truncated to milliseconds. Use last_updated_ts_ms instead. format: date-time expiration_time: type: string + x-rust-type: common::types::Timestamp + x-rust-serialize-with: crate::wire::serialize_optional_order_time deprecated: true description: Deprecated - Order expiration time in RFC3339 format, truncated to milliseconds. Use expiration_ts_ms instead. format: date-time @@ -4626,6 +4638,7 @@ components: description: Unique identifier for the RFQ creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the RFQ creator (pseudonymous). When obscure_creator_id is enabled, other users receive the shared placeholder "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" (SHA-256 of empty input). The creator sees their normal ID. market_ticker: type: string @@ -4641,15 +4654,25 @@ components: target_cost_dollars: type: string description: Target cost in dollars (optional) - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_option_value_dollars + x-rust-type: crate::wire::CenticentDollars created_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the RFQ was created format: date-time mve_collection_ticker: type: string description: Multivariate event collection ticker. Omitted for non-MVE RFQs. + allowed_leg_misses: + type: integer + minimum: 0 + description: >- + For an RFQ on a combo (`mve_collection_ticker` is set), the number of + selected legs that may lose while the combo still pays Yes. `0` is a + standard combo, in which every selected leg must win. A quote on a + combo whose value is above `0` must state the same value. Omitted for + non-MVE RFQs, and for a combo whose rule could not be read: do not + treat a combo without it as standard. mve_selected_legs: type: array minItems: 1 @@ -4709,6 +4732,7 @@ components: description: Unique identifier for the RFQ creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the RFQ creator (pseudonymous). When obscure_creator_id is enabled, other users receive the shared placeholder "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" (SHA-256 of empty input). The creator sees their normal ID. market_ticker: type: string @@ -4724,10 +4748,10 @@ components: target_cost_dollars: type: string description: Target cost in dollars (optional) - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_option_value_dollars + x-rust-type: crate::wire::CenticentDollars deleted_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the RFQ was deleted format: date-time rfq_batch_id: @@ -4759,9 +4783,11 @@ components: description: Identifier of the RFQ this quote is for quote_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the quote creator (anonymized) rfq_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the RFQ creator (pseudonymous). When obscure_creator_id is enabled, other users receive the shared placeholder "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" (SHA-256 of empty input). The creator sees their normal ID. On a quote on a child RFQ of an RFQ batch, always the placeholder. market_ticker: type: string @@ -4792,10 +4818,10 @@ components: rfq_target_cost_dollars: type: string description: Target cost from the RFQ in dollars (optional) - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_option_value_dollars + x-rust-type: crate::wire::CenticentDollars created_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the quote was created format: date-time subaccount: @@ -4829,9 +4855,11 @@ components: description: Identifier of the RFQ this quote is for quote_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the quote creator (anonymized) rfq_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the RFQ creator (pseudonymous). When obscure_creator_id is enabled, other users receive the shared placeholder "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" (SHA-256 of empty input). The creator sees their normal ID. On a quote on a child RFQ of an RFQ batch, always the placeholder. market_ticker: type: string @@ -4871,8 +4899,7 @@ components: rfq_target_cost_dollars: type: string description: Target cost from the RFQ in dollars (optional) - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_option_value_dollars + x-rust-type: crate::wire::CenticentDollars subaccount: type: integer description: | @@ -4904,9 +4931,11 @@ components: description: Identifier of the RFQ this quote was for quote_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Anonymized identifier for the quote creator rfq_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Anonymized identifier for the RFQ creator order_id: type: string @@ -4919,6 +4948,7 @@ components: description: Market ticker for the executed quote executed_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the quote was executed and orders were placed format: date-time subaccount: @@ -4953,11 +4983,22 @@ components: description: Unique identifier for the RFQ batch creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the batch creator (pseudonymous). When obscure_creator_id is enabled, other users receive the shared placeholder "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" (SHA-256 of empty input). The creator sees their normal ID. created_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the RFQ batch was created format: date-time + allowed_leg_misses: + type: integer + minimum: 0 + description: >- + The number of selected legs that may lose while each child combo still + pays Yes; every child of a batch shares one value. `0` is a standard + combo. A batch quote must state the same value when it is above `0`. + Omitted when the rule could not be read: do not treat the batch's + combos as standard then. legs: type: array description: Distinct legs across the batch's combos, each listed once @@ -5004,8 +5045,7 @@ components: target_cost_dollars: type: string description: Target cost in dollars (optional) - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_option_value_dollars + x-rust-type: crate::wire::CenticentDollars mve_collection_ticker: type: string description: Multivariate event collection ticker (optional) @@ -5037,6 +5077,7 @@ components: description: Unique identifier for the RFQ batch creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the batch creator, obscured as in rfq_batch_created rfq_ids: type: array @@ -5045,6 +5086,7 @@ components: type: string deleted_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the RFQ batch closed format: date-time sending_ts_ms: @@ -5073,9 +5115,11 @@ components: description: Identifier of the RFQ batch this batch quote prices quote_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Your public communications ID as the batch quote creator created_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the batch quote was created format: date-time quotes: @@ -5120,8 +5164,7 @@ components: rfq_target_cost_dollars: type: string description: Target cost from the child RFQ in dollars (optional) - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_option_value_dollars + x-rust-type: crate::wire::CenticentDollars subaccount: type: integer description: | @@ -5158,6 +5201,7 @@ components: description: Increases with every snapshot of this batch. Apply a snapshot only if its version is greater than the last one you applied. updated_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when a best bid last changed format: date-time yes_complete: @@ -5210,8 +5254,7 @@ components: rfq_target_cost_dollars: type: string description: Target cost from the child RFQ in dollars (optional) - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_option_value_dollars + x-rust-type: crate::wire::CenticentDollars subaccount: type: integer description: | @@ -5243,9 +5286,11 @@ components: description: Identifier of the RFQ batch quote_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Your public communications ID as the batch quote creator rfq_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the RFQ batch creator, obscured as in quote_accepted accepted_side: type: string @@ -5253,6 +5298,7 @@ components: enum: ["yes", "no"] accepted_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the RFQ batch was accepted format: date-time quotes: @@ -5302,8 +5348,7 @@ components: rfq_target_cost_dollars: type: string description: Target cost from the child RFQ in dollars (optional) - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_option_value_dollars + x-rust-type: crate::wire::CenticentDollars subaccount: type: integer description: | @@ -5335,6 +5380,7 @@ components: description: The client_batch_id you gave when creating the batch. Omitted when none was given. rfq_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Your public communications ID as the RFQ batch creator executed_rfq_ids: type: array @@ -5348,6 +5394,7 @@ components: type: string executed_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the last child finished format: date-time close_reason: @@ -5384,6 +5431,7 @@ components: description: Identifier of the RFQ batch rfq_creator_id: type: string + x-rust-type: crate::wire::PublicCommunicationsId description: Public communications ID of the RFQ batch creator. When the creator obscured their ID, it is revealed only if at least one of your children executed. executed_rfq_ids: type: array @@ -5397,6 +5445,7 @@ components: type: string executed_ts: type: string + x-rust-type: crate::wire::RfqTimestamp description: Timestamp when the last child of the batch finished format: date-time close_reason: diff --git a/specs/openapi.yaml b/specs/openapi.yaml index f649d8f..1f881bc 100644 --- a/specs/openapi.yaml +++ b/specs/openapi.yaml @@ -1753,7 +1753,7 @@ paths: operationId: IntraExchangeInstanceTransfer summary: Intra Account Transfer description: | - Transfers funds within the same account. + Transfers your funds between exchange shards, or between your Predictions and Perps accounts. Transfers between the Predictions and Perps accounts are not available to FCM members or self-clearing members. Subaccount-restricted API keys can only transfer between `event_contract` exchange indices, with `source_subaccount` and `destination_subaccount` both set to the key's subaccount. @@ -3083,7 +3083,7 @@ paths: '404': $ref: '#/components/responses/NotFoundError' '409': - $ref: '#/components/responses/ConflictError' + $ref: '#/components/responses/CreateQuoteConflict' '500': $ref: '#/components/responses/InternalServerError' @@ -3291,6 +3291,8 @@ paths: $ref: '#/components/responses/BadRequestError' '401': $ref: '#/components/responses/UnauthorizedError' + '409': + $ref: '#/components/responses/CreateQuoteConflict' '500': $ref: '#/components/responses/InternalServerError' @@ -5924,6 +5926,18 @@ components: application/json: schema: $ref: '#/components/schemas/ErrorResponse' + CreateQuoteConflict: + description: The quote conflicts with the RFQ state or quoting is restricted for the maker. + headers: + X-Retry-After: + description: For a temporary quote_timed_out restriction, the remaining delay before retrying, rounded up to whole seconds. + schema: + type: integer + minimum: 0 + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' ConflictError: description: Conflict - resource already exists or cannot be modified content: @@ -9416,8 +9430,8 @@ components: IntraExchangeInstanceTransferStatus: type: string - enum: ['pending', 'complete'] - x-enum-varnames: ['IntraExchangeInstanceTransferStatusPending', 'IntraExchangeInstanceTransferStatusComplete'] + enum: ['pending', 'complete', 'failed'] + x-enum-varnames: ['IntraExchangeInstanceTransferStatusPending', 'IntraExchangeInstanceTransferStatusComplete', 'IntraExchangeInstanceTransferStatusFailed'] description: Transfer status. IntraExchangeInstanceTransfer: @@ -9864,6 +9878,17 @@ components: $ref: '#/components/schemas/MveSelectedLeg' description: Selected legs for the MVE collection x-go-type-skip-optional-pointer: true + allowed_leg_misses: + type: integer + minimum: 0 + description: >- + For an RFQ on a combo (`mve_collection_ticker` is set), the number of selected legs that may lose + while the combo still pays Yes. `0` is a standard combo, in which every selected leg must win. With + `1`, a combo of N legs pays Yes when at least N-1 legs win. The value is a property of the + collection and never changes. Present on every combo RFQ and omitted otherwise, except for a combo + whose collection no longer exists: its rule is unknown, the field is omitted, and quotes on it are + refused. Price a combo from this value, not from the collection ticker's name, and do not treat a + combo without it as standard. rest_remainder: type: boolean description: Whether to rest the remainder of the RFQ after execution @@ -10158,6 +10183,14 @@ components: subaccount: type: integer description: Optional subaccount number to place the quote under (0 for primary, 1-63 for subaccounts) + allowed_leg_misses: + type: integer + minimum: 0 + description: >- + The `allowed_leg_misses` of the RFQ, as you priced it. Required when that value is above `0`: a quote on a + combo that allows leg misses is rejected with `allowed_leg_misses_required` unless it states the + same value, and with `allowed_leg_misses_mismatch` if it states another. Optional otherwise; `0` + and omitting it mean the same. CreateQuoteResponse: type: object @@ -10485,6 +10518,14 @@ components: subaccount: type: integer description: Optional subaccount number to place the batch quote under (0 for primary, 1-63 for subaccounts) + allowed_leg_misses: + type: integer + minimum: 0 + description: >- + The `allowed_leg_misses` of the batch's child RFQs, as you priced it. Required when that value is above `0`: a quote on a + combo that allows leg misses is rejected with `allowed_leg_misses_required` unless it states the + same value, and with `allowed_leg_misses_mismatch` if it states another. Optional otherwise; `0` + and omitting it mean the same. CreateRFQBatchQuoteResponse: type: object @@ -11502,7 +11543,8 @@ components: description: '[DEPRECATED - Use associated_events instead] A list of events associated with the collection. Markets in these events can be passed as inputs to the Create endpoint.' is_ordered: type: boolean - description: Whether the collection is ordered. If true, the order of markets passed into Create affects the output. If false, the order does not matter. + deprecated: true + description: Legacy field. Always false. is_single_market_per_event: type: boolean description: '[DEPRECATED - Use associated_events instead] Whether the collection accepts multiple markets from the same event passed into Create.' @@ -13141,6 +13183,15 @@ components: items: $ref: '#/components/schemas/MveSelectedLeg' x-go-type-skip-optional-pointer: true + allowed_leg_misses: + type: integer + minimum: 0 + description: >- + For a combo market (`mve_collection_ticker` is set), the number of selected legs that may lose + while the market still resolves Yes. `0` is a standard combo, in which every selected leg must win. + The value is a property of the collection and never changes. Present on every combo market and + omitted otherwise, except for a combo whose collection no longer exists: its rule is unknown and + the field is omitted. Do not treat a combo without it as standard. primary_participant_key: type: string nullable: true diff --git a/specs/perps_asyncapi.yaml b/specs/perps_asyncapi.yaml index c277ffd..b16a313 100644 --- a/specs/perps_asyncapi.yaml +++ b/specs/perps_asyncapi.yaml @@ -5,6 +5,10 @@ info: description: | WebSocket API for receiving real-time market data notifications and updates on Kalshi perps markets. + JSON is the default. Offer `kalshi.margin.sbe.v1` to receive binary data for order books, + trades, tickers, fills, user orders and order-group updates. Commands and control responses + use JSON text. See [Binary Margin WebSocket data](/margin-ws/websockets/binary-data). + Supported channels: - `orderbook_delta` - `ticker` @@ -58,7 +62,8 @@ channels: title: WebSocket Connection description: | Main WebSocket connection endpoint. - Authentication is required during the WebSocket handshake. + Authentication is required during the WebSocket handshake. Clients requesting binary data + should verify the HTTP 101 response echoes `Sec-WebSocket-Protocol: kalshi.margin.sbe.v1`. bindings: ws: method: GET @@ -90,7 +95,8 @@ channels: address: / title: Connection Keep-Alive description: | - Kalshi sends Ping frames every 10 seconds with body `heartbeat`. + Kalshi sends a Ping frame (`0x9`) with body `heartbeat` after 10 seconds without sending a text or binary data message on the connection. + Every data message Kalshi sends, and each heartbeat Ping, restarts that 10 seconds, so a connection that is receiving data can go a long time without a Ping. Clients should respond with Pong frames. messages: incomingPing: @@ -175,7 +181,14 @@ channels: price, top-of-book size, volume, open-interest, and optional reference/mark prices. Messages are coalesced to at most one per market per second (latest value wins - within the window). + within the window). Funding rate and `settlement_mark_price` refreshes do not send a + message on their own; the market's next message carries them. + + Set `send_initial_snapshot` on `subscribe`, or on `update_subscription` with `add_markets`, + to get the current values, when available, of each market in that command's `market_ticker` + or `market_tickers`. A subscription that names no markets covers every market but gets no + initial snapshot. Seed it from `GET /margin/markets`, which has every ticker value except + `funding_rate` and `last_trade_size_fp`. Requirements: - no additional channel-level auth beyond the authenticated WebSocket connection @@ -876,7 +889,7 @@ components: minItems: 1 send_initial_snapshot: type: boolean - description: Sends an initial snapshot for ticker subscriptions. + description: Sends an initial snapshot, when available, for each market named in `market_ticker` or `market_tickers` on ticker subscriptions. A ticker subscription that names no markets gets none. default: false skip_ticker_ack: type: boolean @@ -1368,13 +1381,20 @@ components: type: string description: Total notional value of one sided open interest in dollars. reference_price: - description: Underlying reference index value scaled to one contract, when available (CF Benchmarks for crypto perps; Pyth for metals, commodities, and other Pyth-indexed perps). ts_ms is the index source timestamp. + description: Underlying reference price scaled to one contract, from the market's underlying price source, when available. ts_ms is the source timestamp. allOf: - $ref: '#/components/schemas/tickerPrice' settlement_mark_price: - $ref: '#/components/schemas/tickerPrice' + description: | + Running estimate of the settlement mark price, refreshed every few seconds. + The mark applied at each 12:00 PM and 4:00 PM ET settlement is computed separately at that time and can differ from this estimate. + Clearing members can read the applied marks from [`GET /margin/settlement_prices`](/api-reference/get-settlement-prices). + allOf: + - $ref: '#/components/schemas/tickerPrice' liquidation_mark_price: - $ref: '#/components/schemas/tickerPrice' + description: Last published mark price used for margin and liquidation. ts_ms is when it was published. + allOf: + - $ref: '#/components/schemas/tickerPrice' funding_rate: $ref: '#/components/schemas/fundingRate' ts_ms: @@ -1465,12 +1485,11 @@ components: x-rust-serialize-with: ws::dto::serde_money::serialize_amount_fixed_point_count fee_cost: type: string - x-rust-type: common::types::Value - x-rust-serialize-with: ws::dto::serde_money::serialize_value_dollars + x-rust-type: crate::wire::CenticentDollars post_position: type: string - x-rust-type: common::types::Position - x-rust-serialize-with: ws::dto::serde_money::serialize_position_fixed_point_count + x-rust-type: i64 + x-rust-serialize-with: ws::dto::serde_money::serialize_centicount_fixed_point_count subaccount: type: integer subaccount_type: diff --git a/specs/perps_openapi.yaml b/specs/perps_openapi.yaml index 6e002cd..4fe8b2e 100644 --- a/specs/perps_openapi.yaml +++ b/specs/perps_openapi.yaml @@ -1543,7 +1543,7 @@ paths: post: operationId: IntraExchangeInstanceTransfer summary: Intra Account Transfer - description: "Endpoint for transferring funds within the same account. Transfers out of the margin balance are refused with HTTP 403 and error code `permission_denied` (details: `margin withdrawals are temporarily disabled during settlement and funding`) from shortly before each scheduled settlement or funding run until that run has been processed, and while a cash corporate action is being processed. The details text is the same in each case. Retry with a backoff until the transfer is accepted." + description: "Endpoint for transferring funds between your Predictions and Perps accounts. It is not available to FCM members or self-clearing members. Transfers out of the margin balance are refused with HTTP 403 and error code `permission_denied` (details: `margin withdrawals are temporarily disabled during settlement and funding`) from shortly before each scheduled settlement or funding run until that run has been processed, and while a cash corporate action is being processed. The details text is the same in each case. Retry with a backoff until the transfer is accepted." tags: - portfolio security: @@ -3418,6 +3418,10 @@ components: type: string title: type: string + expiration_ts: + type: string + format: date-time + description: Scheduled expiration time in RFC 3339 format. Omitted for markets without an expiration. market_version: type: integer format: int32 @@ -3495,6 +3499,12 @@ components: volume_24h: $ref: '#/components/schemas/FixedPointCount' description: One sided trade volume in the last 24 hours. + taker_long_volume_24h: + $ref: '#/components/schemas/FixedPointCount' + description: Number of contracts traded in the last 24 hours where the taker was the buyer. + taker_short_volume_24h: + $ref: '#/components/schemas/FixedPointCount' + description: Number of contracts traded in the last 24 hours where the taker was the seller. volume_24h_notional_value_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Total notional value of one sided trade volume in the last 24 hours in dollars. @@ -3512,7 +3522,10 @@ components: description: Total number of contracts resting at the best ask price, as a fixed-point count string. Zero when there is no ask. Omitted when market stats are unavailable. settlement_mark_price: $ref: '#/components/schemas/TickerPrice' - description: Mark price used for settlement and funding. + description: > + Running estimate of the settlement mark price, refreshed every few seconds. + The mark applied at each 12:00 PM and 4:00 PM ET settlement is computed separately at that time and can differ from this estimate. + Clearing members can read the applied marks from [`GET /margin/settlement_prices`](/api-reference/get-settlement-prices). liquidation_mark_price: $ref: '#/components/schemas/TickerPrice' description: Mark price used for liquidation. From b38b30adbd742f967eaf1724899dd3dbc173c04a Mon Sep 17 00:00:00 2001 From: Jeff West Date: Tue, 1 Dec 2026 09:29:10 -0600 Subject: [PATCH 2/2] =?UTF-8?q?feat(communications):=20allowed=5Fleg=5Fmis?= =?UTF-8?q?ses,=20X-Retry-After,=20failed=20transfer=20status,=20perps=20m?= =?UTF-8?q?arket=20fields=20(#592)=20=E2=80=94=2022.18.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 43 +++++++++++++++ docs/errors.md | 2 +- docs/migration.md | 4 +- docs/perps.md | 12 ++++- docs/resources/communications.md | 14 +++++ docs/resources/markets.md | 6 +++ docs/resources/multivariate.md | 4 ++ docs/resources/portfolio.md | 5 ++ docs/retries.md | 5 ++ kalshi/__init__.py | 2 +- kalshi/_base_client.py | 79 +++++++++++++++++----------- kalshi/_contract_map.py | 4 ++ kalshi/errors.py | 16 ++++-- kalshi/models/communications.py | 11 ++++ kalshi/models/markets.py | 3 ++ kalshi/models/multivariate.py | 8 ++- kalshi/models/portfolio.py | 2 +- kalshi/perps/models/markets.py | 12 +++++ kalshi/perps/models/transfers.py | 5 +- kalshi/perps/resources/transfers.py | 15 +++--- kalshi/perps/ws/models/ticker.py | 5 ++ kalshi/resources/communications.py | 50 ++++++++++++++++++ kalshi/ws/models/__init__.py | 2 + kalshi/ws/models/communications.py | 21 ++++++++ pyproject.toml | 2 +- tests/perps/test_markets.py | 30 +++++++++++ tests/test_client.py | 51 ++++++++++++++++++ tests/test_communications.py | 81 +++++++++++++++++++++++++++++ tests/test_models.py | 5 ++ tests/test_portfolio.py | 6 +++ tests/ws/test_models.py | 37 +++++++++++++ 31 files changed, 488 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b8d46d3..fc888ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,49 @@ All notable changes to kalshi-sdk will be documented in this file. +## 22.18.0 — 2026-12-01 + +Reconciles nightly spec drift (#592). Additive only. No breaking changes. + +### Added + +- Combo **`allowed_leg_misses`** (`int | None`, `>= 0`) on `RFQ`, `Market`, + `CreateQuoteRequest`, `CreateRFQBatchQuoteRequest`, WS `RfqCreatedPayload`, + and WS `RfqBatchCreatedPayload`. Present on combo RFQs/markets; omitted for + non-combo and for combos whose collection no longer exists — do not treat a + missing value on a combo as standard. Quote create kwargs + (`quotes.create` / `rfq_batches.quotes.create`, sync and async) forward it + and send it only when set. Required by the server when the RFQ's (or + batch's) `allowed_leg_misses` is greater than 0; otherwise rejected with + `allowed_leg_misses_required` / `allowed_leg_misses_mismatch`. `0` and + omitted mean the same. +- `IntraExchangeInstanceTransferStatusLiteral` gains `"failed"` + (`"pending"`, `"complete"`, `"failed"`). +- Quote-create 409 (`quote_timed_out`) may send **`X-Retry-After`** (integer + seconds). `_parse_retry_after` falls back to it when `Retry-After` is + absent; `KalshiConflictError.retry_after` is populated. POST is never + retried and 409 is not retryable. +- Perps **`MarginMarket.expiration_ts`** (`AwareDatetime | None`; omitted for + markets without an expiration) and optional + **`taker_long_volume_24h` / `taker_short_volume_24h`** (FixedPointCount, + `_fp` alias like `volume_24h`). + +### Changed + +- `MultivariateEventCollection.is_ordered` is a legacy field (always false); + kept as-is under deprecated fields. + +### Docs + +- Combo `allowed_leg_misses` on quotes, RFQs, and markets; quote 409 + `X-Retry-After`. +- Perps intra-exchange transfer is between your Predictions and Perps + accounts; not available to FCM members or self-clearing members. +- Perps `settlement_mark_price` is a running estimate refreshed every few + seconds; applied 12:00 PM / 4:00 PM ET marks can differ (see + `GET /margin/settlement_prices`). Ticker WS `liquidation_mark_price` is + the last published mark used for margin and liquidation. + ## 22.17.0 — 2026-11-26 Reconciles nightly spec drift (#590). Additive only. No breaking changes. diff --git a/docs/errors.md b/docs/errors.md index a8c2774..8ebf056 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -48,7 +48,7 @@ leave it `None`. | `400` | `KalshiValidationError` | `.details` is populated from `body["details"]` or `body["errors"]` when present and dict-shaped. | | `401` / `403` | `KalshiAuthError` | Bad signature, expired key, missing scope. | | `404` | `KalshiNotFoundError` | Unknown ticker, missing order, etc. | -| `409` | `KalshiConflictError` | Duplicate `client_order_id` or other state conflict. | +| `409` | `KalshiConflictError` | Duplicate `client_order_id` or other state conflict. Quote create may send `X-Retry-After` (integer seconds) for a temporary `quote_timed_out` restriction; `.retry_after` is populated from `Retry-After` when present, else `X-Retry-After`. 409 is not retried. | | `429` | `KalshiRateLimitError` | `.retry_after` parsed from the `Retry-After` header if it's a non-negative finite numeric (HTTP-date form falls back to computed backoff). | | `5xx` | `KalshiServerError` | All server-side failures. | | anything else | `KalshiError` | Catch-all, with `status_code` set. | diff --git a/docs/migration.md b/docs/migration.md index 776e9d3..f5e3a5f 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -796,7 +796,9 @@ Syncs the SDK to OpenAPI/AsyncAPI spec **3.25.0**. **No breaking changes.** - Core OpenAPI lists `POST /portfolio/intra_exchange_instance_transfer`, still marked **currently not available**. The core client does not expose it; use - `PerpsClient.transfers.transfer_instance()` on the margin product. + `PerpsClient.transfers.transfer_instance()` on the margin product + (Predictions ↔ Perps; not available to FCM members or self-clearing + members). See the [changelog](https://github.com/TexasCoding/kalshi-python-sdk/blob/main/CHANGELOG.md) for the full list. diff --git a/docs/perps.md b/docs/perps.md index e4e1c2e..75fe994 100644 --- a/docs/perps.md +++ b/docs/perps.md @@ -65,7 +65,7 @@ async with AsyncPerpsClient.from_env(demo=True) as perps: | `portfolio` | `positions()`, `fills()` / `fills_all()`, `trades()` / `trades_all()`, cross/isolated exit triggers | | `margin` | `balance()`, `risk()`, `notional_risk_limit()`, `fee_tiers()`, `fee_tier_rates()`, `api_limits()`, `corporate_actions()`, `corporate_action_payment_history()` | | `funding` | `rate_estimate()`, `historical_rates()`, `premium_index()`, `history()` | -| `transfers` | `transfer_instance()`, `create_subaccount()`, `transfer_subaccount()` | +| `transfers` | `transfer_instance()` (Predictions ↔ Perps; not available to FCM members or self-clearing members), `create_subaccount()`, `transfer_subaccount()` | | `fcm` | `create_subtrader(subtrader_suffix=..., require_category_cap=...)`; `risk_controls` / `update_risk_controls` / `delete_risk_controls`; `update_notional_risk_limit` / `delete_notional_risk_limit`; `transfer_position(...)` | `markets.bulk_orderbooks(*, tickers)` fetches up to 100 margin orderbooks @@ -226,6 +226,10 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id) `"corporate_action"`, …). Empty means the market is not halted or the reason has not been observed — do not read empty as proof the market is live. + `MarginMarket.expiration_ts` (`AwareDatetime | None`) is omitted for + markets without an expiration. Optional `taker_long_volume_24h` / + `taker_short_volume_24h` are 24h taker-side contract counts typed like + `volume_24h` (`FixedPointCount | None`, `_fp` alias accepted). - **Mark prices** (since the v3.21.0 spec sync) — `MarginMarket` carries three optional reference-price objects: `settlement_mark_price`, `liquidation_mark_price`, and `reference_price`, each a nested `TickerPrice` @@ -233,6 +237,12 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id) (`DollarDecimal`, a `FixedPointDollars` USD string) and `ts_ms` (the source timestamp in epoch **milliseconds**, `int`). All three are absent from the spec `required` list, so they are `None` when the upstream price is unavailable. + `settlement_mark_price` is a running estimate refreshed every few seconds; + the mark applied at 12:00 PM / 4:00 PM ET can differ — see + `GET /margin/settlement_prices`. On the ticker WS payload, + `liquidation_mark_price` is the last published mark used for margin and + liquidation; `reference_price` is the underlying reference scaled to one + contract, from the market's underlying price source, when available. - **Exchange shard** (SDK v11.0.0) — `MarginMarket.exchange_index` (`int`) is required; order groups may only reference markets that share their `exchange_index`. diff --git a/docs/resources/communications.md b/docs/resources/communications.md index 9a062ab..74ab7af 100644 --- a/docs/resources/communications.md +++ b/docs/resources/communications.md @@ -91,6 +91,7 @@ resp = client.communications.quotes.create( yes_bid="0.60", no_bid="0.40", rest_remainder=False, + allowed_leg_misses=1, # required when the RFQ's allowed_leg_misses > 0 ) # 3) Wait for the counterparty to accept. @@ -288,6 +289,19 @@ suffix), matching `quotes.create()`. Accept `min_bids` use Python name no size of its own) or on each `CreateRFQBatchChild`. `rest_remainder` must be false: a batch executes as one fill-or-kill. +`allowed_leg_misses` (`int | None`, optional, `>= 0`) is the combo rule +on `RFQ` and on `quotes.create` / `rfq_batches.quotes.create`. On an RFQ +it is present for every combo and omitted otherwise, except when the +combo's collection no longer exists — then the field is omitted and +quotes on it are refused. Do not treat a combo without it as standard. +On a quote it is required by the server when the RFQ's (or batch's) +`allowed_leg_misses` is greater than 0; otherwise the server rejects with +`allowed_leg_misses_required` / `allowed_leg_misses_mismatch`. `0` and +omitted mean the same. Sent only when set. Combo `Market` rows carry the +same optional field. A 409 on quote create may include `X-Retry-After` +(seconds) for a temporary `quote_timed_out` restriction; see +[Errors](../errors.md). + ## Migrating from v2.x | v2.x (deprecated) | v3.0.0 (canonical) | diff --git a/docs/resources/markets.md b/docs/resources/markets.md index e3d38c8..3c8b5fb 100644 --- a/docs/resources/markets.md +++ b/docs/resources/markets.md @@ -27,6 +27,12 @@ recent trades. | `flight_disruption_availability()` | `GET /flight_disruption_markets/availability` | no | | `list_flights(*, carrier, flight_number, date)` | `GET /flight_disruption_markets/flights` | **yes** | +Combo markets (`mve_collection_ticker` set) may include +`allowed_leg_misses` (`int | None`): how many selected legs may lose while +the market still resolves Yes. `0` is a standard combo. Omitted for +non-combo markets and for combos whose collection no longer exists — do +not treat a missing value on a combo as standard. + !!! warning "Orderbook endpoints require auth" `orderbook()` and `bulk_orderbooks()` raise `AuthRequiredError` on an unauthenticated client. The rest of the market-data surface is public. diff --git a/docs/resources/multivariate.md b/docs/resources/multivariate.md index 3ff1a65..d21ab7f 100644 --- a/docs/resources/multivariate.md +++ b/docs/resources/multivariate.md @@ -51,6 +51,10 @@ Each collection includes required `price_level_structure` (`str`) and `price_ranges` (list of `{start, end, step}` dicts) describing the price bands used for **new** markets created in the collection. Existing markets may differ — use the minted `Market`'s fields for its current pricing. +`is_ordered` is a legacy field (always false) and is still returned. + +Combo `Market` rows may include `allowed_leg_misses`; see +[Communications](communications.md) and [Markets](markets.md). ## Select legs diff --git a/docs/resources/portfolio.md b/docs/resources/portfolio.md index 1508e8e..e89e735 100644 --- a/docs/resources/portfolio.md +++ b/docs/resources/portfolio.md @@ -280,6 +280,11 @@ print(t.status, t.created_ts) `IntraExchangeInstanceTransfer.amount` is a fixed-point dollar `DollarDecimal` (not the integer centicents used on the POST create body). +`status` is `"pending"`, `"complete"`, or `"failed"`. + +`PerpsClient.transfers.transfer_instance()` moves funds between your +Predictions and Perps accounts; it is not available to FCM members or +self-clearing members. ## Target balance allocation diff --git a/docs/retries.md b/docs/retries.md index 6415eda..8a4cffb 100644 --- a/docs/retries.md +++ b/docs/retries.md @@ -56,6 +56,11 @@ The header is only honored when it parses as a non-negative finite number. `Retry-After: 0` is honored (sleeps 0). HTTP-date form, `NaN`, negatives, and non-numeric values fall back to the computed full-jitter backoff. +When `Retry-After` is absent, `X-Retry-After` is parsed the same way as +delta-seconds (quote create 409 `quote_timed_out`). `Retry-After` wins +when both are present. 409 is never retried; POST is never retried. The +hint is on `KalshiConflictError.retry_after` for the caller. + When retries are exhausted, the last `KalshiRateLimitError` is raised with `.retry_after` populated from the header — so application-level retry logic can see the hint. diff --git a/kalshi/__init__.py b/kalshi/__init__.py index 0a4b5a0..f937534 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -553,4 +553,4 @@ "Withdrawal", ] -__version__ = "22.17.0" +__version__ = "22.18.0" diff --git a/kalshi/_base_client.py b/kalshi/_base_client.py index 2e47492..36fef50 100644 --- a/kalshi/_base_client.py +++ b/kalshi/_base_client.py @@ -98,7 +98,11 @@ def _map_error(response: httpx.Response) -> KalshiError: if status == 404: return KalshiNotFoundError(message=message, status_code=status) if status == 409: - return KalshiConflictError(message=message, status_code=status) + return KalshiConflictError( + message=message, + status_code=status, + retry_after=_parse_retry_after(response), + ) if status in (408, 429, 504) or status >= 500: retry_after_val = _parse_retry_after(response) if status == 429: @@ -120,39 +124,54 @@ def _map_error(response: httpx.Response) -> KalshiError: return KalshiError(message=message, status_code=status) -def _parse_retry_after(response: httpx.Response) -> float | None: - """Parse RFC 7231 §7.1.3 Retry-After to seconds; ``None`` if absent/unparseable (#267, #322).""" - raw = response.headers.get("Retry-After") - if not raw: - return None +def _parse_delta_seconds(raw: str) -> float | None: + """Parse a Retry-After / X-Retry-After delta-seconds value.""" try: val = float(raw) - if not math.isfinite(val): - return None - if val < 0: - return 0.0 - return val except ValueError: - pass - # RFC 7231 §7.1.3: Retry-After may also be an HTTP-date. - try: - dt = email.utils.parsedate_to_datetime(raw) - except (TypeError, ValueError): - dt = None - if dt is None: - logger.debug( - "Retry-After %r is neither delta-seconds nor HTTP-date; " - "falling back to computed backoff", - raw, - ) return None - # RFC 5322 dates without a tz are interpreted as UTC by - # parsedate_to_datetime; ensure aware before subtracting. - if dt.tzinfo is None: - dt = dt.replace(tzinfo=UTC) - delta = (dt - datetime.now(tz=UTC)).total_seconds() - # Clamp negatives (date in the past) to 0 — retry immediately. - return max(0.0, delta) + if not math.isfinite(val): + return None + if val < 0: + return 0.0 + return val + + +def _parse_retry_after(response: httpx.Response) -> float | None: + """Parse RFC 7231 §7.1.3 Retry-After to seconds; ``None`` if absent/unparseable (#267, #322). + + When ``Retry-After`` is absent, falls back to ``X-Retry-After`` using the + same delta-seconds parsing (quote 409 ``quote_timed_out``). A present but + unparseable ``Retry-After`` does not fall back. + """ + raw = response.headers.get("Retry-After") + if raw: + delta = _parse_delta_seconds(raw) + if delta is not None: + return delta + # RFC 7231 §7.1.3: Retry-After may also be an HTTP-date. + try: + dt = email.utils.parsedate_to_datetime(raw) + except (TypeError, ValueError): + dt = None + if dt is None: + logger.debug( + "Retry-After %r is neither delta-seconds nor HTTP-date; " + "falling back to computed backoff", + raw, + ) + return None + # RFC 5322 dates without a tz are interpreted as UTC by + # parsedate_to_datetime; ensure aware before subtracting. + if dt.tzinfo is None: + dt = dt.replace(tzinfo=UTC) + http_delta = (dt - datetime.now(tz=UTC)).total_seconds() + # Clamp negatives (date in the past) to 0 — retry immediately. + return max(0.0, http_delta) + x_raw = response.headers.get("X-Retry-After") + if not x_raw: + return None + return _parse_delta_seconds(x_raw) def _compute_backoff(attempt: int, config: KalshiConfig) -> float: diff --git a/kalshi/_contract_map.py b/kalshi/_contract_map.py index 8589f00..f6e15b3 100644 --- a/kalshi/_contract_map.py +++ b/kalshi/_contract_map.py @@ -847,6 +847,10 @@ class ContractEntry: spec_schema="rfqCreatedPayload", notes="Spec has mve_collection_ticker, mve_selected_legs not in SDK", ), + ContractEntry( + sdk_model="kalshi.ws.models.communications.RfqBatchCreatedPayload", + spec_schema="rfqBatchCreatedPayload", + ), ContractEntry( sdk_model="kalshi.ws.models.communications.RfqDeletedPayload", spec_schema="rfqDeletedPayload", diff --git a/kalshi/errors.py b/kalshi/errors.py index b5d8cea..4939c89 100644 --- a/kalshi/errors.py +++ b/kalshi/errors.py @@ -9,10 +9,11 @@ class KalshiError(Exception): """Base exception for all Kalshi SDK errors. ``retry_after`` carries the server's RFC 7231 §7.1.3 Retry-After hint - (parsed to seconds) when present. Populated for 408/429/503/504 and - other retryable 5xx responses; ``None`` otherwise. The transport - retry loop reads it via plain attribute access regardless of error - subclass (#322). + (parsed to seconds) when present, or ``X-Retry-After`` (delta-seconds) + when ``Retry-After`` is absent. Populated for 408/429/409/503/504 and + other retryable 5xx responses; ``None`` otherwise. 409 is not retryable + — the hint is for the caller. The transport retry loop reads it via + plain attribute access regardless of error subclass (#322). """ def __init__( @@ -67,7 +68,12 @@ class KalshiRateLimitError(KalshiError): class KalshiConflictError(KalshiError): - """409 Conflict (e.g., duplicate ``client_order_id``).""" + """409 Conflict (e.g., duplicate ``client_order_id``). + + Quote create may send ``X-Retry-After`` (seconds) for a temporary + ``quote_timed_out`` restriction; ``retry_after`` is populated then. + POST is never retried and 409 is not retryable. + """ class KalshiTimeoutError(KalshiError): diff --git a/kalshi/models/communications.py b/kalshi/models/communications.py index c279d0a..d18ce9c 100644 --- a/kalshi/models/communications.py +++ b/kalshi/models/communications.py @@ -53,6 +53,9 @@ class RFQ(BaseModel): ) mve_collection_ticker: str | None = None mve_selected_legs: list[MveSelectedLeg] | None = None + # Combo-only. Omitted for non-combo and for combos whose collection no + # longer exists — do not treat a missing value on a combo as standard. + allowed_leg_misses: int | None = None rest_remainder: bool | None = None cancellation_reason: str | None = None creator_user_id: str | None = None @@ -219,6 +222,10 @@ class CreateQuoteRequest(BaseModel): rest_remainder: bool subaccount: StrictInt | None = Field(default=None, ge=0) post_only: bool | None = None + # Required by the server when the RFQ's allowed_leg_misses > 0 (else + # rejected with allowed_leg_misses_required / allowed_leg_misses_mismatch); + # 0 and omitted mean the same. + allowed_leg_misses: int | None = Field(default=None, ge=0) model_config = {"extra": "forbid"} @@ -502,6 +509,10 @@ class CreateRFQBatchQuoteRequest(BaseModel): rest_remainder: bool post_only: bool | None = None subaccount: StrictInt | None = Field(default=None, ge=0) + # Required by the server when the batch's allowed_leg_misses > 0 (else + # rejected with allowed_leg_misses_required / allowed_leg_misses_mismatch); + # 0 and omitted mean the same. + allowed_leg_misses: int | None = Field(default=None, ge=0) model_config = {"extra": "forbid"} diff --git a/kalshi/models/markets.py b/kalshi/models/markets.py index cffb1b1..2a89048 100644 --- a/kalshi/models/markets.py +++ b/kalshi/models/markets.py @@ -138,6 +138,9 @@ class Market(BaseModel): is_provisional: bool | None = None mve_collection_ticker: str | None = None mve_selected_legs: list[dict[str, Any]] | None = None + # Combo-only. Omitted for non-combo and for combos whose collection no + # longer exists — do not treat a missing value on a combo as standard. + allowed_leg_misses: int | None = None price_level_structure: str price_ranges: NullableList[dict[str, Any]] primary_participant_key: str | None = None diff --git a/kalshi/models/multivariate.py b/kalshi/models/multivariate.py index 600c629..9fca448 100644 --- a/kalshi/models/multivariate.py +++ b/kalshi/models/multivariate.py @@ -33,7 +33,10 @@ class AssociatedEvent(BaseModel): class MultivariateEventCollection(BaseModel): - """A multivariate event collection (combo contract template).""" + """A multivariate event collection (combo contract template). + + ``is_ordered`` is a legacy field. Always false. + """ collection_ticker: str series_ticker: str @@ -46,8 +49,9 @@ class MultivariateEventCollection(BaseModel): associated_event_tickers: NullableList[str] is_single_market_per_event: bool is_all_yes: bool - # Active fields + # Legacy field. Always false. is_ordered: bool + # Active fields size_min: int size_max: int functional_description: str diff --git a/kalshi/models/portfolio.py b/kalshi/models/portfolio.py index c50961d..52f78fe 100644 --- a/kalshi/models/portfolio.py +++ b/kalshi/models/portfolio.py @@ -224,7 +224,7 @@ class Settlement(BaseModel): ExchangeInstanceLiteral = Literal["event_contract", "margined"] """Exchange instance for intra-exchange fund movement (event vs margined).""" -IntraExchangeInstanceTransferStatusLiteral = Literal["pending", "complete"] +IntraExchangeInstanceTransferStatusLiteral = Literal["pending", "complete", "failed"] """Status of an intra-exchange instance transfer.""" diff --git a/kalshi/perps/models/markets.py b/kalshi/perps/models/markets.py index 6aa543e..1fdd0cc 100644 --- a/kalshi/perps/models/markets.py +++ b/kalshi/perps/models/markets.py @@ -83,6 +83,8 @@ class MarginMarket(BaseModel): status: MarginMarketStatusLiteral # Stable market UUID; remains unchanged if the ticker is renamed. market_id: str | None = None + # Omitted for markets without an expiration. + expiration_ts: AwareDatetime | None = None # Size of one contract in the market's underlying units (6 decimal places). # Prices are per contract, and track the underlying asset's price x # ``underlying_multiplier`` x ``contract_size``. @@ -161,6 +163,14 @@ class MarginMarket(BaseModel): default=None, validation_alias=AliasChoices("volume_24h_fp", "volume_24h"), ) + taker_long_volume_24h: FixedPointCount | None = Field( + default=None, + validation_alias=AliasChoices("taker_long_volume_24h_fp", "taker_long_volume_24h"), + ) + taker_short_volume_24h: FixedPointCount | None = Field( + default=None, + validation_alias=AliasChoices("taker_short_volume_24h_fp", "taker_short_volume_24h"), + ) volume_24h_notional_value: DollarDecimal | None = Field( default=None, validation_alias=AliasChoices( @@ -179,6 +189,8 @@ class MarginMarket(BaseModel): ) # Mark-price objects (spec ``$ref: TickerPrice``) — nested {price, ts_ms}, # NOT bare price strings; absent from the spec ``required`` list, so optional. + # Running estimate refreshed every few seconds; applied 12:00 PM / 4:00 PM + # ET marks can differ. See GET /margin/settlement_prices. settlement_mark_price: TickerPrice | None = None liquidation_mark_price: TickerPrice | None = None reference_price: TickerPrice | None = None diff --git a/kalshi/perps/models/transfers.py b/kalshi/perps/models/transfers.py index c583067..9ddcae6 100644 --- a/kalshi/perps/models/transfers.py +++ b/kalshi/perps/models/transfers.py @@ -38,8 +38,9 @@ class IntraExchangeInstanceTransferRequest(BaseModel): """Body for ``POST /portfolio/intra_exchange_instance_transfer``. - Moves funds between the ``event_contract`` and ``margined`` exchange - instances. ``amount`` is **centicents** (integer, ``int64``) — not dollars. + Moves funds between your Predictions and Perps accounts; not available + to FCM members or self-clearing members. ``amount`` is **centicents** + (integer, ``int64``) — not dollars. Shard fields default to ``0`` (only ``0`` is currently supported); because the body is serialized with ``exclude_none=True`` (not ``exclude_defaults``), shard ``0`` values are emitted on the wire, which is fine. diff --git a/kalshi/perps/resources/transfers.py b/kalshi/perps/resources/transfers.py index 11e1f58..9641a25 100644 --- a/kalshi/perps/resources/transfers.py +++ b/kalshi/perps/resources/transfers.py @@ -3,9 +3,8 @@ Three authenticated POST endpoints on the perps ``/portfolio/*`` host: - ``transfer_instance`` — ``POST /portfolio/intra_exchange_instance_transfer`` - (move funds between the ``event_contract`` and ``margined`` instances). The - spec marks this endpoint **"currently not available"**; it is implemented for - forward compatibility and may return an error until the server enables it. + (move funds between your Predictions and Perps accounts; not available to + FCM members or self-clearing members). - ``create_subaccount`` — ``POST /portfolio/margin/subaccounts`` (no request body; returns the new subaccount number, HTTP 201). Max 63 subaccounts/user, numbered sequentially from 1. @@ -176,10 +175,9 @@ def transfer_instance( client_transfer_id: UUID | str | None = None, extra_headers: dict[str, str] | None = None, ) -> IntraExchangeInstanceTransferResponse: - """Move funds between exchange instances. + """Move funds between your Predictions and Perps accounts. - Spec marks this endpoint "currently not available" — it is implemented - forward-compatibly and may return an error until the server enables it. + Not available to FCM members or self-clearing members. ``source_subaccount`` / ``destination_subaccount`` are optional; only supported for event contract to event contract transfers. Omit so the keys are not sent; an explicit ``0`` is emitted. @@ -306,10 +304,9 @@ async def transfer_instance( client_transfer_id: UUID | str | None = None, extra_headers: dict[str, str] | None = None, ) -> IntraExchangeInstanceTransferResponse: - """Move funds between exchange instances. + """Move funds between your Predictions and Perps accounts. - Spec marks this endpoint "currently not available" — it is implemented - forward-compatibly and may return an error until the server enables it. + Not available to FCM members or self-clearing members. ``source_subaccount`` / ``destination_subaccount`` are optional; only supported for event contract to event contract transfers. Omit so the keys are not sent; an explicit ``0`` is emitted. diff --git a/kalshi/perps/ws/models/ticker.py b/kalshi/perps/ws/models/ticker.py index aad68ca..5dd8adf 100644 --- a/kalshi/perps/ws/models/ticker.py +++ b/kalshi/perps/ws/models/ticker.py @@ -92,8 +92,13 @@ class MarginTickerPayload(BaseModel): "open_interest_notional_value_dollars", "open_interest_notional_value" ), ) + # Underlying reference price scaled to one contract, from the market's + # underlying price source, when available. reference_price: TickerPrice | None = None + # Running estimate refreshed every few seconds; applied 12:00 PM / 4:00 PM + # ET marks can differ. See GET /margin/settlement_prices. settlement_mark_price: TickerPrice | None = None + # Last published mark price used for margin and liquidation. liquidation_mark_price: TickerPrice | None = None funding_rate: FundingRate | None = None ts_ms: int diff --git a/kalshi/resources/communications.py b/kalshi/resources/communications.py index f5c3c0d..99f7c60 100644 --- a/kalshi/resources/communications.py +++ b/kalshi/resources/communications.py @@ -203,6 +203,7 @@ def _build_create_quote_body( rest_remainder: bool | None, subaccount: int | None, post_only: bool | None, + allowed_leg_misses: int | None, ) -> dict[str, Any]: _check_request_exclusive( request, @@ -212,6 +213,7 @@ def _build_create_quote_body( rest_remainder=rest_remainder, subaccount=subaccount, post_only=post_only, + allowed_leg_misses=allowed_leg_misses, ) if request is None: if rfq_id is None or yes_bid is None or no_bid is None or rest_remainder is None: @@ -226,6 +228,7 @@ def _build_create_quote_body( rest_remainder=rest_remainder, subaccount=subaccount, post_only=post_only, + allowed_leg_misses=allowed_leg_misses, ) return request.model_dump(exclude_none=True, by_alias=True, mode="json") @@ -409,6 +412,7 @@ def _build_create_rfq_batch_quote_body( rest_remainder: bool | None, post_only: bool | None, subaccount: int | None, + allowed_leg_misses: int | None, ) -> dict[str, Any]: _check_request_exclusive( request, @@ -416,6 +420,7 @@ def _build_create_rfq_batch_quote_body( rest_remainder=rest_remainder, post_only=post_only, subaccount=subaccount, + allowed_leg_misses=allowed_leg_misses, ) if request is None: if quotes is None or rest_remainder is None: @@ -427,6 +432,7 @@ def _build_create_rfq_batch_quote_body( rest_remainder=rest_remainder, post_only=post_only, subaccount=subaccount, + allowed_leg_misses=allowed_leg_misses, ) return request.model_dump(exclude_none=True, by_alias=True, mode="json") @@ -722,6 +728,7 @@ def create( rest_remainder: bool, subaccount: int | None = ..., post_only: bool | None = ..., + allowed_leg_misses: int | None = ..., extra_headers: dict[str, str] | None = None, ) -> CreateQuoteResponse: ... def create( @@ -734,8 +741,16 @@ def create( rest_remainder: bool | None = None, subaccount: int | None = None, post_only: bool | None = None, + allowed_leg_misses: int | None = None, extra_headers: dict[str, str] | None = None, ) -> CreateQuoteResponse: + """Create a quote on an RFQ. + + ``allowed_leg_misses`` is required by the server when the RFQ's + ``allowed_leg_misses`` is greater than 0 (else rejected with + ``allowed_leg_misses_required`` / ``allowed_leg_misses_mismatch``); + ``0`` and omitted mean the same. Sent only when set. + """ self._require_auth() body = _build_create_quote_body( request, @@ -745,6 +760,7 @@ def create( rest_remainder=rest_remainder, subaccount=subaccount, post_only=post_only, + allowed_leg_misses=allowed_leg_misses, ) data = self._post("/communications/quotes", json=body, extra_headers=extra_headers) return CreateQuoteResponse.model_validate(data) @@ -1113,6 +1129,7 @@ def create( rest_remainder: bool, post_only: bool | None = ..., subaccount: int | None = ..., + allowed_leg_misses: int | None = ..., extra_headers: dict[str, str] | None = None, ) -> CreateRFQBatchQuoteResponse: ... def create( @@ -1124,8 +1141,16 @@ def create( rest_remainder: bool | None = None, post_only: bool | None = None, subaccount: int | None = None, + allowed_leg_misses: int | None = None, extra_headers: dict[str, str] | None = None, ) -> CreateRFQBatchQuoteResponse: + """Create a quote on an RFQ batch. + + ``allowed_leg_misses`` is required by the server when the batch's + ``allowed_leg_misses`` is greater than 0 (else rejected with + ``allowed_leg_misses_required`` / ``allowed_leg_misses_mismatch``); + ``0`` and omitted mean the same. Sent only when set. + """ self._require_auth() body = _build_create_rfq_batch_quote_body( request, @@ -1133,6 +1158,7 @@ def create( rest_remainder=rest_remainder, post_only=post_only, subaccount=subaccount, + allowed_leg_misses=allowed_leg_misses, ) data = self._post( f"/communications/rfq_batches/{_seg(rfq_batch_id, name='rfq_batch_id')}/quotes", @@ -1589,6 +1615,7 @@ def create_quote( rest_remainder: bool | None = None, subaccount: int | None = None, post_only: bool | None = None, + allowed_leg_misses: int | None = None, extra_headers: dict[str, str] | None = None, ) -> CreateQuoteResponse: """.. deprecated:: 3.0.0 Use :meth:`client.communications.quotes.create` instead.""" @@ -1600,6 +1627,7 @@ def create_quote( rest_remainder=rest_remainder, subaccount=subaccount, post_only=post_only, + allowed_leg_misses=allowed_leg_misses, extra_headers=extra_headers, ) @@ -1877,6 +1905,7 @@ async def create( rest_remainder: bool, subaccount: int | None = ..., post_only: bool | None = ..., + allowed_leg_misses: int | None = ..., extra_headers: dict[str, str] | None = None, ) -> CreateQuoteResponse: ... async def create( @@ -1889,8 +1918,16 @@ async def create( rest_remainder: bool | None = None, subaccount: int | None = None, post_only: bool | None = None, + allowed_leg_misses: int | None = None, extra_headers: dict[str, str] | None = None, ) -> CreateQuoteResponse: + """Create a quote on an RFQ. + + ``allowed_leg_misses`` is required by the server when the RFQ's + ``allowed_leg_misses`` is greater than 0 (else rejected with + ``allowed_leg_misses_required`` / ``allowed_leg_misses_mismatch``); + ``0`` and omitted mean the same. Sent only when set. + """ self._require_auth() body = _build_create_quote_body( request, @@ -1900,6 +1937,7 @@ async def create( rest_remainder=rest_remainder, subaccount=subaccount, post_only=post_only, + allowed_leg_misses=allowed_leg_misses, ) data = await self._post("/communications/quotes", json=body, extra_headers=extra_headers) return CreateQuoteResponse.model_validate(data) @@ -2257,6 +2295,7 @@ async def create( rest_remainder: bool, post_only: bool | None = ..., subaccount: int | None = ..., + allowed_leg_misses: int | None = ..., extra_headers: dict[str, str] | None = None, ) -> CreateRFQBatchQuoteResponse: ... async def create( @@ -2268,8 +2307,16 @@ async def create( rest_remainder: bool | None = None, post_only: bool | None = None, subaccount: int | None = None, + allowed_leg_misses: int | None = None, extra_headers: dict[str, str] | None = None, ) -> CreateRFQBatchQuoteResponse: + """Create a quote on an RFQ batch. + + ``allowed_leg_misses`` is required by the server when the batch's + ``allowed_leg_misses`` is greater than 0 (else rejected with + ``allowed_leg_misses_required`` / ``allowed_leg_misses_mismatch``); + ``0`` and omitted mean the same. Sent only when set. + """ self._require_auth() body = _build_create_rfq_batch_quote_body( request, @@ -2277,6 +2324,7 @@ async def create( rest_remainder=rest_remainder, post_only=post_only, subaccount=subaccount, + allowed_leg_misses=allowed_leg_misses, ) data = await self._post( f"/communications/rfq_batches/{_seg(rfq_batch_id, name='rfq_batch_id')}/quotes", @@ -2736,6 +2784,7 @@ async def create_quote( rest_remainder: bool | None = None, subaccount: int | None = None, post_only: bool | None = None, + allowed_leg_misses: int | None = None, extra_headers: dict[str, str] | None = None, ) -> CreateQuoteResponse: """.. deprecated:: 3.0.0 Use :meth:`client.communications.quotes.create` instead.""" @@ -2747,6 +2796,7 @@ async def create_quote( rest_remainder=rest_remainder, subaccount=subaccount, post_only=post_only, + allowed_leg_misses=allowed_leg_misses, extra_headers=extra_headers, ) diff --git a/kalshi/ws/models/__init__.py b/kalshi/ws/models/__init__.py index e05d794..a6950ad 100644 --- a/kalshi/ws/models/__init__.py +++ b/kalshi/ws/models/__init__.py @@ -24,6 +24,7 @@ QuoteAcceptedPayload, QuoteCreatedPayload, QuoteExecutedPayload, + RfqBatchCreatedPayload, RfqCreatedPayload, RfqDeletedPayload, ) @@ -111,6 +112,7 @@ "QuoteAcceptedPayload", "QuoteCreatedPayload", "QuoteExecutedPayload", + "RfqBatchCreatedPayload", "RfqCreatedPayload", "RfqDeletedPayload", "SubscribedMessage", diff --git a/kalshi/ws/models/communications.py b/kalshi/ws/models/communications.py index d02aa58..0406464 100644 --- a/kalshi/ws/models/communications.py +++ b/kalshi/ws/models/communications.py @@ -36,6 +36,9 @@ class RfqCreatedPayload(BaseModel): # event_ticker/market_ticker/side/yes_settlement_value_dollars. mve_collection_ticker: str | None = None mve_selected_legs: list[dict[str, object]] | None = None + # Combo-only. Omitted for non-combo and for combos whose collection no + # longer exists — do not treat a missing value on a combo as standard. + allowed_leg_misses: int | None = None # Set when this RFQ is a child of an RFQ batch; omitted otherwise. rfq_batch_id: str | None = None model_config = {"extra": "allow", "populate_by_name": True} @@ -162,6 +165,24 @@ class QuoteExecutedPayload(BaseModel): model_config = {"extra": "allow", "populate_by_name": True} +class RfqBatchCreatedPayload(BaseModel): + """RFQ-batch created notification payload (``rfqBatchCreatedPayload.msg``). + + ``legs`` and ``rfqs`` keep the wire object shape as dicts (same pattern as + ``RfqCreatedPayload.mve_selected_legs``). Combo-only ``allowed_leg_misses`` + is omitted when the rule could not be read — do not treat the batch's + combos as standard then. + """ + + id: str + creator_id: str + created_ts: AwareDatetime + legs: list[dict[str, object]] + rfqs: list[dict[str, object]] + allowed_leg_misses: int | None = None + model_config = {"extra": "allow", "populate_by_name": True} + + class CommunicationsMessage(BaseModel): """RFQ and quote notifications. Payload varies by sub-type, so msg is a dict. diff --git a/pyproject.toml b/pyproject.toml index e795b8d..da93f1b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "22.17.0" +version = "22.18.0" description = "A professional Python SDK for the Kalshi prediction markets and Perps (margin) APIs" readme = "README.md" license = { text = "MIT" } diff --git a/tests/perps/test_markets.py b/tests/perps/test_markets.py index ee54db0..a92ca3f 100644 --- a/tests/perps/test_markets.py +++ b/tests/perps/test_markets.py @@ -177,6 +177,36 @@ def test_bid_ask_size_omitted_when_missing(self) -> None: assert m.bid_size is None assert m.ask_size is None + def test_expiration_ts_and_taker_volumes_omitted(self) -> None: + m = MarginMarket.model_validate(_market_dict()) + assert m.expiration_ts is None + assert m.taker_long_volume_24h is None + assert m.taker_short_volume_24h is None + + def test_expiration_ts_and_taker_volumes_parse(self) -> None: + m = MarginMarket.model_validate( + _market_dict( + expiration_ts="2026-12-31T23:59:59Z", + taker_long_volume_24h="10.00", + taker_short_volume_24h="12.50", + ) + ) + assert m.expiration_ts is not None + assert m.expiration_ts.year == 2026 + assert m.taker_long_volume_24h == Decimal("10.00") + assert m.taker_short_volume_24h == Decimal("12.50") + assert isinstance(m.taker_long_volume_24h, Decimal) + + def test_taker_volumes_accept_fp_alias(self) -> None: + m = MarginMarket.model_validate( + _market_dict( + taker_long_volume_24h_fp="3.00", + taker_short_volume_24h_fp="4.00", + ) + ) + assert m.taker_long_volume_24h == Decimal("3.00") + assert m.taker_short_volume_24h == Decimal("4.00") + def test_funding_fields_required(self) -> None: for key in ( "funding_deadband", diff --git a/tests/test_client.py b/tests/test_client.py index f3dcab4..2727477 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -289,6 +289,36 @@ def test_post_not_retried_on_500(self, transport: SyncTransport) -> None: transport.request("POST", "/portfolio/orders", json={"ticker": "T"}) assert route.call_count == 1 + @respx.mock + def test_post_409_x_retry_after_not_retried(self, transport: SyncTransport) -> None: + route = respx.post( + "https://test.kalshi.com/trade-api/v2/communications/quotes", + ).mock( + return_value=httpx.Response( + 409, + json={"message": "quote_timed_out"}, + headers={"X-Retry-After": "7"}, + ) + ) + with pytest.raises(KalshiConflictError) as exc_info: + transport.request("POST", "/communications/quotes", json={"rfq_id": "r"}) + assert exc_info.value.retry_after == 7.0 + assert route.call_count == 1 + + @respx.mock + def test_get_409_not_retried(self, transport: SyncTransport) -> None: + route = respx.get("https://test.kalshi.com/trade-api/v2/markets").mock( + return_value=httpx.Response( + 409, + json={"message": "conflict"}, + headers={"X-Retry-After": "7"}, + ) + ) + with pytest.raises(KalshiConflictError) as exc_info: + transport.request("GET", "/markets") + assert exc_info.value.retry_after == 7.0 + assert route.call_count == 1 + @respx.mock def test_post_not_retried(self, transport: SyncTransport) -> None: route = respx.post("https://test.kalshi.com/trade-api/v2/portfolio/orders").mock( @@ -1195,6 +1225,27 @@ def test_409_maps_to_KalshiConflictError(self) -> None: # noqa: N802 err = _map_error(resp) assert isinstance(err, KalshiConflictError) assert err.status_code == 409 + assert err.retry_after is None + + def test_409_x_retry_after_populates_retry_after(self) -> None: + resp = httpx.Response( + 409, + json={"message": "quote_timed_out"}, + headers={"X-Retry-After": "7"}, + ) + err = _map_error(resp) + assert isinstance(err, KalshiConflictError) + assert err.retry_after == 7.0 + + def test_409_retry_after_wins_over_x_retry_after(self) -> None: + resp = httpx.Response( + 409, + json={"message": "conflict"}, + headers={"Retry-After": "3", "X-Retry-After": "7"}, + ) + err = _map_error(resp) + assert isinstance(err, KalshiConflictError) + assert err.retry_after == 3.0 def test_410_falls_back_to_KalshiError(self) -> None: # noqa: N802 # 410 unmapped — see follow-up. Pin current behavior so a future diff --git a/tests/test_communications.py b/tests/test_communications.py index 084177e..3aa15c3 100644 --- a/tests/test_communications.py +++ b/tests/test_communications.py @@ -270,6 +270,12 @@ def test_create_rfq_rejects_zero_contracts(self) -> None: with pytest.raises(ValidationError): CreateRFQRequest(market_ticker="MKT-1", rest_remainder=True, contracts=0) + def test_rfq_allowed_leg_misses_optional(self) -> None: + rfq = RFQ.model_validate(_MINIMAL_RFQ) + assert rfq.allowed_leg_misses is None + rfq = RFQ.model_validate({**_MINIMAL_RFQ, "allowed_leg_misses": 1}) + assert rfq.allowed_leg_misses == 1 + def test_create_quote_request_serializes_bids_without_dollars_suffix(self) -> None: # Spec wire uses yes_bid / no_bid (no _dollars suffix) for this one. req = CreateQuoteRequest( @@ -286,6 +292,27 @@ def test_create_quote_request_serializes_bids_without_dollars_suffix(self) -> No "rest_remainder": True, } + def test_create_quote_request_omits_allowed_leg_misses_when_unset(self) -> None: + req = CreateQuoteRequest( + rfq_id="rfq-1", + yes_bid=Decimal("0.56"), + no_bid=Decimal("0.44"), + rest_remainder=True, + ) + body = req.model_dump(exclude_none=True, by_alias=True, mode="json") + assert "allowed_leg_misses" not in body + + def test_create_quote_request_serializes_allowed_leg_misses(self) -> None: + req = CreateQuoteRequest( + rfq_id="rfq-1", + yes_bid=Decimal("0.56"), + no_bid=Decimal("0.44"), + rest_remainder=True, + allowed_leg_misses=1, + ) + body = req.model_dump(exclude_none=True, by_alias=True, mode="json") + assert body["allowed_leg_misses"] == 1 + def test_create_quote_forbids_extra(self) -> None: with pytest.raises(ValidationError): CreateQuoteRequest( # type: ignore[call-arg] @@ -673,6 +700,21 @@ def test_sends_correct_body(self, comms: CommunicationsResource) -> None: "rest_remainder": True, } + @respx.mock + def test_sends_allowed_leg_misses_when_set(self, comms: CommunicationsResource) -> None: + route = respx.post( + "https://test.kalshi.com/trade-api/v2/communications/quotes", + ).mock(return_value=httpx.Response(201, json={"id": "q-new"})) + comms.create_quote( + rfq_id="rfq-1", + yes_bid=Decimal("0.56"), + no_bid=Decimal("0.44"), + rest_remainder=True, + allowed_leg_misses=1, + ) + body = json.loads(route.calls[0].request.content) + assert body["allowed_leg_misses"] == 1 + @respx.mock def test_400(self, comms: CommunicationsResource) -> None: respx.post( @@ -2201,6 +2243,23 @@ def test_create_rfq_batch_quote_request_serializes_bids_without_suffix(self) -> "no_bid": "0.44", } assert "yes_bid_dollars" not in body["quotes"][0] + assert "allowed_leg_misses" not in body + + def test_create_rfq_batch_quote_request_serializes_allowed_leg_misses(self) -> None: + req = CreateRFQBatchQuoteRequest( + quotes=[ + RFQBatchQuoteEntry( + rfq_id="rfq-1", yes_bid=Decimal("0.56"), no_bid=Decimal("0.44") + ), + RFQBatchQuoteEntry( + rfq_id="rfq-2", yes_bid=Decimal("0.50"), no_bid=Decimal("0.50") + ), + ], + rest_remainder=True, + allowed_leg_misses=1, + ) + body = req.model_dump(exclude_none=True, by_alias=True, mode="json") + assert body["allowed_leg_misses"] == 1 def test_create_rfq_batch_quote_request_forbids_extra(self) -> None: with pytest.raises(ValidationError): @@ -2525,6 +2584,28 @@ def test_sends_correct_body(self, comms: CommunicationsResource) -> None: assert body["rest_remainder"] is True assert body["post_only"] is True assert body["quotes"][0]["yes_bid"] == "0.56" + assert "allowed_leg_misses" not in body + + @respx.mock + def test_sends_allowed_leg_misses_when_set(self, comms: CommunicationsResource) -> None: + route = respx.post(f"{_BATCH_URL}/batch-1/quotes").mock( + return_value=httpx.Response(201, json={"id": "bq-new"}) + ) + comms.rfq_batches.quotes.create( + "batch-1", + quotes=[ + RFQBatchQuoteEntry( + rfq_id="rfq-1", yes_bid=Decimal("0.56"), no_bid=Decimal("0.44") + ), + RFQBatchQuoteEntry( + rfq_id="rfq-2", yes_bid=Decimal("0.50"), no_bid=Decimal("0.50") + ), + ], + rest_remainder=True, + allowed_leg_misses=1, + ) + body = json.loads(route.calls[0].request.content) + assert body["allowed_leg_misses"] == 1 @respx.mock def test_400(self, comms: CommunicationsResource) -> None: diff --git a/tests/test_models.py b/tests/test_models.py index 16cdeb4..514dbc6 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -299,6 +299,7 @@ def test_all_new_fields_default_to_none(self) -> None: "is_provisional", "mve_collection_ticker", "mve_selected_legs", + "allowed_leg_misses", # NOTE: price_level_structure / price_ranges were optional in v3.18.0 # but #172 promoted them to required-on-the-wire. They no longer # default to None; removed from this list. @@ -306,6 +307,10 @@ def test_all_new_fields_default_to_none(self) -> None: ): assert getattr(m, name) is None, f"{name} should default to None" + def test_allowed_leg_misses_parses(self) -> None: + m = Market.model_validate(market_dict(ticker="T", allowed_leg_misses=1)) + assert m.allowed_leg_misses == 1 + class TestOrderV3180Fields: """v3.18.0 backfill (issue #159): 8 new optional fields on ``Order``. diff --git a/tests/test_portfolio.py b/tests/test_portfolio.py index 0bc5a25..777e5c6 100644 --- a/tests/test_portfolio.py +++ b/tests/test_portfolio.py @@ -1526,6 +1526,12 @@ def test_get_by_id(self, portfolio: PortfolioResource) -> None: assert t.transfer_id == "xfer-1" assert t.amount == Decimal("25.5000") + def test_failed_status_parses(self) -> None: + from kalshi.models.portfolio import IntraExchangeInstanceTransfer + + t = IntraExchangeInstanceTransfer.model_validate({**_TRANSFER, "status": "failed"}) + assert t.status == "failed" + def test_requires_auth(self, unauth_portfolio: PortfolioResource) -> None: with pytest.raises(AuthRequiredError): unauth_portfolio.intra_exchange_transfers() diff --git a/tests/ws/test_models.py b/tests/ws/test_models.py index de5fc18..8792e98 100644 --- a/tests/ws/test_models.py +++ b/tests/ws/test_models.py @@ -27,6 +27,7 @@ QuoteAcceptedPayload, QuoteCreatedPayload, QuoteExecutedPayload, + RfqBatchCreatedPayload, RfqCreatedPayload, ) from kalshi.ws.models.ebattle import ( @@ -1127,6 +1128,42 @@ def test_rfq_created_mve_fields(self) -> None: assert payload.mve_collection_ticker == "COLL-001" assert payload.mve_selected_legs is not None assert payload.mve_selected_legs[0]["event_ticker"] == "EVT-1" + assert payload.allowed_leg_misses is None + + def test_rfq_created_allowed_leg_misses(self) -> None: + payload = RfqCreatedPayload.model_validate( + { + "id": "rfq-1", + "creator_id": "user-1", + "market_ticker": "MKT-1", + "created_ts": "2026-01-01T00:00:00Z", + "allowed_leg_misses": 1, + } + ) + assert payload.allowed_leg_misses == 1 + + def test_rfq_batch_created_payload_allowed_leg_misses(self) -> None: + payload = RfqBatchCreatedPayload.model_validate( + { + "id": "batch-1", + "creator_id": "user-1", + "created_ts": "2026-01-01T00:00:00Z", + "legs": [], + "rfqs": [], + "allowed_leg_misses": 1, + } + ) + assert payload.allowed_leg_misses == 1 + omitted = RfqBatchCreatedPayload.model_validate( + { + "id": "batch-1", + "creator_id": "user-1", + "created_ts": "2026-01-01T00:00:00Z", + "legs": [], + "rfqs": [], + } + ) + assert omitted.allowed_leg_misses is None def test_rfq_deleted_rfq_context(self) -> None: from kalshi.ws.models.communications import RfqDeletedPayload