From 77d6bc37edf1c1d773b4e64bdcf3d18cf2f17dc6 Mon Sep 17 00:00:00 2001 From: Jeff West Date: Fri, 13 Nov 2026 09:15:41 -0600 Subject: [PATCH 1/2] chore(spec): sync core, asyncapi, perps + perps_scm specs (#582) --- specs/asyncapi.yaml | 65 +++- specs/openapi.yaml | 569 +++++++++++++++++++++++++++++++++-- specs/perps_openapi.yaml | 20 +- specs/perps_scm_openapi.yaml | 5 +- 4 files changed, 603 insertions(+), 56 deletions(-) diff --git a/specs/asyncapi.yaml b/specs/asyncapi.yaml index 6017847..4e50af3 100644 --- a/specs/asyncapi.yaml +++ b/specs/asyncapi.yaml @@ -22,11 +22,11 @@ info: | 4 | Subscription IDs required | Missing sids in unsubscribe | | 5 | Unknown command | Invalid command name | | 6 | Retired | Not emitted. The number stays reserved. | - | 7 | Unknown subscription ID | Subscription ID not found | + | 7 | Unknown subscription ID | Subscription ID not found. An `unsubscribe` listing several `sids` still unsubscribes the ones that exist, then returns this error for the rest | | 8 | Unknown channel name | Invalid channel in subscribe | - | 9 | Authentication required | Channel requires authenticated connection | + | 9 | Authentication required | Channel requires authentication, or your API key is not entitled to this channel: a key limited to market data on `fill`, `market_positions`, `order_group_updates` or `user_orders`, or a key without access to a restricted data feed | | 10 | Channel error | Channel-specific error | - | 11 | Invalid parameter | Malformed parameter value, or update_interval_ms differs from the existing orderbook subscription | + | 11 | Invalid parameter | Malformed parameter value, or update_interval_ms differs from the existing orderbook subscription (the message is then `update_interval_ms cannot change on an existing subscription`) | | 12 | Exactly one subscription ID is required | For update_subscription | | 13 | Unsupported action | Invalid action for update_subscription | | 14 | Market Ticker required | Missing market specification (market_ticker or market_id) | @@ -39,8 +39,9 @@ info: | 21 | shard_key must be >= 0 and < shard_factor | Invalid shard_key | | 22 | shard_factor must be <= 100 | shard_factor too large | | 23 | Match IDs required | Missing match_ids for subscribe_matches/unsubscribe_matches on ebattle_scores | - | 26 | Subscription market limit exceeded | Adding markets would exceed the per-subscription market limit | - | 27 | Too many requests | The subscription exceeded its command rate limit | + | 24 | Index IDs required | Missing index_ids for subscribe_indices/unsubscribe_indices on cfbenchmarks_value / cfbenchmarks_value_5hz | + | 26 | Subscription market limit exceeded | Adding markets would take an `orderbook_delta` subscription over 500,000 markets. No markets from the command are added | + | 27 | Too many requests | `subscribe` / `add_markets` commands for an `orderbook_delta` subscription were sent too fast. The command is not applied; wait briefly and send it again | | 28 | Underlying tickers required | Missing underlying_tickers for subscribe_underlyings/unsubscribe_underlyings on pyth_value | | 29 | update_interval_ms must be 0, 100 or 1000 | Invalid update_interval_ms on orderbook_delta | @@ -52,6 +53,26 @@ info: |------|-------| | 10 | Channel error | | 25 | Subscription buffer overflow | + + A terminal error on a running subscription ends that subscription, not the connection. The server sends + the `error` with that subscription's `sid` and no `id`, then an `unsubscribed` message for the same `sid`. + Your other subscriptions keep running. Subscribe to the channel again to get a new `sid`. + + Code 10 can also answer a `subscribe` that could not be opened. That `error` carries the command's `id` + and no `sid`, no subscription was created, and no `unsubscribed` follows. + + ## Disconnects + + The server can close the connection at any time. Reconnect with exponential backoff and subscribe again; + subscriptions and `sid` values do not carry over to a new connection. + + - **Slow reader:** if a message is still waiting to be written to your socket 15 seconds after the + server received it, the server closes the connection with close code `1008` and reason + `WebSocket server delivery exceeded 15 seconds`. A socket that stops accepting writes is also closed. + Read from the socket continuously and move slow work off the reading path. + - **Normal closure:** close code `1000` is a normal closure and does not identify a cause. A graceful + server shutdown, such as during a release, is one cause. An abrupt failure may close the connection + without any close frame. contact: name: Kalshi Support url: https://kalshi.com @@ -91,6 +112,16 @@ channels: Authentication is required to establish the connection; include API key headers during the WebSocket handshake. Some channels carry only public market data, but the connection itself still requires authentication. Use the subscribe command to subscribe to specific data channels. For more information, see the [Getting Started](https://docs.kalshi.com/getting_started/quick_start_websockets) guide. + + **Handshake errors:** a rejected handshake returns an HTTP error instead of upgrading. `429 Too Many Requests` with code + `too_many_requests` has two causes: you have reached your tier's [concurrent connection limit](https://docs.kalshi.com/getting_started/rate_limits#websocket-connection-limits), + or you are opening connections too quickly. The HTTP status and error code are the same for both, so reconnect with + exponential backoff rather than in a tight loop, and close connections you no longer use. + + **One subscription per channel:** a connection holds at most one subscription to each channel. A `subscribe` naming a channel + you are already subscribed to does not create a second subscription or return `subscribed`. It is applied to the existing `sid`: + on channels with a market filter it adds the listed markets and returns `ok`, or returns an `error`. To change other parameters, + `unsubscribe`, wait for `unsubscribed`, then `subscribe` again. bindings: ws: method: GET @@ -138,7 +169,10 @@ channels: description: | WebSocket control frames for connection management. - Kalshi sends Ping frames (`0x9`) every 10 seconds with body `heartbeat` to maintain the connection. + Kalshi sends a Ping frame (`0x9`) with body `heartbeat` after 10 seconds without sending a data message (a JSON text frame) 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. Clients should respond with Pong frames (`0xA`). Clients may also send Ping frames to which Kalshi will respond with Pong. messages: incomingPing: @@ -161,11 +195,13 @@ channels: - Market specification required: - Use `market_ticker` (string) for a single market - Use `market_tickers` (array of strings) for multiple markets - - `market_id`/`market_ids` are not supported for this channel + - `market_id`/`market_ids` are not supported for this channel and never select a market. A first `subscribe` that gives only `market_id`/`market_ids` is acknowledged with `subscribed` but receives no snapshots or deltas. On an existing subscription, a `subscribe`, `add_markets` or `delete_markets` that gives only IDs returns `ok` and changes nothing, so the markets already subscribed keep streaming; `get_snapshot` with only IDs returns error code 14 - Sends `orderbook_snapshot` first, then incremental `orderbook_delta` updates - Supports `update_subscription` with `add_markets` / `delete_markets` / `get_snapshot` actions - `get_snapshot` returns an `orderbook_snapshot` for the requested `market_tickers` without changing the subscribed markets. Apply every returned snapshot as a replacement for that market's local book - Each connection has one `orderbook_delta` subscription. A repeated `subscribe` adds new markets to its existing `sid`; it does not resend snapshots for markets already subscribed + - A subscription holds at most 500,000 markets. A `subscribe` or `add_markets` that would exceed this returns error code 26 and adds none of its markets + - When a market is determined, the server sends an empty `orderbook_snapshot` for it and removes it from the subscription. No further messages follow for that market and there is no separate notification; replace your local book with the empty snapshot - A repeated `subscribe` must use the existing `update_interval_ms` (omitting it means `0`). A different valid interval returns error code 11 without adding markets. Use `update_subscription` with `add_markets` to add markets without respecifying the interval. To change the interval, `unsubscribe`, wait for `unsubscribed`, then `subscribe` again **Matching real-time updates across connections:** @@ -204,9 +240,10 @@ channels: **Requirements:** - No additional channel-level authentication beyond the authenticated WebSocket connection - - Market specification optional (omit to receive all markets) + - Market specification optional (omit to receive all markets except those whose ticker starts with `KXRFQ`, which are sent only to subscriptions that name them) - Supports `market_ticker`/`market_tickers` and `market_id`/`market_ids` - - Updates sent whenever any ticker field changes + - Changes are combined and sent on a flush scheduled every second: each flush sends one message per changed market, carrying its current values, so intermediate values are not sent. This is a schedule, not a guaranteed minimum gap; two updates for one market can arrive less than a second apart. For every trade or book change, use the `trade` or `orderbook_delta` channel + - A subscription created without a market filter cannot be changed: `update_subscription` and a repeated `subscribe` return error code 13. To filter, or to receive `KXRFQ` markets, `unsubscribe` and `subscribe` again with a market filter **Use case:** Displaying current market prices and statistics messages: @@ -223,6 +260,7 @@ channels: - No additional channel-level authentication beyond the authenticated WebSocket connection - Market specification optional (omit to receive all trades) - Updates sent immediately after trade execution + - A repeated `subscribe` or an `update_subscription` without `market_ticker`/`market_tickers` returns error code 14. That error and error code 13 on this channel carry no `id` **Use case:** Trade feed, volume analysis messages: @@ -257,6 +295,7 @@ channels: - Market specification optional (omit to receive all positions) - Filters are by `market_ticker`/`market_tickers` only; `market_id`/`market_ids` are not supported - Updates sent when your position changes due to trades, settlements, etc. + - Messages carry no `seq` and are not ordered against the `fill` channel: the position update for a trade can arrive after its `fill` message. Do not assume your position is current when a fill arrives **Monetary Values:** All monetary values are returned as fixed-point dollar strings (`_dollars` suffix). @@ -1760,9 +1799,9 @@ components: | 4 | Subscription IDs required | Missing sids in unsubscribe | | 5 | Unknown command | Invalid command name | | 6 | Retired | Not emitted. The number stays reserved. | - | 7 | Unknown subscription ID | Subscription ID not found | + | 7 | Unknown subscription ID | Subscription ID not found. An `unsubscribe` listing several `sids` still unsubscribes the ones that exist, then returns this error for the rest | | 8 | Unknown channel name | Invalid channel in subscribe | - | 9 | Authentication required | Channel requires authenticated connection | + | 9 | Authentication required | Channel requires authentication, or your API key is not entitled to this channel: a key limited to market data on `fill`, `market_positions`, `order_group_updates` or `user_orders`, or a key without access to a restricted data feed | | 10 | Channel error | Channel-specific error | | 11 | Invalid parameter | Malformed parameter value, or update_interval_ms differs from the existing orderbook subscription | | 12 | Exactly one subscription ID is required | For update_subscription | @@ -1779,8 +1818,8 @@ components: | 23 | Match IDs required | Missing match_ids for the channel/action | | 24 | Index IDs required | Missing index_ids for subscribe_indices/unsubscribe_indices on cfbenchmarks_value / cfbenchmarks_value_5hz | | 25 | Subscription buffer overflow | The subscription's outbound buffer was exceeded | - | 26 | Subscription market limit exceeded | Adding markets would exceed the per-subscription market limit | - | 27 | Too many requests | The subscription exceeded its command rate limit | + | 26 | Subscription market limit exceeded | Adding markets would take an `orderbook_delta` subscription over 500,000 markets. No markets from the command are added | + | 27 | Too many requests | `subscribe` / `add_markets` commands for an `orderbook_delta` subscription were sent too fast. The command is not applied; wait briefly and send it again | | 28 | Underlying tickers required | Missing underlying_tickers for subscribe_underlyings/unsubscribe_underlyings on pyth_value | | 29 | update_interval_ms must be 0, 100 or 1000 | Invalid update_interval_ms on orderbook_delta | contentType: application/json diff --git a/specs/openapi.yaml b/specs/openapi.yaml index 1206361..e332b3d 100644 --- a/specs/openapi.yaml +++ b/specs/openapi.yaml @@ -154,7 +154,12 @@ paths: get: operationId: GetExchangeStatus summary: Get Exchange Status - description: ' Endpoint for getting the exchange status.' + description: | + Endpoint for getting the exchange status. + + The top-level fields describe the default exchange index (0). Read the flags only from a 200 response. When the status of the default index cannot be read, the response is a 500, 503 or 504; its body can be an `ExchangeStatus` with `exchange_active` and `trading_active` set to `false`, or an error object, and in neither case does it mean the exchange is paused. + + In `exchange_index_statuses` on a 200 response, an index other than 0 whose status request failed or timed out is reported with all of its flags `false`. Read the status again before treating a single `false` reading for one index as a pause. tags: - exchange responses: @@ -256,6 +261,10 @@ paths: description: | Time period length of each candlestick in minutes. Valid values: 1 (1 minute), 60 (1 hour), 1440 (1 day). Candlesticks for markets that settled before the historical cutoff are only available via `GET /historical/markets/{ticker}/candlesticks`. See [Historical Data](https://docs.kalshi.com/getting_started/historical_data) for details. + + One request can span at most 5,000 periods. If the minutes between `start_ts` and `end_ts` divided by `period_interval` exceed 5,000, the request is rejected with 400 `bad_request` and the `details` field gives the requested and maximum counts. For example, 1-minute candlesticks are limited to about 3.5 days per request; split a longer range into several requests. `start_ts` and `end_ts` must be in seconds; millisecond values are rejected with 400 `bad_request`. + + The most recent candlesticks can be a few seconds behind the latest trades and quotes. tags: - market parameters: @@ -329,6 +338,8 @@ paths: summary: Get Trades description: | Endpoint for getting all trades for all markets. A trade represents a completed transaction between two users on a specific market. Each trade includes the market ticker, price, quantity, and timestamp information. Block trades are included in the response by default and identified by the `is_block_trade` field; use the `is_block_trade` query parameter to filter by block / non-block. This endpoint returns a paginated response. Use the 'limit' parameter to control page size (1-1000, defaults to 100). The response includes a 'cursor' field - pass this value in the 'cursor' parameter of your next request to get the next page. An empty cursor indicates no more pages are available. + + A `ticker` that does not match any market returns 200 with an empty `trades` list, not 404. A `cursor` that cannot be decoded is ignored and the first page is returned, so pass the cursor exactly as it was returned. `min_ts` and `max_ts` must be in seconds; millisecond values are rejected with 400 `bad_request`. tags: - market parameters: @@ -354,14 +365,14 @@ paths: get: operationId: GetMarketOrderbook summary: Get Market Orderbook - description: ' Endpoint for getting the current order book for a specific market. The order book shows all active bid orders for both yes and no sides of a binary market. It returns yes bids and no bids only (no asks are returned). This is because in binary markets, a bid for yes at price X is equivalent to an ask for no at price (100-X). For example, a yes bid at 7¢ is the same as a no ask at 93¢, with identical contract sizes. Each side shows price levels with their corresponding quantities and order counts, organized from best to worst prices.' + description: ' Endpoint for getting the current order book for a specific market. The order book shows all active bid orders for both yes and no sides of a binary market. It returns yes bids and no bids only (no asks are returned). This is because in binary markets, a bid for yes at price X is equivalent to an ask for no at price (100-X). For example, a yes bid at 7¢ is the same as a no ask at 93¢, with identical contract sizes. Each side lists price levels as [price, quantity] pairs sorted by price in ascending order, so the best (highest) bid is the last element. Order counts are not returned. When `depth` is set, the best `depth` levels of each side are returned. A ticker that has no order book, including a ticker that does not match any market, returns 200 with empty arrays rather than 404.' tags: - market parameters: - $ref: '#/components/parameters/TickerPath' - name: depth in: query - description: Depth of the orderbook to retrieve (0 or negative means all levels, 1-100 for specific depth) + description: Number of price levels to return per side, counted from the best bid. Omit it or pass 0 for all levels; pass 1-100 for a specific depth. Values below 0 or above 100 are rejected with 400. required: false schema: type: integer @@ -388,7 +399,7 @@ paths: get: operationId: GetMarketOrderbooks summary: Get Multiple Market Orderbooks - description: 'Endpoint for getting the current order books for multiple markets in a single request. The order book shows all active bid orders for both yes and no sides of a binary market. It returns yes bids and no bids only (no asks are returned). This is because in binary markets, a bid for yes at price X is equivalent to an ask for no at price (100-X). For example, a yes bid at 7¢ is the same as a no ask at 93¢, with identical contract sizes. Each side shows price levels with their corresponding quantities and order counts, organized from best to worst prices. Returns one orderbook per requested market ticker.' + description: 'Endpoint for getting the current order books for multiple markets in a single request. The order book shows all active bid orders for both yes and no sides of a binary market. It returns yes bids and no bids only (no asks are returned). This is because in binary markets, a bid for yes at price X is equivalent to an ask for no at price (100-X). For example, a yes bid at 7¢ is the same as a no ask at 93¢, with identical contract sizes. Each side lists price levels as [price, quantity] pairs sorted by price in ascending order, so the best (highest) bid is the last element. Order counts are not returned. Returns one orderbook per requested market ticker, in request order. A ticker that has no order book, including a ticker that does not match any market, is returned with empty arrays.' tags: - market parameters: @@ -529,6 +540,14 @@ paths: Markets that settled before the historical cutoff are only available via `GET /historical/markets`. See [Historical Data](https://docs.kalshi.com/getting_started/historical_data) for details. + Paging and ordering: + - When `event_ticker` or `tickers` is the only filter (no `status`, `series_ticker`, timestamp filter, `mve_filter` or `cursor`), every matching market is returned in one response, in no guaranteed order. `limit` is not applied and the returned `cursor` is empty. + - Otherwise results are sorted by creation time, newest first, with these exceptions. With `min_updated_ts` or `max_updated_ts` they are sorted by last update time, oldest first. When neither `event_ticker` nor `tickers` is supplied, `status=closed`, `min_close_ts` or `max_close_ts` sorts by close time, latest first, and `min_settled_ts` or `max_settled_ts` sorts by settlement time, latest first. A request that supplies `event_ticker` or `tickers` together with another filter is sorted by creation time, even when that filter is `status=closed` or a close-time or settlement-time filter. The unpaged case above, where `event_ticker` or `tickers` is the only filter, has no guaranteed order. + - A market whose close time changes while you page through a listing sorted by close time can be skipped or returned twice. Deduplicate by `ticker`. + - A `cursor` that cannot be decoded is ignored and the first page is returned, with no error. Pass the cursor exactly as it was returned, and stop when the returned `cursor` is empty. + + Responses are cached for a short time, so prices, sizes and `status` can lag the exchange by several seconds, and filtered listings can lag longer than a read of a single market. Use the [WebSocket API](https://docs.kalshi.com/websockets/websocket-connection) when you need current state. + tags: - market parameters: @@ -565,7 +584,7 @@ paths: get: operationId: GetMarket summary: Get Market - description: ' Endpoint for getting data about a specific market by its ticker. A market represents a specific binary outcome within an event that users can trade on (e.g., "Will candidate X win?"). Markets have yes/no positions, current prices, volume, and settlement rules.' + description: ' Endpoint for getting data about a specific market by its ticker. A market represents a specific binary outcome within an event that users can trade on (e.g., "Will candidate X win?"). Markets have yes/no positions, current prices, volume, and settlement rules. The response is cached for a short time, so prices, sizes and `status` can lag the exchange by a few seconds; use the WebSocket API when you need current state.' tags: - market parameters: @@ -592,7 +611,7 @@ paths: Endpoint for retrieving candlestick data for multiple markets. - Accepts up to 100 market tickers per request - - Returns up to 10,000 candlesticks total across all markets + - The request may cover at most 10,000 candlestick periods in total: the minutes between `start_ts` and `end_ts`, divided by `period_interval`, multiplied by the number of tickers. A larger request is rejected with 400 `bad_request` (the `details` field gives the requested and maximum counts) even if fewer candlesticks exist; the response is never truncated - Returns candlesticks grouped by market_id - Optionally includes a synthetic initial candlestick for price continuity (see `include_latest_before_start` parameter) tags: @@ -1066,7 +1085,7 @@ paths: get: operationId: GetOrder summary: Get Order - description: ' Endpoint for getting a single order.' + description: ' Endpoint for getting a single order. Order reads are updated asynchronously after the matching engine processes a write, so an order created, amended or cancelled moments ago can briefly return `404 not_found` or its previous state. The response of the write itself is the only immediate result; the `user_orders` WebSocket channel is also asynchronous and is the stream to wait on for updates.' x-mint: content: | @@ -1162,7 +1181,7 @@ paths: post: operationId: CreateOrderV2 summary: Create Order (V2) - description: 'Endpoint for submitting event-market orders using the V2 request/response shape (single-book `bid`/`ask` side and fixed-point dollar prices). The legacy `/portfolio/orders` endpoint will be deprecated no earlier than May 6, 2026 — clients should migrate to this path.' + description: 'Endpoint for submitting event-market orders using the V2 request/response shape (single-book `bid`/`ask` side and fixed-point dollar prices). The legacy `/portfolio/orders` write endpoints (create, cancel, amend, decrease and their batch forms) have been removed and now return `410 Gone` with code `deprecated_v1_order_endpoint`; use this path instead. A `201` means the order was accepted, not that it is resting: check `remaining_count`. See [Order Errors](/getting_started/order_errors) for the error codes this endpoint returns.' tags: - orders security: @@ -1228,7 +1247,7 @@ paths: post: operationId: BatchCreateOrdersV2 summary: Batch Create Orders (V2) - description: 'Endpoint for submitting a batch of event-market orders using the V2 request/response shape. The maximum batch size scales with your tier''s write budget — see [Rate Limits and Tiers](/getting_started/rate_limits).' + description: 'Endpoint for submitting a batch of event-market orders using the V2 request/response shape. The maximum batch size scales with your tier''s write budget — see [Rate Limits and Tiers](/getting_started/rate_limits). Orders are processed one at a time in request order and the batch is not atomic: a `201` response carries one entry per order, and an order that failed has an `error` object (`code`, `message`, `details`) in place of `order_id`. An entry error with a timeout or unavailable code does not prove the order was not placed. Some checks reject the whole batch before any order is sent. See [Order Errors](/getting_started/order_errors#batch-requests) for those cases and for the error body.' x-mint: content: | @@ -1265,7 +1284,7 @@ paths: delete: operationId: BatchCancelOrdersV2 summary: Batch Cancel Orders (V2) - description: 'Endpoint for cancelling a batch of event-market orders using the V2 response shape. To auto-route a cancellation, provide its `market_ticker` and omit `exchange_index` or set it to `-1`. The maximum batch size scales with your tier''s write budget — see [Rate Limits and Tiers](/getting_started/rate_limits).' + description: 'Endpoint for cancelling a batch of event-market orders using the V2 response shape. To auto-route a cancellation, provide its `market_ticker` and omit `exchange_index` or set it to `-1`. The maximum batch size scales with your tier''s write budget — see [Rate Limits and Tiers](/getting_started/rate_limits). The batch is not atomic: the `200` response carries one entry per order, and a cancellation that failed has an `error` object and `reduced_by` of `0.00`. An entry error with a timeout or unavailable code does not prove the order was not cancelled. Some checks reject the whole batch before any cancellation is sent. See [Order Errors](/getting_started/order_errors#batch-requests).' x-mint: content: | @@ -1348,7 +1367,7 @@ paths: delete: operationId: CancelOrderV2 summary: Cancel Order (V2) - description: 'Endpoint for cancelling event-market orders using the V2 response shape. To auto-route the cancellation, provide `market_ticker` and omit `exchange_index` or set it to `-1`. Returns `{order_id, client_order_id, reduced_by}` rather than a full order object.' + description: 'Endpoint for cancelling event-market orders using the V2 response shape. To auto-route the cancellation, provide `market_ticker` and omit `exchange_index` or set it to `-1`. Returns `{order_id, client_order_id, reduced_by}` rather than a full order object. A cancellation sent to an exchange shard other than the one the order rests on returns `404`, even though the order is still resting; see [Order Errors](/getting_started/order_errors#requests-sent-to-the-wrong-exchange-shard).' x-mint: content: | @@ -1396,7 +1415,7 @@ paths: post: operationId: AmendOrderV2 summary: Amend Order (V2) - description: 'Endpoint for amending the price, max fillable count, and/or expiration time of an existing event-market order. The request `count` is the updated total/max fillable count, equal to already filled count plus desired resting remaining count. This behavior matches the v1 amend endpoints; only the request/response shape differs.' + description: 'Endpoint for amending the price, max fillable count, and/or expiration time of an existing event-market order. The request `count` is the updated total/max fillable count, equal to already filled count plus desired resting remaining count. An amend that changes nothing returns `400` with code `AMEND_ORDER_NO_OP`. See [Order Errors](/getting_started/order_errors).' x-mint: content: | @@ -1741,6 +1760,10 @@ paths: When `source_exchange_shard` and `destination_exchange_shard` are the same, Kalshi treats the request as a subaccount transfer. The returned transfer ID appears in the subaccount transfer history. Cross-exchange-index subaccount transfers run in up to three non-atomic steps. If a later step fails, completed steps are not undone, so funds may remain in the primary account on the source or destination exchange index. + + Naming a numbered subaccount requires the Advanced API tier or above; on the Basic tier the request returns 403 with code `subaccount_creation_requires_advanced_api_usage_level`. + + **Rate limit:** this endpoint has its own bucket, separate from the Read and Write budgets and the same on every tier. It refills at 600 tokens per minute and holds 600 tokens; at the default cost of 10 tokens that is 60 transfers per minute. A request over the limit returns 429. tags: - portfolio security: @@ -1835,7 +1858,7 @@ paths: post: operationId: CreateSubaccount summary: Create Subaccount - description: 'Creates a new subaccount for the authenticated user. This endpoint is available to all users on the Advanced API tier and above. Subaccounts are numbered sequentially starting from 1. Maximum 63 numbered subaccounts per user (64 including the primary account).' + description: 'Creates a new subaccount for the authenticated user. This endpoint is available to all users on the Advanced API tier and above; on the Basic tier it returns 403 with code `subaccount_creation_requires_advanced_api_usage_level`. The demo environment does not enforce the tier requirement. Subaccounts are numbered sequentially starting from 1. Maximum 63 numbered subaccounts per user (64 including the primary account).' tags: - portfolio security: @@ -2039,6 +2062,7 @@ paths: description: | Returns settlement records still in the live data set. Archived positions are available via `GET /historical/positions`, which has different fields; this endpoint does not return archived settlement records. Resource-bound MCP OAuth tokens may read the owner's settlements with read::mcp_portfolio. + Available to direct member accounts. FCM member accounts receive 403 with code `permission_denied`. tags: - portfolio security: @@ -2189,6 +2213,7 @@ paths: Endpoint for getting all fills for the member. A fill is when a trade you have is matched. Registered partners may also use a user OAuth access token with the explicitly granted read::compliance_partner scope. Fills that occurred before the historical cutoff are only available via `GET /historical/fills`. See [Historical Data](https://docs.kalshi.com/getting_started/historical_data) for details. + Available to direct member accounts. FCM member accounts receive 403 with code `permission_denied` here and use `GET /fcm/fills` instead. tags: - portfolio security: @@ -3447,7 +3472,7 @@ paths: post: operationId: CreateApiKey summary: Create API Key - description: ' Endpoint for creating a new API key with a user-provided public key. This endpoint allows users with Premier or Market Maker API usage levels to create API keys by providing their own RSA or Ed25519 public key in PEM format. The platform will use this public key to verify signatures on API requests: RSA-PSS with SHA-256 for RSA keys, Ed25519 for Ed25519 keys.' + description: ' Endpoint for creating a new API key with a user-provided public key. This endpoint is available on every API usage tier. Provide your own RSA or Ed25519 public key in PEM format. The platform will use this public key to verify signatures on API requests: RSA-PSS with SHA-256 for RSA keys, Ed25519 for Ed25519 keys. In production, an account can hold up to 100 directly managed API keys (keys created on the account settings page or through the API key endpoints).' tags: - api-keys security: @@ -3472,9 +3497,9 @@ paths: '401': description: Unauthorized '403': - description: Forbidden - insufficient API usage level, or fcm_subtrader_id from a non-FCM caller + description: Forbidden - the calling API key lacks the `write` scope, or fcm_subtrader_id from a non-FCM caller '409': - description: Conflict - the bound FCM subtrader is not yet visible in the credential registry; retry after the subtrader create propagates + description: Conflict - the account already holds the maximum number of directly managed API keys, 100 in production (code `MAXIMUM_NUMBER_OF_API_KEYS_REACHED`); or the bound FCM subtrader is not yet visible in the credential registry, in which case retry after the subtrader create propagates '500': description: Internal server error @@ -3482,7 +3507,7 @@ paths: post: operationId: GenerateApiKey summary: Generate API Key - description: ' Endpoint for generating a new API key with an automatically created key pair. This endpoint generates a key pair of the requested key_type (RSA when omitted). The public key is stored on the platform, while the private key is returned to the user and must be stored securely. The private key cannot be retrieved again.' + description: ' Endpoint for generating a new API key with an automatically created key pair. This endpoint generates a key pair of the requested key_type (RSA when omitted). The public key is stored on the platform, while the private key is returned to the user and must be stored securely. The private key cannot be retrieved again. In production, an account can hold up to 100 directly managed API keys (keys created on the account settings page or through the API key endpoints).' tags: - api-keys security: @@ -3507,9 +3532,9 @@ paths: '401': description: Unauthorized '403': - description: Forbidden - fcm_subtrader_id requires an FCM member caller + description: Forbidden - the calling API key lacks the `write` scope, or fcm_subtrader_id requires an FCM member caller '409': - description: Conflict - the bound FCM subtrader is not yet visible in the credential registry; retry after the subtrader create propagates + description: Conflict - the account already holds the maximum number of directly managed API keys, 100 in production (code `MAXIMUM_NUMBER_OF_API_KEYS_REACHED`); or the bound FCM subtrader is not yet visible in the credential registry, in which case retry after the subtrader create propagates '500': description: Internal server error @@ -4281,6 +4306,254 @@ paths: '500': $ref: '#/components/responses/InternalServerError' + /concert_cancellation_markets: + post: + operationId: CreateConcertCancellationMarket + summary: Create Concert Cancellation Market + description: | + Returns the on-request 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 + 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. + + Take `jambase_event_id` and `scheduled_date` from + `GET /concert_cancellation_markets/concerts` or + `GET /concert_cancellation_markets/concerts/search`. A new market is + created from the show's listing as it stands now, so the request is + refused when the show has moved to another date or has already been + canceled or postponed. + + An existing market is returned until it closes, even when new markets + are no longer offered. A new market's show must start more than an + hour from now and within the `max_days_ahead` that + `GET /concert_cancellation_markets/availability` reports. + + A market is traded through RFQs: pass the returned `market_ticker` to + `POST /communications/rfqs`. These markets are in series starting with + `KXRFQ` and are left out of unscoped market listings. + + A market created a moment ago may not be readable yet: if + `GET /markets/{ticker}` returns 404 right after creation, retry. + + Errors carry the specific reason in `details`: + + | Status | `code` | When | + | --- | --- | --- | + | 400 | `bad_request` | The body isn't valid JSON, or a field has the wrong type. | + | 400 | `missing_parameters` | A required field is missing or empty. | + | 400 | `invalid_parameters` | A field is present but unusable: an unknown cover, a `jambase_event_id` that isn't `jambase:`, a `scheduled_date` that isn't YYYY-MM-DD, or a show scheduled further ahead than `max_days_ahead`. | + | 404 | `not_found` | The listing source has no show with that id. | + | 409 | `concert_cancellation_market_unavailable` | The request is valid but the market isn't offered: concert markets or the cover are switched off, the show is now listed on another date, has already been canceled or postponed, starts too soon, isn't a concert, or its market has closed. | + | 429 | `concert_cancellation_market_limit_exceeded` | The daily limit on new concert markets across all users was reached. Retrying at once doesn't help. | + | 429 | `too_many_requests` | Your API rate limit. This endpoint is charged against your write budget. | + tags: + - markets + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateConcertCancellationMarketRequest' + responses: + '200': + description: Market returned or created successfully + content: + application/json: + schema: + $ref: '#/components/schemas/CreateConcertCancellationMarketResponse' + '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' + + /concert_cancellation_markets/availability: + get: + operationId: GetConcertCancellationAvailability + summary: Get Concert Cancellation Market Availability + description: | + Returns which on-request concert markets can be created: whether + creation is on, 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 + from `covers` can't be created. Existing markets are unaffected. + + Each metro carries the number of upcoming shows listed for it. Pass + `date_from` and `date_to` to count only the shows a listing with the + same dates would return. + tags: + - markets + parameters: + - name: date_from + in: query + required: false + description: Count shows from this venue-local date, as YYYY-MM-DD. Omitted counts from today. + schema: + type: string + x-oapi-codegen-extra-tags: + validate: omitempty,datetime=2006-01-02 + - name: date_to + in: query + required: false + description: Count shows up to this venue-local date, inclusive, as YYYY-MM-DD. Omitted for no end. + schema: + type: string + x-oapi-codegen-extra-tags: + validate: omitempty,datetime=2006-01-02 + responses: + '200': + description: Availability retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetConcertCancellationAvailabilityResponse' + '400': + $ref: '#/components/responses/BadRequestError' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + + /concert_cancellation_markets/concerts: + get: + operationId: GetConcerts + summary: Get Concerts + description: | + Lists a metro's upcoming concerts that a cancellation market can still + be created for, soonest first, 50 to a page and at most 20 pages. + Narrow the dates to reach later shows. Each concert carries the + `jambase_event_id` and `scheduled_date` that + `POST /concert_cancellation_markets` takes, and the event and market + tickers it has or would get for each offered cover. A ticker listed + here names a market that may not exist yet: create it before sending + an RFQ. + + Dates and times are local to the venue. + tags: + - markets + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + parameters: + - name: metro_id + in: query + required: true + description: One of the metros from `GET /concert_cancellation_markets/availability`, such as `jambase:1`. + schema: + type: string + x-oapi-codegen-extra-tags: + validate: required + - name: date_from + in: query + required: false + description: List shows from this venue-local date, as YYYY-MM-DD. Omitted, or a date that has passed, lists from today. Pages count from it. + schema: + type: string + x-oapi-codegen-extra-tags: + validate: omitempty,datetime=2006-01-02 + - name: date_to + in: query + required: false + description: List shows up to this venue-local date, inclusive, as YYYY-MM-DD. Must not be before `date_from`. Omitted for no end. + schema: + type: string + x-oapi-codegen-extra-tags: + validate: omitempty,datetime=2006-01-02 + - name: page + in: query + required: false + description: Page to return, starting at 1. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 20 + default: 1 + x-oapi-codegen-extra-tags: + validate: omitempty,min=1,max=20 + responses: + '200': + description: Concerts retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetConcertsResponse' + '400': + $ref: '#/components/responses/BadRequestError' + '401': + $ref: '#/components/responses/UnauthorizedError' + '409': + $ref: '#/components/responses/ConflictError' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + + /concert_cancellation_markets/concerts/search: + get: + operationId: SearchConcerts + summary: Search Concerts + description: | + Lists upcoming concerts matching a name, across metros, that a + cancellation market can still be created for: up to 50, in the same + shape as `GET /concert_cancellation_markets/concerts`. The name is + matched against the acts on the bill, and may also match venues and + cities. + + Searches can be limited across all users. When the limit is reached + the request returns 429 `concert_search_limit_exceeded`; browse by + metro instead, or retry later. + tags: + - markets + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + parameters: + - name: q + in: query + required: true + description: The name to search for, or part of one. 2 to 80 characters; some searches need at least 3. + schema: + type: string + minLength: 2 + maxLength: 80 + x-oapi-codegen-extra-tags: + validate: required,min=2,max=80 + responses: + '200': + description: Concerts retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/SearchConcertsResponse' + '400': + $ref: '#/components/responses/BadRequestError' + '401': + $ref: '#/components/responses/UnauthorizedError' + '409': + $ref: '#/components/responses/ConflictError' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + /multivariate_event_collections/{collection_ticker}: get: operationId: GetMultivariateEventCollection @@ -4311,7 +4584,7 @@ paths: post: operationId: CreateMarketInMultivariateEventCollection summary: Create Market In Multivariate Event Collection - description: 'Endpoint for creating an individual market in a multivariate event collection. This endpoint must be hit at least once before trading or looking up a market. Users are limited to 5000 creations per week.' + description: 'Endpoint for creating an individual market in a multivariate event collection. This endpoint must be hit at least once before a combo market can be quoted or traded. If the same legs were created before, it returns the existing market, which does not count toward the limit; the legs are still validated again, so a selection that worked before can later be rejected. On the production API, the standard limit is 5000 new markets per user per rolling 7 days, counted both across all collections and within each collection; over either limit the endpoint returns 429 `too_many_requests` until earlier creations pass the 7-day mark. Ordinary request-rate limiting returns the same status and code. A leg selection that cannot be combined returns 400 with `code` `conflicting_leg_outcomes`, `duplicated_legs` or `invalid_market_combination`.' tags: - multivariate security: @@ -5115,7 +5388,7 @@ paths: get: operationId: GetMarketCandlesticksHistorical summary: Get Historical Market Candlesticks - description: ' Endpoint for fetching historical candlestick data for markets that have been archived from the live data set. Time period length of each candlestick in minutes. Valid values: 1 (1 minute), 60 (1 hour), 1440 (1 day).' + description: ' Endpoint for fetching historical candlestick data for markets that have been archived from the live data set. Time period length of each candlestick in minutes. Valid values: 1 (1 minute), 60 (1 hour), 1440 (1 day). One request can span at most 5,000 periods: if the minutes between `start_ts` and `end_ts` divided by `period_interval` exceed 5,000, the request is rejected with 400 `bad_request`. Split a longer range into several requests.' tags: - historical parameters: @@ -9441,7 +9714,7 @@ components: description: Whether to rest the remainder of the RFQ after execution replace_existing: type: boolean - description: Whether to delete existing RFQs as part of this RFQ's creation + description: Whether to close your older open RFQs to make room for this one. When true, the oldest open RFQs on the subaccount are closed, on any market, until at most two remain open including this one. An RFQ with a confirmed quote, or with an accepted quote still inside its confirmation window, is never closed, so the RFQ that stays open is not always the newest. If too few RFQs can be closed, the request fails with `expired`. It also skips the one-open-RFQ-per-market check. default: false x-go-type-skip-optional-pointer: true subtrader_id: @@ -10454,6 +10727,7 @@ components: validate: required,min=1 client_order_id: type: string + description: 'Optional client-assigned ID, up to 64 characters from letters, digits and `_ - : + = /`. It must be unique per subaccount on the market''s exchange shard while the order is open. See [Order Errors](/getting_started/order_errors#client-order-ids).' x-go-type-skip-optional-pointer: true side: $ref: '#/components/schemas/BookSide' @@ -10974,24 +11248,24 @@ components: type: array items: type: string - 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 Lookup and Create endpoints.' + 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 Lookup/Create affects the output. If false, the order does not matter. + 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. 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 Lookup/Create.' + description: '[DEPRECATED - Use associated_events instead] Whether the collection accepts multiple markets from the same event passed into Create.' is_all_yes: type: boolean description: '[DEPRECATED - Use associated_events instead] Whether the collection requires that only the market side of ''yes'' may be used.' size_min: type: integer format: int32 - description: The minimum number of markets that must be passed into Lookup/Create (inclusive). + description: The minimum number of markets that must be passed into Create (inclusive). size_max: type: integer format: int32 - description: The maximum number of markets that must be passed into Lookup/Create (inclusive). + description: The maximum number of markets that must be passed into Create (inclusive). functional_description: type: string description: A functional description of the collection describing how inputs affect the output. @@ -11277,6 +11551,238 @@ components: $ref: '#/components/schemas/WeatherPointVariableAvailability' description: The variables on offer and where. A variable left out can't be created. + ConcertCover: + type: string + enum: + - postponed + - cancelled + - either + # Named so the generated constants don't collide with status values. + x-enum-varnames: + - ConcertCoverPostponed + - ConcertCoverCancelled + - ConcertCoverEither + description: | + What a concert cancellation market pays on, read from the show's + listing after its scheduled date has ended: + - `postponed`: Yes when the show is listed as postponed, or as taking + place on any other date. A show listed as canceled resolves to No. + - `cancelled`: Yes when the show is listed as canceled. + - `either`: Yes in both of those cases. + + CreateConcertCancellationMarketRequest: + type: object + required: + - jambase_event_id + - scheduled_date + - cover + properties: + jambase_event_id: + type: string + description: The show, as `jambase:`, from the concert listing or search. + example: jambase:16543035 + x-oapi-codegen-extra-tags: + validate: required + scheduled_date: + type: string + description: The venue-local date the show is scheduled for, as YYYY-MM-DD. It must match the show's current listing. + example: '2026-11-20' + x-oapi-codegen-extra-tags: + validate: required,datetime=2006-01-02 + cover: + $ref: '#/components/schemas/ConcertCover' + + CreateConcertCancellationMarketResponse: + type: object + required: + - cover + - event_ticker + - market_ticker + - created + properties: + cover: + $ref: '#/components/schemas/ConcertCover' + event_ticker: + type: string + description: Event ticker of the market. + example: KXRFQCONCERTP-JB16543035-26NOV20 + market_ticker: + type: string + description: Market ticker of the market. + example: KXRFQCONCERTP-JB16543035-26NOV20-PPD + created: + type: boolean + description: False when a market for the same request already existed. + + ConcertMetro: + type: object + required: + - id + - name + - upcoming_shows + properties: + id: + type: string + description: Metro id to pass as `metro_id` when listing concerts. + example: jambase:1 + name: + type: string + description: Metro name. + example: New York + latitude: + type: number + format: double + description: Latitude of the metro's center. Left out when unknown. + longitude: + type: number + format: double + description: Longitude of the metro's center. Left out when unknown. + upcoming_shows: + type: integer + format: int32 + description: Upcoming shows listed in the metro, within the request's dates when given. 0 when no count is available. + x-omitempty: false + + GetConcertCancellationAvailabilityResponse: + type: object + required: + - enabled + - covers + - max_days_ahead + - metros + properties: + enabled: + type: boolean + description: Whether concert cancellation markets can be created at all. + covers: + type: array + items: + $ref: '#/components/schemas/ConcertCover' + description: The covers on offer. A cover left out can't be created. + max_days_ahead: + type: integer + format: int32 + description: How many days ahead a show may be scheduled for a new market. + metros: + type: array + items: + $ref: '#/components/schemas/ConcertMetro' + description: The metros whose concerts are listed. + + ConcertMarket: + type: object + required: + - cover + - event_ticker + - market_ticker + properties: + cover: + $ref: '#/components/schemas/ConcertCover' + event_ticker: + type: string + description: Event ticker the show has or would get for this cover. + market_ticker: + type: string + description: Market ticker the show has or would get for this cover. The market may not exist yet. + + Concert: + type: object + required: + - jambase_event_id + - name + - lineup + - venue_name + - timezone + - scheduled_date + - markets + properties: + jambase_event_id: + type: string + description: The show's id, as `jambase:`. + example: jambase:16543035 + name: + type: string + description: The show's name as listed. + headliner: + type: string + description: The top-billed act. Left out when the listing names none. + lineup: + type: array + items: + type: string + description: The acts on the bill, in billing order. + venue_name: + type: string + description: The venue's name. + city: + type: string + description: The venue's city. + region: + type: string + description: The venue's state or region. + country: + type: string + description: The venue's country code. + timezone: + type: string + description: IANA time zone of the venue, which `scheduled_date` and `start_time` are local to. + example: America/New_York + scheduled_date: + type: string + description: The venue-local date the show is scheduled for, as YYYY-MM-DD. + example: '2026-11-20' + start_time: + type: string + description: Venue-local start time with no UTC offset, as YYYY-MM-DDTHH:MM:SS. Left out while only the date is announced. + example: '2026-11-20T20:00:00' + latitude: + type: number + format: double + description: Latitude of the venue. Left out when unknown. + longitude: + type: number + format: double + description: Longitude of the venue. Left out when unknown. + url: + type: string + description: The show's listing page. + markets: + type: array + items: + $ref: '#/components/schemas/ConcertMarket' + description: One entry per offered cover. + + GetConcertsResponse: + type: object + required: + - concerts + - page + - total_pages + properties: + concerts: + type: array + items: + $ref: '#/components/schemas/Concert' + page: + type: integer + format: int32 + description: The page returned. + total_pages: + type: integer + format: int32 + description: Pages available for this metro and these dates. + x-omitempty: false + + SearchConcertsResponse: + type: object + required: + - concerts + properties: + concerts: + type: array + items: + $ref: '#/components/schemas/Concert' + # Market Orderbook schemas PriceLevelDollarsCountFp: type: array @@ -11924,12 +12430,9 @@ components: format: date-time nullable: true x-omitempty: true - description: Time when this market is expected to expire - expiration_time: - type: string - format: date-time - deprecated: true - x-go-type-skip-optional-pointer: true + description: >- + Time when this market is expected to expire. Never later than + `latest_expiration_time`. latest_expiration_time: type: string format: date-time diff --git a/specs/perps_openapi.yaml b/specs/perps_openapi.yaml index 4f0f2e5..cc24194 100644 --- a/specs/perps_openapi.yaml +++ b/specs/perps_openapi.yaml @@ -520,7 +520,7 @@ paths: post: operationId: CreateMarginOrder summary: Create Order - description: Endpoint for submitting orders in a market. + description: Endpoint for submitting orders in a market. Rejections return an error `code` that names the cause; see Order rejections in the Perps API overview (https://docs.kalshi.com/margin#order-rejections) for the codes and HTTP statuses. tags: - orders security: @@ -558,7 +558,7 @@ paths: x-mint: content: | - **Rate limit:** 10 tokens per request, the same cost as cancelling one margin order. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + **Rate limit:** 10 tokens per request. Cancelling one margin order by ID costs 1 token. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. tags: - orders @@ -1482,7 +1482,7 @@ paths: post: operationId: IntraExchangeInstanceTransfer summary: Intra Account Transfer - description: "Endpoint for transferring funds within the same account." + 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." tags: - portfolio security: @@ -1544,7 +1544,7 @@ paths: post: operationId: ApplyMarginSubaccountTransfer summary: Transfer Between Subaccounts - description: 'Transfers funds between the authenticated user''s margin subaccounts. Use 0 for the primary account, or 1-63 for numbered subaccounts.' + description: 'Transfers funds between the authenticated user''s margin subaccounts. Use 0 for the primary account, or 1-63 for numbered subaccounts. Transfers 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: @@ -1863,7 +1863,10 @@ paths: Endpoint for setting a stop-loss / take-profit bracket or a trailing stop on a non-isolated margin position. A position holds one trailing stop and up to 20 brackets, so long as their counts fit the position. Requires an open position unless - `anchor_order_id` is supplied, and fires reduce-only orders. + `anchor_order_id` is supplied, and fires reduce-only orders. A fired trigger places an + immediate-or-cancel limit order near the stop price, not a market order, so it can fill + partially or not at all. See Exit triggers in the Perps API overview + (https://docs.kalshi.com/margin#exit-triggers) for validation errors and retry behavior. tags: - exit-triggers security: @@ -2518,7 +2521,7 @@ components: description: 'How the grant was created: "volume" (earned from trading volume) or "manual" (assigned by Kalshi).' FixedPointCount: type: string - description: Fixed-point contract count string (2 decimals, e.g., "10.00"; referred to as "fp" in field names). Requests accept 0-2 decimal places (e.g., "10", "10.0", "10.00"); responses always emit 2 decimals. Fractional contract values (e.g., "2.50") are supported; the minimum granularity is 0.01 contracts. + description: Fixed-point contract count string (2 decimals, e.g., "10.00"; referred to as "fp" in field names). Requests accept 0-2 decimal places (e.g., "10", "10.0", "10.00"); responses always emit 2 decimals. A market whose `fractional_trading_enabled` is false trades whole contracts only. There, an order for a fractional count (e.g., "2.50") is rejected with HTTP 400 and error code `invalid_order_size`, and an amend or decrease that would leave a fractional count is rejected with HTTP 400 and error code `invalid_amend_quantity_for_order`. example: "10.00" ExitTriggerKind: type: string @@ -3372,7 +3375,7 @@ components: $ref: '#/components/schemas/MarginMarketStatus' fractional_trading_enabled: type: boolean - description: Whether fractional trading is enabled for this market. + description: Whether fractional trading is enabled for this market. When false, order counts must be whole numbers of contracts. minimum_quantity: $ref: '#/components/schemas/FixedPointCount' description: Minimum order quantity in contracts. @@ -3597,7 +3600,7 @@ components: LastUpdateReason: type: string enum: ['', 'Decrease', 'Amend', 'MarginCancel', 'SelfTradeCancel', 'ExpiryCancel', 'Trade', 'PostOnlyCrossCancel', 'ReduceOnlyCancel'] - description: ReduceOnlyCancel means reduce_only capped the order at placement. + description: ReduceOnlyCancel means reduce_only capped the order at placement. The empty string is returned for every other update, including an order canceled because its market closed or halted, or because its order group triggered. The WebSocket `user_orders` channel reports those reasons by name. MarginMarketResponse: type: object @@ -3679,6 +3682,7 @@ components: description: Incremental realized PnL contributed by this fill, in fixed-point dollars order_source: $ref: '#/components/schemas/OrderSource' + description: Whether the order behind this fill was placed by the user or by the system. `system` covers liquidation, TP/SL and auto-rebalance orders alike; to tell them apart, fetch the order by `order_id` and read its `order_reason`. GetMarginPositionsResponse: type: object diff --git a/specs/perps_scm_openapi.yaml b/specs/perps_scm_openapi.yaml index 7fe8c65..56d0823 100644 --- a/specs/perps_scm_openapi.yaml +++ b/specs/perps_scm_openapi.yaml @@ -1010,10 +1010,11 @@ components: reportable_threshold: { type: integer, format: int64, description: 'CFTC reporting level for this market, in contracts (17 CFR 15.03(b)). A position of at least this size in either direction is reportable.' } EstimatePortfolioMaintenanceMarginPosition: type: object - required: [market_ticker, quantity] + required: [market_ticker] properties: market_ticker: { type: string, description: Market to include in the hypothetical portfolio. Must belong to the request's asset class. } - quantity: { type: integer, format: int64, description: "Signed whole contract count; positive long, negative short. Must be non-zero." } + quantity: { type: integer, format: int64, description: "Signed whole contract count; positive long, negative short. Must be non-zero. Provide `quantity` or `quantity_fp`." } + quantity_fp: { type: string, description: "Signed contract count as a fixed-point string with at most two decimal places (e.g. \"0.25\", \"-1.50\"); positive long, negative short. Must be non-zero and at most 1000000 in magnitude, and must equal `quantity` when both are given." } price: { type: string, description: 'Price of one contract in USD, to at most four decimal places (e.g. "6.8000"). Must be positive. Omit to use the market''s mark price from its latest settlement (before the end of `date`, if set); returns 400 if there is none.' } EstimatePortfolioMaintenanceMarginRequest: From 1e3207c06f2636974e3842183fc251421d66c013 Mon Sep 17 00:00:00 2001 From: Jeff West Date: Fri, 13 Nov 2026 09:45:39 -0600 Subject: [PATCH 2/2] =?UTF-8?q?feat(markets):=20concert=20cancellation=20m?= =?UTF-8?q?arkets=20+=20perps=20estimate=20quantity=5Ffp=20(#582)=20?= =?UTF-8?q?=E2=80=94=2022.14.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 38 ++ CLAUDE.md | 2 +- README.md | 2 +- docs/index.md | 2 +- docs/perps.md | 7 +- docs/resources/markets.md | 34 ++ kalshi/__init__.py | 20 +- kalshi/_contract_map.py | 32 + kalshi/models/__init__.py | 18 + kalshi/models/markets.py | 102 ++++ kalshi/perps/klear/models/margin.py | 25 +- kalshi/resources/markets.py | 218 +++++++ pyproject.toml | 2 +- tests/_contract_support.py | 21 + tests/perps/klear/test_margin.py | 44 ++ tests/test_concert_cancellation_markets.py | 646 +++++++++++++++++++++ tests/test_contracts.py | 3 + 17 files changed, 1205 insertions(+), 11 deletions(-) create mode 100644 tests/test_concert_cancellation_markets.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 02fdf16..84cb098 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,44 @@ All notable changes to kalshi-sdk will be documented in this file. +## 22.14.0 — 2026-11-13 + +Adds on-request concert cancellation markets (#582) against OpenAPI v3.36.0 +and reconciles perps SCM estimate-position quantity drift. Additive only. +No breaking changes. + +### Added + +- **`markets.create_concert_cancellation_market(...)`** (sync and async) — + `POST /concert_cancellation_markets`, 200 `CreateConcertCancellationMarketResponse`. + Authenticated. Returns the concert cancellation market for a show, date and + cover, creating it if it does not exist. `created` is false when a market + for the same request already existed. Required: `jambase_event_id`, + `scheduled_date` (YYYY-MM-DD), `cover` (`ConcertCoverLiteral`: `"postponed"` + / `"cancelled"` / `"either"`). Accepts + `request=CreateConcertCancellationMarketRequest(...)` or keyword fields. + POST is never retried. +- **`markets.concert_cancellation_availability(...)`** (sync and async) — + `GET /concert_cancellation_markets/availability`, 200 + `GetConcertCancellationAvailabilityResponse` (`enabled`, `covers`, + `max_days_ahead`, `metros` as `ConcertMetro`). Public. Optional `date_from` + / `date_to` bound the upcoming-show counts. +- **`markets.list_concerts(*, metro_id, ...)`** (sync and async) — + `GET /concert_cancellation_markets/concerts`, 200 `GetConcertsResponse`. + Authenticated. Lists a metro's upcoming concerts. Optional `date_from`, + `date_to`, `page`. No SDK paginator. +- **`markets.search_concerts(*, q)`** (sync and async) — + `GET /concert_cancellation_markets/concerts/search`, 200 + `SearchConcertsResponse`. Authenticated. Name search across metros. + (Closes #582). + +### Changed + +- Perps Klear **`EstimatePortfolioMaintenanceMarginPosition.quantity`** is + optional; new optional **`quantity_fp`** (`FixedPointCount`, serialized as a + string). Provide `quantity` or `quantity_fp`. A position with neither size + field fails validation. + ## 22.13.0 — 2026-11-12 Reconciles spec drift (#580): incentive schedules, incentive-program diff --git a/CLAUDE.md b/CLAUDE.md index becfe3b..4464427 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -122,7 +122,7 @@ tests/ ## API Reference -- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.36.0, 138 operations; 137 mapped in the core SDK — `POST /portfolio/intra_exchange_instance_transfer` is implemented on `PerpsClient.transfers.transfer_instance` and left unimplemented on the core client) +- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.36.0, 142 operations; 141 mapped in the core SDK — `POST /portfolio/intra_exchange_instance_transfer` is implemented on `PerpsClient.transfers.transfer_instance` and left unimplemented on the core client) - AsyncAPI spec: https://docs.kalshi.com/asyncapi.yaml (16 WebSocket channels; 13 typed `subscribe_*` + escape-hatch) - Base URL: https://api.elections.kalshi.com/trade-api/v2 - Demo URL: https://demo-api.kalshi.co/trade-api/v2 diff --git a/README.md b/README.md index a2d5789..b42ffdc 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 (137 mapped of 138 operations across 19 resources, OpenAPI v3.36.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch). +- **Full coverage** of the Kalshi REST API (141 mapped of 142 operations across 19 resources, OpenAPI v3.36.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch). - **Perps (margin) API**: standalone `PerpsClient` / `AsyncPerpsClient` + `PerpsWebSocket` for the perpetual-futures exchange (54 REST operations, 6 WS channels), plus a `KlearClient` for the Self-Clearing-Member "Klear" settlement API (26 of 27 operations). See [Perps (margin) trading](#perps-margin-trading). - **FIX protocol**: an async-first FIX engine (FIXT.1.1 / FIX50SP2) for both products — order-entry, drop-copy, market-data, post-trade (prediction), and RFQ (prediction) sessions (plus order-group management over the order-entry session) with typed message models, sequence recovery, and order-book / settlement reassembly. `from kalshi import FixClient` / `MarginFixClient`. See [FIX protocol](#fix-protocol-low-latency-trading). - **V2 event-market orders**: `create_v2` / `amend_v2` / `decrease_v2` / `cancel_v2` / `cancel_all_v2` plus batched variants on `/portfolio/events/orders/*` — the only order-write surface. diff --git a/docs/index.md b/docs/index.md index 3cb7d11..7fbb49b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,7 +3,7 @@ A professional, spec-first Python SDK for the [Kalshi](https://kalshi.com) prediction markets API. -- **Full REST coverage** — 137 mapped of 138 operations across 19 resources +- **Full REST coverage** — 141 mapped of 142 operations across 19 resources (OpenAPI v3.36.0), every kwarg drift-tested against the spec. - **V2 event-market orders** — new `create_v2` / `amend_v2` / `decrease_v2` / `cancel_v2` / `cancel_all_v2` family on `/portfolio/events/orders/*`. Legacy `/portfolio/orders` diff --git a/docs/perps.md b/docs/perps.md index e5d07b3..f31fae4 100644 --- a/docs/perps.md +++ b/docs/perps.md @@ -381,9 +381,10 @@ in the v11.0.0 reconcile.) or `"Energy"`. `klear.margin.settlement_prices(asset_class="Crypto", settlement_time=...)` returns a ticker → centicents map at a settlement cycle. `klear.margin.estimate_maintenance_margin(asset_class="Crypto", positions=[...])` -margins a hypothetical portfolio. Optional `date=` (YYYY-MM-DD) and -`clearing_type=` (`"FCM"` / `"SelfClearing"`) select the matrix day and -clearing arrangement. +margins a hypothetical portfolio. Each position takes `market_ticker` and a +size — `quantity` (whole contracts) or `quantity_fp` (fixed-point string such +as `"0.25"`). Optional `date=` (YYYY-MM-DD) and `clearing_type=` (`"FCM"` / +`"SelfClearing"`) select the matrix day and clearing arrangement. `klear.margin.estimate_maintenance_margin_metadata(asset_class="Crypto", date=...)` returns the matrices, liquidation configs, and subgroups that feed that estimate. diff --git a/docs/resources/markets.md b/docs/resources/markets.md index bc8018a..7bedaa9 100644 --- a/docs/resources/markets.md +++ b/docs/resources/markets.md @@ -19,6 +19,10 @@ recent trades. | `list_all_trades(...)` | walks `list_trades` | no | | `create_weather_point_market(...)` | `POST /weather_point_markets` | **yes** | | `weather_point_availability()` | `GET /weather_point_markets/availability` | no | +| `create_concert_cancellation_market(...)` | `POST /concert_cancellation_markets` | **yes** | +| `concert_cancellation_availability(...)` | `GET /concert_cancellation_markets/availability` | no | +| `list_concerts(*, metro_id, ...)` | `GET /concert_cancellation_markets/concerts` | **yes** | +| `search_concerts(*, q)` | `GET /concert_cancellation_markets/concerts/search` | **yes** | !!! warning "Orderbook endpoints require auth" `orderbook()` and `bulk_orderbooks()` raise `AuthRequiredError` on an @@ -173,6 +177,36 @@ unset optional fields are omitted from the wire body. The same request always returns the same market; `created` is false when it already existed. The response coordinates are the snapped NOAA MRMS grid-cell center. +## Concert cancellation markets + +On-request markets on whether a concert is called off. Creation, listing, and +search are authenticated; availability is public. POST is never retried. + +```python +avail = client.markets.concert_cancellation_availability() +print(avail.enabled, avail.covers, avail.max_days_ahead) +print([m.name for m in avail.metros]) + +page = client.markets.list_concerts(metro_id=avail.metros[0].id) +show = page.concerts[0] + +hits = client.markets.search_concerts(q="Madison Square") + +resp = client.markets.create_concert_cancellation_market( + jambase_event_id=show.jambase_event_id, + scheduled_date=show.scheduled_date, # YYYY-MM-DD + cover="postponed", # ConcertCoverLiteral: "postponed" / "cancelled" / "either" +) +print(resp.market_ticker, resp.created, resp.cover) +``` + +Take `jambase_event_id` and `scheduled_date` from `list_concerts` or +`search_concerts`. A cover missing from `avail.covers` cannot be created. The +same request always returns the same market; `created` is false when it already +existed. Pass the returned `market_ticker` to `POST /communications/rfqs`. +`list_concerts` is paged by the server (`page` / `total_pages`); there is no +SDK paginator. + ## Reference ::: kalshi.resources.markets.MarketsResource diff --git a/kalshi/__init__.py b/kalshi/__init__.py index 86ba4dc..c0bb211 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -57,8 +57,14 @@ BookSideLiteral, CancelOrderV2Response, Candlestick, + Concert, + ConcertCoverLiteral, + ConcertMarket, + ConcertMetro, CreateApiKeyRequest, CreateApiKeyResponse, + CreateConcertCancellationMarketRequest, + CreateConcertCancellationMarketResponse, CreateFCMPositionTransferRequest, CreateFCMPositionTransferResponse, CreateFCMSubtraderRequest, @@ -116,6 +122,8 @@ GetApiKeysResponse, GetBlockTradeProposalsResponse, GetCommunicationsIDResponse, + GetConcertCancellationAvailabilityResponse, + GetConcertsResponse, GetEventContractExitTriggersResponse, GetEventLiveDataResponse, GetFCMEventContractDailyCapResponse, @@ -200,6 +208,7 @@ RfqStatusLiteral, Schedule, ScopeList, + SearchConcertsResponse, SelfTradePreventionTypeLiteral, Series, SeriesFeeChange, @@ -302,8 +311,14 @@ "BookSideLiteral", "CancelOrderV2Response", "Candlestick", + "Concert", + "ConcertCoverLiteral", + "ConcertMarket", + "ConcertMetro", "CreateApiKeyRequest", "CreateApiKeyResponse", + "CreateConcertCancellationMarketRequest", + "CreateConcertCancellationMarketResponse", "CreateFCMPositionTransferRequest", "CreateFCMPositionTransferResponse", "CreateFCMSubtraderRequest", @@ -365,6 +380,8 @@ "GetApiKeysResponse", "GetBlockTradeProposalsResponse", "GetCommunicationsIDResponse", + "GetConcertCancellationAvailabilityResponse", + "GetConcertsResponse", "GetEventContractExitTriggersResponse", "GetEventLiveDataResponse", "GetFCMEventContractDailyCapResponse", @@ -480,6 +497,7 @@ "RfqStatusLiteral", "Schedule", "ScopeList", + "SearchConcertsResponse", "SelfTradePreventionTypeLiteral", "Series", "SeriesFeeChange", @@ -519,4 +537,4 @@ "Withdrawal", ] -__version__ = "22.13.0" +__version__ = "22.14.0" diff --git a/kalshi/_contract_map.py b/kalshi/_contract_map.py index 9db7354..dc0f7bd 100644 --- a/kalshi/_contract_map.py +++ b/kalshi/_contract_map.py @@ -516,6 +516,38 @@ class ContractEntry: sdk_model="kalshi.models.markets.GetWeatherPointAvailabilityResponse", spec_schema="GetWeatherPointAvailabilityResponse", ), + ContractEntry( + sdk_model="kalshi.models.markets.CreateConcertCancellationMarketRequest", + spec_schema="CreateConcertCancellationMarketRequest", + ), + ContractEntry( + sdk_model="kalshi.models.markets.CreateConcertCancellationMarketResponse", + spec_schema="CreateConcertCancellationMarketResponse", + ), + ContractEntry( + sdk_model="kalshi.models.markets.ConcertMetro", + spec_schema="ConcertMetro", + ), + ContractEntry( + sdk_model="kalshi.models.markets.GetConcertCancellationAvailabilityResponse", + spec_schema="GetConcertCancellationAvailabilityResponse", + ), + ContractEntry( + sdk_model="kalshi.models.markets.ConcertMarket", + spec_schema="ConcertMarket", + ), + ContractEntry( + sdk_model="kalshi.models.markets.Concert", + spec_schema="Concert", + ), + ContractEntry( + sdk_model="kalshi.models.markets.GetConcertsResponse", + spec_schema="GetConcertsResponse", + ), + ContractEntry( + sdk_model="kalshi.models.markets.SearchConcertsResponse", + spec_schema="SearchConcertsResponse", + ), # -- orders V2 family (#171) ----------------------------------------- ContractEntry( sdk_model="kalshi.models.orders.CreateOrderV2Request", diff --git a/kalshi/models/__init__.py b/kalshi/models/__init__.py index 3ebea1f..096a2be 100644 --- a/kalshi/models/__init__.py +++ b/kalshi/models/__init__.py @@ -123,8 +123,16 @@ from kalshi.models.markets import ( BidAskDistribution, Candlestick, + Concert, + ConcertCoverLiteral, + ConcertMarket, + ConcertMetro, + CreateConcertCancellationMarketRequest, + CreateConcertCancellationMarketResponse, CreateWeatherPointMarketRequest, CreateWeatherPointMarketResponse, + GetConcertCancellationAvailabilityResponse, + GetConcertsResponse, GetWeatherPointAvailabilityResponse, Market, MarketCandlesticks, @@ -133,6 +141,7 @@ Orderbook, OrderbookLevel, PriceDistribution, + SearchConcertsResponse, WeatherPointDomain, WeatherPointVariableAvailability, WeatherPointVariableLiteral, @@ -279,8 +288,14 @@ "BookSideLiteral", "CancelOrderV2Response", "Candlestick", + "Concert", + "ConcertCoverLiteral", + "ConcertMarket", + "ConcertMetro", "CreateApiKeyRequest", "CreateApiKeyResponse", + "CreateConcertCancellationMarketRequest", + "CreateConcertCancellationMarketResponse", "CreateFCMPositionTransferRequest", "CreateFCMPositionTransferResponse", "CreateFCMSubtraderRequest", @@ -338,6 +353,8 @@ "GetApiKeysResponse", "GetBlockTradeProposalsResponse", "GetCommunicationsIDResponse", + "GetConcertCancellationAvailabilityResponse", + "GetConcertsResponse", "GetEventContractExitTriggersResponse", "GetEventLiveDataResponse", "GetFCMEventContractDailyCapResponse", @@ -422,6 +439,7 @@ "RfqStatusLiteral", "Schedule", "ScopeList", + "SearchConcertsResponse", "SelfTradePreventionTypeLiteral", "Series", "SeriesFeeChange", diff --git a/kalshi/models/markets.py b/kalshi/models/markets.py index 706a4be..95f41da 100644 --- a/kalshi/models/markets.py +++ b/kalshi/models/markets.py @@ -380,3 +380,105 @@ class GetWeatherPointAvailabilityResponse(BaseModel): variables: NullableList[WeatherPointVariableAvailability] model_config = {"extra": "allow"} + + +ConcertCoverLiteral = Literal["postponed", "cancelled", "either"] +"""What a concert cancellation market pays on. Spec: ConcertCover enum.""" + + +class CreateConcertCancellationMarketRequest(BaseModel): + """Body for POST /concert_cancellation_markets. + + Matches spec ``components.schemas.CreateConcertCancellationMarketRequest``. + Required: ``jambase_event_id``, ``scheduled_date`` (YYYY-MM-DD), ``cover``. + """ + + jambase_event_id: str + scheduled_date: str + cover: ConcertCoverLiteral + + model_config = {"extra": "forbid"} + + +class CreateConcertCancellationMarketResponse(BaseModel): + """Response from POST /concert_cancellation_markets.""" + + cover: ConcertCoverLiteral + event_ticker: str + market_ticker: str + created: bool + + model_config = {"extra": "allow"} + + +class ConcertMetro(BaseModel): + """A metro whose concerts ``GET /concert_cancellation_markets/concerts`` lists.""" + + id: str + name: str + latitude: float | None = None + longitude: float | None = None + upcoming_shows: int + + model_config = {"extra": "allow"} + + +class GetConcertCancellationAvailabilityResponse(BaseModel): + """Response from GET /concert_cancellation_markets/availability.""" + + enabled: bool + covers: NullableList[ConcertCoverLiteral] + max_days_ahead: int + metros: NullableList[ConcertMetro] + + model_config = {"extra": "allow"} + + +class ConcertMarket(BaseModel): + """Event and market tickers a show has or would get for one cover.""" + + cover: ConcertCoverLiteral + event_ticker: str + market_ticker: str + + model_config = {"extra": "allow"} + + +class Concert(BaseModel): + """A concert listing that a cancellation market can still be created for.""" + + jambase_event_id: str + name: str + lineup: NullableList[str] + venue_name: str + timezone: str + scheduled_date: str + markets: NullableList[ConcertMarket] + headliner: str | None = None + city: str | None = None + region: str | None = None + country: str | None = None + start_time: str | None = None + latitude: float | None = None + longitude: float | None = None + url: str | None = None + + model_config = {"extra": "allow"} + + +class GetConcertsResponse(BaseModel): + """Response from GET /concert_cancellation_markets/concerts.""" + + concerts: NullableList[Concert] + page: int + total_pages: int + + model_config = {"extra": "allow"} + + +class SearchConcertsResponse(BaseModel): + """Response from GET /concert_cancellation_markets/concerts/search.""" + + concerts: NullableList[Concert] + + model_config = {"extra": "allow"} diff --git a/kalshi/perps/klear/models/margin.py b/kalshi/perps/klear/models/margin.py index 16063a4..e86b83d 100644 --- a/kalshi/perps/klear/models/margin.py +++ b/kalshi/perps/klear/models/margin.py @@ -44,7 +44,7 @@ from decimal import Decimal from typing import Annotated, Literal -from pydantic import AfterValidator, AwareDatetime, BaseModel, Field, SecretStr +from pydantic import AfterValidator, AwareDatetime, BaseModel, Field, SecretStr, model_validator from kalshi.types import DollarDecimal, FixedPointCount, NullableList @@ -615,6 +615,12 @@ def _require_nonzero_quantity(value: int) -> int: return value +def _require_nonzero_quantity_fp(value: Decimal) -> Decimal: + if value == 0: + raise ValueError("quantity_fp must be non-zero") + return value + + def _require_positive_price(value: Decimal) -> Decimal: if value <= 0: raise ValueError(f"price must be positive (got {value})") @@ -622,14 +628,27 @@ def _require_positive_price(value: Decimal) -> Decimal: class EstimatePortfolioMaintenanceMarginPosition(BaseModel): - """One hypothetical position in an estimate-maintenance-margin request.""" + """One hypothetical position in an estimate-maintenance-margin request. + + Provide ``quantity`` (whole contracts) or ``quantity_fp`` (fixed-point + string). At least one size field is required. + """ market_ticker: str - quantity: Annotated[int, AfterValidator(_require_nonzero_quantity)] + quantity: Annotated[int, AfterValidator(_require_nonzero_quantity)] | None = None + quantity_fp: Annotated[FixedPointCount, AfterValidator(_require_nonzero_quantity_fp)] | None = ( + None + ) price: Annotated[DollarDecimal, AfterValidator(_require_positive_price)] model_config = {"extra": "forbid"} + @model_validator(mode="after") + def _require_size(self) -> EstimatePortfolioMaintenanceMarginPosition: + if self.quantity is None and self.quantity_fp is None: + raise ValueError("a position must have a size") + return self + ClearingTypeLiteral = Literal["FCM", "SelfClearing"] """Clearing arrangement whose margin rules to apply on an estimate request.""" diff --git a/kalshi/resources/markets.py b/kalshi/resources/markets.py index 0c005e6..91f7180 100644 --- a/kalshi/resources/markets.py +++ b/kalshi/resources/markets.py @@ -14,8 +14,13 @@ from kalshi.models.markets import ( BatchGetMarketCandlesticksResponse, Candlestick, + ConcertCoverLiteral, + CreateConcertCancellationMarketRequest, + CreateConcertCancellationMarketResponse, CreateWeatherPointMarketRequest, CreateWeatherPointMarketResponse, + GetConcertCancellationAvailabilityResponse, + GetConcertsResponse, GetMarketCandlesticksResponse, GetMarketOrderbooksResponse, GetWeatherPointAvailabilityResponse, @@ -25,6 +30,7 @@ MveFilterLiteral, Orderbook, OrderbookLevel, + SearchConcertsResponse, WeatherPointVariableLiteral, ) from kalshi.resources._base import ( @@ -281,6 +287,33 @@ def _build_create_weather_point_market_body( return request.model_dump(exclude_none=True, by_alias=True, mode="json") +def _build_create_concert_cancellation_market_body( + request: CreateConcertCancellationMarketRequest | None, + *, + jambase_event_id: str | None, + scheduled_date: str | None, + cover: ConcertCoverLiteral | None, +) -> dict[str, Any]: + _check_request_exclusive( + request, + jambase_event_id=jambase_event_id, + scheduled_date=scheduled_date, + cover=cover, + ) + if request is None: + if jambase_event_id is None or scheduled_date is None or cover is None: + raise TypeError( + "create_concert_cancellation_market() requires `jambase_event_id`, " + "`scheduled_date`, and `cover` (or pass `request=...`)" + ) + request = CreateConcertCancellationMarketRequest( + jambase_event_id=jambase_event_id, + scheduled_date=scheduled_date, + cover=cover, + ) + return request.model_dump(exclude_none=True, by_alias=True, mode="json") + + class MarketsResource(SyncResource): """Sync markets API.""" @@ -599,6 +632,100 @@ def weather_point_availability( data = self._get("/weather_point_markets/availability", extra_headers=extra_headers) return GetWeatherPointAvailabilityResponse.model_validate(data) + @overload + def create_concert_cancellation_market( + self, + *, + request: CreateConcertCancellationMarketRequest, + extra_headers: dict[str, str] | None = None, + ) -> CreateConcertCancellationMarketResponse: ... + @overload + def create_concert_cancellation_market( + self, + *, + jambase_event_id: str, + scheduled_date: str, + cover: ConcertCoverLiteral, + extra_headers: dict[str, str] | None = None, + ) -> CreateConcertCancellationMarketResponse: ... + def create_concert_cancellation_market( + self, + *, + request: CreateConcertCancellationMarketRequest | None = None, + jambase_event_id: str | None = None, + scheduled_date: str | None = None, + cover: ConcertCoverLiteral | None = None, + extra_headers: dict[str, str] | None = None, + ) -> CreateConcertCancellationMarketResponse: + """``POST /concert_cancellation_markets``. Not retried. + + Returns the on-request concert cancellation market for a show, date and + cover, creating it if it does not exist. ``created`` is false when a + market for the same request already existed. + """ + self._require_auth() + body = _build_create_concert_cancellation_market_body( + request, + jambase_event_id=jambase_event_id, + scheduled_date=scheduled_date, + cover=cover, + ) + data = self._post("/concert_cancellation_markets", json=body, extra_headers=extra_headers) + return CreateConcertCancellationMarketResponse.model_validate(data) + + def concert_cancellation_availability( + self, + *, + date_from: str | None = None, + date_to: str | None = None, + extra_headers: dict[str, str] | None = None, + ) -> GetConcertCancellationAvailabilityResponse: + """``GET /concert_cancellation_markets/availability``. Public.""" + params = _params(date_from=date_from, date_to=date_to) + data = self._get( + "/concert_cancellation_markets/availability", + params=params, + extra_headers=extra_headers, + ) + return GetConcertCancellationAvailabilityResponse.model_validate(data) + + def list_concerts( + self, + *, + metro_id: str, + date_from: str | None = None, + date_to: str | None = None, + page: int | None = None, + extra_headers: dict[str, str] | None = None, + ) -> GetConcertsResponse: + """``GET /concert_cancellation_markets/concerts``. Authenticated.""" + self._require_auth() + params = _params( + metro_id=metro_id, + date_from=date_from, + date_to=date_to, + page=page, + ) + data = self._get( + "/concert_cancellation_markets/concerts", + params=params, + extra_headers=extra_headers, + ) + return GetConcertsResponse.model_validate(data) + + def search_concerts( + self, *, q: str, extra_headers: dict[str, str] | None = None + ) -> SearchConcertsResponse: + """``GET /concert_cancellation_markets/concerts/search``. Authenticated.""" + self._require_auth() + params = _params(q=q) + data = self._get( + "/concert_cancellation_markets/concerts/search", + params=params, + extra_headers=extra_headers, + ) + return SearchConcertsResponse.model_validate(data) + class AsyncMarketsResource(AsyncResource): """Async markets API.""" @@ -918,3 +1045,94 @@ async def weather_point_availability( """Async :meth:`MarketsResource.weather_point_availability`.""" data = await self._get("/weather_point_markets/availability", extra_headers=extra_headers) return GetWeatherPointAvailabilityResponse.model_validate(data) + + @overload + async def create_concert_cancellation_market( + self, + *, + request: CreateConcertCancellationMarketRequest, + extra_headers: dict[str, str] | None = None, + ) -> CreateConcertCancellationMarketResponse: ... + @overload + async def create_concert_cancellation_market( + self, + *, + jambase_event_id: str, + scheduled_date: str, + cover: ConcertCoverLiteral, + extra_headers: dict[str, str] | None = None, + ) -> CreateConcertCancellationMarketResponse: ... + async def create_concert_cancellation_market( + self, + *, + request: CreateConcertCancellationMarketRequest | None = None, + jambase_event_id: str | None = None, + scheduled_date: str | None = None, + cover: ConcertCoverLiteral | None = None, + extra_headers: dict[str, str] | None = None, + ) -> CreateConcertCancellationMarketResponse: + """Async :meth:`MarketsResource.create_concert_cancellation_market`.""" + self._require_auth() + body = _build_create_concert_cancellation_market_body( + request, + jambase_event_id=jambase_event_id, + scheduled_date=scheduled_date, + cover=cover, + ) + data = await self._post( + "/concert_cancellation_markets", json=body, extra_headers=extra_headers + ) + return CreateConcertCancellationMarketResponse.model_validate(data) + + async def concert_cancellation_availability( + self, + *, + date_from: str | None = None, + date_to: str | None = None, + extra_headers: dict[str, str] | None = None, + ) -> GetConcertCancellationAvailabilityResponse: + """Async :meth:`MarketsResource.concert_cancellation_availability`.""" + params = _params(date_from=date_from, date_to=date_to) + data = await self._get( + "/concert_cancellation_markets/availability", + params=params, + extra_headers=extra_headers, + ) + return GetConcertCancellationAvailabilityResponse.model_validate(data) + + async def list_concerts( + self, + *, + metro_id: str, + date_from: str | None = None, + date_to: str | None = None, + page: int | None = None, + extra_headers: dict[str, str] | None = None, + ) -> GetConcertsResponse: + """Async :meth:`MarketsResource.list_concerts`.""" + self._require_auth() + params = _params( + metro_id=metro_id, + date_from=date_from, + date_to=date_to, + page=page, + ) + data = await self._get( + "/concert_cancellation_markets/concerts", + params=params, + extra_headers=extra_headers, + ) + return GetConcertsResponse.model_validate(data) + + async def search_concerts( + self, *, q: str, extra_headers: dict[str, str] | None = None + ) -> SearchConcertsResponse: + """Async :meth:`MarketsResource.search_concerts`.""" + self._require_auth() + params = _params(q=q) + data = await self._get( + "/concert_cancellation_markets/concerts/search", + params=params, + extra_headers=extra_headers, + ) + return SearchConcertsResponse.model_validate(data) diff --git a/pyproject.toml b/pyproject.toml index 23aec2e..0ce9aeb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "22.13.0" +version = "22.14.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/_contract_support.py b/tests/_contract_support.py index fb7916e..ea1e5b8 100644 --- a/tests/_contract_support.py +++ b/tests/_contract_support.py @@ -162,6 +162,27 @@ class Exclusion: http_method="GET", path_template="/weather_point_markets/availability", ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.create_concert_cancellation_market", + http_method="POST", + path_template="/concert_cancellation_markets", + request_body_schema="#/components/schemas/CreateConcertCancellationMarketRequest", + ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.concert_cancellation_availability", + http_method="GET", + path_template="/concert_cancellation_markets/availability", + ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.list_concerts", + http_method="GET", + path_template="/concert_cancellation_markets/concerts", + ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.search_concerts", + http_method="GET", + path_template="/concert_cancellation_markets/concerts/search", + ), # ── account ───────────────────────────────────────────────────────────── MethodEndpointEntry( sdk_method="kalshi.resources.account.AccountResource.limits", diff --git a/tests/perps/klear/test_margin.py b/tests/perps/klear/test_margin.py index 0f18f7c..eee9795 100644 --- a/tests/perps/klear/test_margin.py +++ b/tests/perps/klear/test_margin.py @@ -1454,9 +1454,53 @@ def test_kwargs(self, auth_klear_client: KlearClient) -> None: body = json.loads(route.calls[0].request.content) assert body["asset_class"] == "Crypto" assert body["positions"][0]["quantity"] == 2 + assert "quantity_fp" not in body["positions"][0] assert body["positions"][0]["price"] == "6.8000" auth_klear_client.close() + @respx.mock + def test_quantity_fp_only(self, auth_klear_client: KlearClient) -> None: + from kalshi.perps.klear.models.margin import ( + EstimatePortfolioMaintenanceMarginPosition, + ) + + route = respx.post(f"{BASE}/margin/estimate_maintenance_margin").mock( + return_value=httpx.Response(200, json={"maintenance_margin_fp": "1234.5600"}) + ) + pos = EstimatePortfolioMaintenanceMarginPosition( + market_ticker="BTC-PERP", + quantity_fp=Decimal("0.25"), + price=Decimal("6.8000"), + ) + auth_klear_client.margin.estimate_maintenance_margin( + asset_class="Crypto", positions=[pos] + ) + body = json.loads(route.calls[0].request.content) + assert "quantity" not in body["positions"][0] + assert body["positions"][0]["quantity_fp"] == "0.25" + assert body["positions"][0]["price"] == "6.8000" + auth_klear_client.close() + + def test_neither_quantity_raises(self) -> None: + from kalshi.perps.klear.models.margin import ( + EstimatePortfolioMaintenanceMarginPosition, + ) + + with pytest.raises(ValidationError): + EstimatePortfolioMaintenanceMarginPosition( + market_ticker="BTC-PERP", price=Decimal("1.00") + ) + + def test_rejects_zero_quantity_fp(self) -> None: + from kalshi.perps.klear.models.margin import ( + EstimatePortfolioMaintenanceMarginPosition, + ) + + with pytest.raises(ValidationError): + EstimatePortfolioMaintenanceMarginPosition( + market_ticker="BTC-PERP", quantity_fp="0", price=Decimal("1.00") + ) + def test_rejects_zero_quantity(self) -> None: from kalshi.perps.klear.models.margin import ( EstimatePortfolioMaintenanceMarginPosition, diff --git a/tests/test_concert_cancellation_markets.py b/tests/test_concert_cancellation_markets.py new file mode 100644 index 0000000..96a5670 --- /dev/null +++ b/tests/test_concert_cancellation_markets.py @@ -0,0 +1,646 @@ +"""Tests for concert cancellation market endpoints on MarketsResource (#582).""" + +from __future__ import annotations + +import json + +import httpx +import pytest +import respx +from pydantic import ValidationError + +from kalshi._base_client import AsyncTransport, SyncTransport +from kalshi.auth import KalshiAuth +from kalshi.config import KalshiConfig +from kalshi.errors import ( + AuthRequiredError, + KalshiConflictError, + KalshiRateLimitError, + KalshiServerError, + KalshiValidationError, +) +from kalshi.models.markets import CreateConcertCancellationMarketRequest +from kalshi.resources.markets import AsyncMarketsResource, MarketsResource + +BASE = "https://test.kalshi.com/trade-api/v2" + +_CREATE_KWARGS: dict[str, object] = { + "jambase_event_id": "jambase:16543035", + "scheduled_date": "2026-11-20", + "cover": "postponed", +} + +_CREATE_BODY = { + "jambase_event_id": "jambase:16543035", + "scheduled_date": "2026-11-20", + "cover": "postponed", +} + +_CREATE_RESPONSE = { + "cover": "postponed", + "event_ticker": "KXRFQCONCERTP-JB16543035-26NOV20", + "market_ticker": "KXRFQCONCERTP-JB16543035-26NOV20-PPD", + "created": True, +} + +_CONCERT = { + "jambase_event_id": "jambase:16543035", + "name": "Artist at Venue", + "lineup": ["Artist"], + "venue_name": "Madison Square Garden", + "timezone": "America/New_York", + "scheduled_date": "2026-11-20", + "markets": [ + { + "cover": "postponed", + "event_ticker": "KXRFQCONCERTP-JB16543035-26NOV20", + "market_ticker": "KXRFQCONCERTP-JB16543035-26NOV20-PPD", + } + ], +} + +_AVAIL_RESPONSE = { + "enabled": True, + "covers": ["postponed", "cancelled", "either"], + "max_days_ahead": 60, + "metros": [ + { + "id": "jambase:1", + "name": "New York", + "latitude": 40.7128, + "longitude": -74.006, + "upcoming_shows": 12, + } + ], +} + +_CONCERTS_RESPONSE = { + "concerts": [_CONCERT], + "page": 1, + "total_pages": 3, +} + +_SEARCH_RESPONSE = { + "concerts": [_CONCERT], +} + + +@pytest.fixture +def config() -> KalshiConfig: + return KalshiConfig( + base_url=BASE, + timeout=5.0, + max_retries=0, + ) + + +@pytest.fixture +def markets(test_auth: KalshiAuth, config: KalshiConfig) -> MarketsResource: + return MarketsResource(SyncTransport(test_auth, config)) + + +@pytest.fixture +def async_markets(test_auth: KalshiAuth, config: KalshiConfig) -> AsyncMarketsResource: + return AsyncMarketsResource(AsyncTransport(test_auth, config)) + + +@pytest.fixture +def unauth_markets(config: KalshiConfig) -> MarketsResource: + return MarketsResource(SyncTransport(None, config)) + + +@pytest.fixture +def retrying_markets(test_auth: KalshiAuth) -> MarketsResource: + return MarketsResource( + SyncTransport( + test_auth, + KalshiConfig( + base_url=BASE, + timeout=5.0, + max_retries=2, + retry_base_delay=0.01, + retry_max_delay=0.05, + ), + ) + ) + + +class TestCreateConcertCancellationMarket: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + resp = markets.create_concert_cancellation_market(**_CREATE_KWARGS) + assert route.calls[0].request.method == "POST" + assert str(route.calls[0].request.url) == f"{BASE}/concert_cancellation_markets" + body = json.loads(route.calls[0].request.content) + assert body == _CREATE_BODY + assert resp.cover == "postponed" + assert resp.event_ticker == _CREATE_RESPONSE["event_ticker"] + assert resp.market_ticker == _CREATE_RESPONSE["market_ticker"] + assert resp.created is True + + @respx.mock + def test_request_model_form(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + req = CreateConcertCancellationMarketRequest(**_CREATE_KWARGS) + resp = markets.create_concert_cancellation_market(request=req) + assert json.loads(route.calls[0].request.content) == _CREATE_BODY + assert resp.created is True + + def test_request_and_kwargs_exclusive(self, markets: MarketsResource) -> None: + req = CreateConcertCancellationMarketRequest(**_CREATE_KWARGS) + with pytest.raises(TypeError, match="not both"): + markets.create_concert_cancellation_market(request=req, cover="cancelled") + + def test_missing_required_kwargs(self, markets: MarketsResource) -> None: + with pytest.raises(TypeError, match="create_concert_cancellation_market"): + markets.create_concert_cancellation_market() # type: ignore[call-overload] + + def test_extra_field_rejected_by_forbid(self) -> None: + with pytest.raises(ValidationError): + CreateConcertCancellationMarketRequest( + **_CREATE_KWARGS, + extra_field="nope", # type: ignore[call-arg] + ) + + def test_requires_auth(self, unauth_markets: MarketsResource) -> None: + with pytest.raises(AuthRequiredError): + unauth_markets.create_concert_cancellation_market(**_CREATE_KWARGS) + + @respx.mock + def test_409_concert_cancellation_market_unavailable(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response( + 409, + json={"error": {"code": "concert_cancellation_market_unavailable"}}, + ) + ) + with pytest.raises(KalshiConflictError): + markets.create_concert_cancellation_market(**_CREATE_KWARGS) + + @respx.mock + def test_429_rate_limit(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response( + 429, + json={"error": {"code": "concert_cancellation_market_limit_exceeded"}}, + ) + ) + with pytest.raises(KalshiRateLimitError): + markets.create_concert_cancellation_market(**_CREATE_KWARGS) + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response( + 400, + json={"error": {"code": "invalid_parameters"}}, + ) + ) + with pytest.raises(KalshiValidationError): + markets.create_concert_cancellation_market(**_CREATE_KWARGS) + + @respx.mock + def test_not_retried_on_503(self, retrying_markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response(503, json={"error": {"code": "unavailable"}}) + ) + with pytest.raises(KalshiServerError): + retrying_markets.create_concert_cancellation_market(**_CREATE_KWARGS) + assert route.call_count == 1 + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> None: + route = respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + resp = await async_markets.create_concert_cancellation_market(**_CREATE_KWARGS) + assert route.calls[0].request.method == "POST" + body = json.loads(route.calls[0].request.content) + assert body == _CREATE_BODY + assert resp.created is True + + @respx.mock + @pytest.mark.asyncio + async def test_async_request_model_form(self, async_markets: AsyncMarketsResource) -> None: + route = respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + req = CreateConcertCancellationMarketRequest(**_CREATE_KWARGS) + await async_markets.create_concert_cancellation_market(request=req) + assert json.loads(route.calls[0].request.content) == _CREATE_BODY + + @pytest.mark.asyncio + async def test_async_request_and_kwargs_exclusive( + self, async_markets: AsyncMarketsResource + ) -> None: + req = CreateConcertCancellationMarketRequest(**_CREATE_KWARGS) + with pytest.raises(TypeError, match="not both"): + await async_markets.create_concert_cancellation_market(request=req, cover="cancelled") + + @respx.mock + @pytest.mark.asyncio + async def test_async_409(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response( + 409, + json={"error": {"code": "concert_cancellation_market_unavailable"}}, + ) + ) + with pytest.raises(KalshiConflictError): + await async_markets.create_concert_cancellation_market(**_CREATE_KWARGS) + + @respx.mock + @pytest.mark.asyncio + async def test_async_429(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response( + 429, + json={"error": {"code": "concert_cancellation_market_limit_exceeded"}}, + ) + ) + with pytest.raises(KalshiRateLimitError): + await async_markets.create_concert_cancellation_market(**_CREATE_KWARGS) + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response( + 400, + json={"error": {"code": "invalid_parameters"}}, + ) + ) + with pytest.raises(KalshiValidationError): + await async_markets.create_concert_cancellation_market(**_CREATE_KWARGS) + + @respx.mock + @pytest.mark.asyncio + async def test_async_not_retried_on_503(self, test_auth: KalshiAuth) -> None: + retrying = AsyncMarketsResource( + AsyncTransport( + test_auth, + KalshiConfig( + base_url=BASE, + timeout=5.0, + max_retries=2, + retry_base_delay=0.01, + retry_max_delay=0.05, + ), + ) + ) + route = respx.post(f"{BASE}/concert_cancellation_markets").mock( + return_value=httpx.Response(503, json={"error": {"code": "unavailable"}}) + ) + with pytest.raises(KalshiServerError): + await retrying.create_concert_cancellation_market(**_CREATE_KWARGS) + assert route.call_count == 1 + + +class TestConcertCancellationAvailability: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + resp = markets.concert_cancellation_availability() + assert route.calls[0].request.method == "GET" + assert ( + str(route.calls[0].request.url) == f"{BASE}/concert_cancellation_markets/availability" + ) + assert "date_from" not in route.calls[0].request.url.params + assert "date_to" not in route.calls[0].request.url.params + assert resp.enabled is True + assert resp.covers == ["postponed", "cancelled", "either"] + assert resp.max_days_ahead == 60 + assert len(resp.metros) == 1 + assert resp.metros[0].id == "jambase:1" + assert resp.metros[0].name == "New York" + assert resp.metros[0].latitude == 40.7128 + assert resp.metros[0].upcoming_shows == 12 + + @respx.mock + def test_optional_query_params_sent_when_set(self, markets: MarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + markets.concert_cancellation_availability(date_from="2026-11-20", date_to="2026-12-01") + params = dict(route.calls[0].request.url.params) + assert params == {"date_from": "2026-11-20", "date_to": "2026-12-01"} + + @respx.mock + def test_empty_lists(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response( + 200, + json={"enabled": False, "covers": [], "max_days_ahead": 0, "metros": []}, + ) + ) + resp = markets.concert_cancellation_availability() + assert resp.enabled is False + assert resp.covers == [] + assert resp.metros == [] + + @respx.mock + def test_null_lists_coerced_to_empty(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response( + 200, + json={ + "enabled": True, + "covers": None, + "max_days_ahead": 30, + "metros": None, + }, + ) + ) + resp = markets.concert_cancellation_availability() + assert resp.covers == [] + assert resp.metros == [] + + @respx.mock + def test_works_without_auth(self, unauth_markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + resp = unauth_markets.concert_cancellation_availability() + assert resp.enabled is True + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + markets.concert_cancellation_availability() + + @respx.mock + def test_429_rate_limit(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response(429, json={"error": {"code": "too_many_requests"}}) + ) + with pytest.raises(KalshiRateLimitError): + markets.concert_cancellation_availability() + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + resp = await async_markets.concert_cancellation_availability() + assert route.calls[0].request.method == "GET" + assert "date_from" not in route.calls[0].request.url.params + assert resp.enabled is True + assert resp.metros[0].id == "jambase:1" + + @respx.mock + @pytest.mark.asyncio + async def test_async_optional_query_params(self, async_markets: AsyncMarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + await async_markets.concert_cancellation_availability(date_from="2026-11-20") + params = dict(route.calls[0].request.url.params) + assert params == {"date_from": "2026-11-20"} + assert "date_to" not in params + + @respx.mock + @pytest.mark.asyncio + async def test_async_empty_lists(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response( + 200, + json={"enabled": False, "covers": [], "max_days_ahead": 0, "metros": []}, + ) + ) + resp = await async_markets.concert_cancellation_availability() + assert resp.enabled is False + assert resp.covers == [] + assert resp.metros == [] + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/availability").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + await async_markets.concert_cancellation_availability() + + +class TestListConcerts: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response(200, json=_CONCERTS_RESPONSE) + ) + resp = markets.list_concerts(metro_id="jambase:1") + assert route.calls[0].request.method == "GET" + params = dict(route.calls[0].request.url.params) + assert params == {"metro_id": "jambase:1"} + assert resp.page == 1 + assert resp.total_pages == 3 + assert len(resp.concerts) == 1 + concert = resp.concerts[0] + assert concert.jambase_event_id == "jambase:16543035" + assert concert.name == "Artist at Venue" + assert concert.lineup == ["Artist"] + assert concert.markets[0].cover == "postponed" + assert concert.start_time is None + + @respx.mock + def test_optional_query_params_sent_when_set(self, markets: MarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response(200, json=_CONCERTS_RESPONSE) + ) + markets.list_concerts( + metro_id="jambase:1", + date_from="2026-11-20", + date_to="2026-12-01", + page=2, + ) + params = dict(route.calls[0].request.url.params) + assert params == { + "metro_id": "jambase:1", + "date_from": "2026-11-20", + "date_to": "2026-12-01", + "page": "2", + } + + def test_missing_required_kwargs(self, markets: MarketsResource) -> None: + with pytest.raises(TypeError, match="metro_id"): + markets.list_concerts() # type: ignore[call-arg] + + def test_requires_auth(self, unauth_markets: MarketsResource) -> None: + with pytest.raises(AuthRequiredError): + unauth_markets.list_concerts(metro_id="jambase:1") + + @respx.mock + def test_null_lists_coerced_to_empty(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response( + 200, + json={ + "concerts": [ + { + "jambase_event_id": "jambase:1", + "name": "Show", + "lineup": None, + "venue_name": "Venue", + "timezone": "America/New_York", + "scheduled_date": "2026-11-20", + "markets": None, + } + ], + "page": 1, + "total_pages": 1, + }, + ) + ) + resp = markets.list_concerts(metro_id="jambase:1") + assert resp.concerts[0].lineup == [] + assert resp.concerts[0].markets == [] + + @respx.mock + def test_null_concerts_coerced_to_empty(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response( + 200, json={"concerts": None, "page": 1, "total_pages": 0} + ) + ) + resp = markets.list_concerts(metro_id="jambase:1") + assert resp.concerts == [] + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + markets.list_concerts(metro_id="jambase:1") + + @respx.mock + def test_429_rate_limit(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response(429, json={"error": {"code": "too_many_requests"}}) + ) + with pytest.raises(KalshiRateLimitError): + markets.list_concerts(metro_id="jambase:1") + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response(200, json=_CONCERTS_RESPONSE) + ) + resp = await async_markets.list_concerts(metro_id="jambase:1") + assert route.calls[0].request.method == "GET" + params = dict(route.calls[0].request.url.params) + assert params == {"metro_id": "jambase:1"} + assert resp.concerts[0].venue_name == "Madison Square Garden" + + @respx.mock + @pytest.mark.asyncio + async def test_async_optional_query_params(self, async_markets: AsyncMarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response(200, json=_CONCERTS_RESPONSE) + ) + await async_markets.list_concerts(metro_id="jambase:1", page=2) + params = dict(route.calls[0].request.url.params) + assert params == {"metro_id": "jambase:1", "page": "2"} + + @pytest.mark.asyncio + async def test_async_requires_auth(self, config: KalshiConfig) -> None: + unauth = AsyncMarketsResource(AsyncTransport(None, config)) + with pytest.raises(AuthRequiredError): + await unauth.list_concerts(metro_id="jambase:1") + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + await async_markets.list_concerts(metro_id="jambase:1") + + +class TestSearchConcerts: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/concerts/search").mock( + return_value=httpx.Response(200, json=_SEARCH_RESPONSE) + ) + resp = markets.search_concerts(q="Artist") + assert route.calls[0].request.method == "GET" + params = dict(route.calls[0].request.url.params) + assert params == {"q": "Artist"} + assert len(resp.concerts) == 1 + assert resp.concerts[0].name == "Artist at Venue" + + def test_missing_required_kwargs(self, markets: MarketsResource) -> None: + with pytest.raises(TypeError, match="search_concerts"): + markets.search_concerts() # type: ignore[call-arg] + + def test_requires_auth(self, unauth_markets: MarketsResource) -> None: + with pytest.raises(AuthRequiredError): + unauth_markets.search_concerts(q="Artist") + + @respx.mock + def test_null_lists_coerced_to_empty(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts/search").mock( + return_value=httpx.Response(200, json={"concerts": None}) + ) + resp = markets.search_concerts(q="Artist") + assert resp.concerts == [] + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts/search").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + markets.search_concerts(q="Artist") + + @respx.mock + def test_429_rate_limit(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts/search").mock( + return_value=httpx.Response( + 429, json={"error": {"code": "concert_search_limit_exceeded"}} + ) + ) + with pytest.raises(KalshiRateLimitError): + markets.search_concerts(q="Artist") + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> None: + route = respx.get(f"{BASE}/concert_cancellation_markets/concerts/search").mock( + return_value=httpx.Response(200, json=_SEARCH_RESPONSE) + ) + resp = await async_markets.search_concerts(q="Artist") + assert route.calls[0].request.method == "GET" + params = dict(route.calls[0].request.url.params) + assert params == {"q": "Artist"} + assert resp.concerts[0].jambase_event_id == "jambase:16543035" + + @pytest.mark.asyncio + async def test_async_requires_auth(self, config: KalshiConfig) -> None: + unauth = AsyncMarketsResource(AsyncTransport(None, config)) + with pytest.raises(AuthRequiredError): + await unauth.search_concerts(q="Artist") + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/concert_cancellation_markets/concerts/search").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + await async_markets.search_concerts(q="Artist") diff --git a/tests/test_contracts.py b/tests/test_contracts.py index f6ccb72..1488ed1 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -1460,6 +1460,9 @@ def _assert_params_match( "#/components/schemas/CreateWeatherPointMarketRequest": ( "kalshi.models.markets.CreateWeatherPointMarketRequest" ), + "#/components/schemas/CreateConcertCancellationMarketRequest": ( + "kalshi.models.markets.CreateConcertCancellationMarketRequest" + ), "#/components/schemas/CreateOrderGroupRequest": ( "kalshi.models.order_groups.CreateOrderGroupRequest" ),