From eadb7cc6db315f24598ab5bd1157d513282941d7 Mon Sep 17 00:00:00 2001 From: Jeff West Date: Thu, 19 Nov 2026 09:23:16 -0600 Subject: [PATCH 1/2] chore(spec): sync core, asyncapi, perps + perps_scm specs (#586) --- specs/asyncapi.yaml | 19 +- specs/openapi.yaml | 575 +++++++++++++++++++++++++++++++++-- specs/perps_asyncapi.yaml | 14 + specs/perps_openapi.yaml | 61 +++- specs/perps_scm_openapi.yaml | 11 +- 5 files changed, 644 insertions(+), 36 deletions(-) diff --git a/specs/asyncapi.yaml b/specs/asyncapi.yaml index d6f7dfc..2642046 100644 --- a/specs/asyncapi.yaml +++ b/specs/asyncapi.yaml @@ -645,6 +645,7 @@ channels: | 3292 | `Equity.Index.US30/USD` | US30 (Dow Jones Industrial Average) Index in USD (24/5) | | 1530 | `InterestRate.US2Y` | US 2-year Treasury yield in percent | | 1534 | `InterestRate.US5Y` | US 5-year Treasury yield in percent | + | 1536 | `InterestRate.US7Y` | US 7-year Treasury yield in percent | | 1527 | `InterestRate.US10Y` | US 10-year Treasury yield in percent | | 1531 | `InterestRate.US30Y` | US 30-year Treasury yield in percent | | 327 | `FX.EUR/USD` | Euro / US Dollar | @@ -664,7 +665,7 @@ channels: Use `underlying_list` to discover recently streamed tickers on your connection. Availability can change, including as futures contracts expire; the table does not guarantee that every feed is streaming in every environment. - Treasury yields use the exact symbols above, without a `/USD` suffix. They are included in `["all"]` subscriptions and can also be requested individually, for example with `underlying_tickers: ["InterestRate.US2Y"]`. These are the yield feeds behind the `KX{2,5,10,30}YRRATE15M` and `KX{2,5,10,30}YRRATEH` markets; `/USD` symbols identify separate bond-price feeds. + Treasury yields use the exact symbols above, without a `/USD` suffix. They are included in `["all"]` subscriptions and can also be requested individually, for example with `underlying_tickers: ["InterestRate.US2Y"]`. These are the yield feeds behind the `KX{2,5,10,30}YRRATE15M` and `KX{2,5,7,10,30}YRRATEH` markets; `/USD` symbols identify separate bond-price feeds. ## Requirements @@ -1927,6 +1928,16 @@ components: clock: 4182057 yes_dollars_fp: [["0.0800", "300.00"], ["0.2200", "333.00"]] no_dollars_fp: [["0.5400", "20.00"], ["0.5600", "146.00"]] + - name: marketWithNoRecordedChange + summary: Orderbook snapshot for a market with no recorded change + payload: + type: orderbook_snapshot + sid: 2 + seq: 3 + msg: + market_ticker: "FED-23DEC-T3.25" + market_id: "" + clock: 0 orderbookDelta: name: orderbook_delta @@ -3639,7 +3650,7 @@ components: description: Qualified Pyth underlying ticker value_usd: type: string - description: 'Value formatted to 8 decimal places in the underlying''s quoted units. For Treasury yields (InterestRate.US2Y, InterestRate.US5Y, InterestRate.US10Y, InterestRate.US30Y), this is percent: "4.25000000" means 4.25%. The field name is retained for compatibility.' + description: 'Value formatted to 8 decimal places in the underlying''s quoted units. For Treasury yields (InterestRate.US2Y, InterestRate.US5Y, InterestRate.US7Y, InterestRate.US10Y, InterestRate.US30Y), this is percent: "4.25000000" means 4.25%. The field name is retained for compatibility.' source_ts_ms: type: integer description: Pyth source timestamp (unix ms) @@ -3695,7 +3706,9 @@ components: market_ticker: $ref: '#/components/schemas/marketTicker' market_id: - $ref: '#/components/schemas/marketId' + type: string + description: Unique market UUID. Can be an empty string for a market with no recorded change. + pattern: '^$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$' clock: type: integer format: int64 diff --git a/specs/openapi.yaml b/specs/openapi.yaml index e332b3d..f96b14d 100644 --- a/specs/openapi.yaml +++ b/specs/openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.0.0 info: title: Kalshi Trade API Manual Endpoints - version: 3.36.0 + version: 3.37.0 description: Manually defined OpenAPI spec for endpoints being migrated to spec-first approach servers: @@ -4223,13 +4223,28 @@ paths: are switched off entirely, the request can be refused whether or not the market exists. - The location snaps to the center of the NOAA MRMS grid cell containing - it; the response carries the snapped coordinates. Markets are only - offered where `GET /weather_point_markets/availability` says so, and - not over open water. - - The window is whole local hours on one calendar day. A new market's - window must start at least 15 minutes from now and within 365 days. + The market's location is the requested coordinates rounded to three + decimal places; requests that agree to three decimal places share a + market. A rounded location exactly on the boundary between two NOAA + MRMS grid cells is moved 0.001° north or east, into one of them. The + response carries the market's coordinates. Markets are only offered + where `GET /weather_point_markets/availability` says so, and only + where the market's grid cell touches land in a US state or territory: + a cell entirely over open water or outside the US is refused, while + any point in a coastal cell that touches land is accepted. + + The window is whole local hours, on one calendar day or, with + `end_date` set to the day after `date`, from one day into the next. + A window that crosses midnight is at most 24 hours long, and only + offered where `GET /weather_point_markets/availability` returns + `max_window_days: 2`. Where it returns 1, the limit applies to the + local dates the market stores, which are those of the first request + for its variable, location and window: a new threshold on an event + first requested across midnight is refused even when your request + names one date in another time zone, and one on an event first + requested within one date is accepted even with `end_date`. A market + that already exists is returned either way. A new market's window must start at least 15 + minutes from now and within 365 days. A market is traded through RFQs: pass the returned `market_ticker` to `POST /communications/rfqs`. These markets are in series starting with @@ -4244,8 +4259,8 @@ paths: | --- | --- | --- | | 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, or the request can't define a market: a latitude or hour out of range, an `end_hour` not after `start_hour`, an unknown variable or strike type, thresholds that don't fit the strike type or the variable's range, a location outside NOAA MRMS coverage, an unknown time zone, a window that doesn't start and end on whole UTC hours, has already ended or starts more than 365 days out, or an hour that a clock change skips or repeats. | - | 409 | `weather_point_market_unavailable` | The request is valid but the market isn't offered: the variable isn't offered at that location, the location is over open water, or the window starts in less than 15 minutes. | + | 400 | `invalid_parameters` | A field is present but unusable, or the request can't define a market: a latitude or hour out of range, an `end_hour` not after `start_hour` on one day, an `end_date` other than `date` or the day after it, a window across midnight longer than 24 hours, an unknown variable or strike type, thresholds that don't fit the strike type or the variable's range, a location outside NOAA MRMS coverage, an unknown time zone, a window that doesn't start and end on whole UTC hours, has already ended or starts more than 365 days out, or an hour that a clock change skips or repeats. | + | 409 | `weather_point_market_unavailable` | The request is valid but the market isn't offered: the variable isn't offered at that location, the market's grid cell is entirely over open water or outside US land, the window starts in less than 15 minutes, or the market's window is stored across two local dates where `max_window_days` is 1. | | 429 | `weather_point_market_limit_exceeded` | A creation limit was reached: the daily limit on new weather markets across all users, or 40 markets for one variable, location and window. Retrying at once doesn't help. | | 429 | `too_many_requests` | Your API rate limit. This endpoint is charged against your write budget. | tags: @@ -4288,10 +4303,12 @@ paths: Returns which on-request weather markets can be created: whether creation is on, the NOAA MRMS domains a location may lie in, and the domains each offered variable may use. A variable missing from - `variables` can't be created. Existing markets are unaffected. + `variables` can't be created. `max_window_days` and + `max_window_hours` say whether a window may cross midnight and how + long it may then be. Existing markets are unaffected. A location inside an offered domain can still be refused at creation - when it is over open water. + when its grid cell is entirely over open water or outside US land. tags: - markets responses: @@ -4325,8 +4342,9 @@ paths: 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 + An existing market is usually returned until it closes, even when new + markets are no longer offered; where creation or its cover is switched + off, the request returns 409. 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. @@ -4381,17 +4399,21 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' /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 + Returns which on-request concert markets are offered: whether they + are listed, the covers offered, how far ahead a show may be scheduled, and the metros whose concerts `GET /concert_cancellation_markets/concerts` lists. A cover missing - from `covers` can't be created. Existing markets are unaffected. + from `covers` can't be created. Where concerts are listed before + markets are offered, `enabled` is true and every create request + returns 409. 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 @@ -4504,13 +4526,16 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' /concert_cancellation_markets/concerts/search: get: operationId: SearchConcerts summary: Search Concerts description: | - Lists upcoming concerts matching a name, across metros, that a + Lists upcoming concerts matching a name, across the metros that + availability lists, 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 @@ -4553,6 +4578,204 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + + /flight_disruption_markets: + post: + operationId: CreateFlightDisruptionMarket + # Hidden from the published docs until flight disruption markets launch. + x-excluded: true + summary: Create Flight Disruption Market + description: | + Returns the on-request market on whether a flight is canceled or + delayed, creating it if it doesn't exist yet. A market is defined by + the flight (`carrier`, `flight_number`, `departure_airport`, + `arrival_airport` and `scheduled_date`), the `cover` (`cancelled`, + `delayed` or `either`) and, for `delayed` and `either`, the + `delay_basis` and `delay_minutes`. 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 the flight's five fields from + `GET /flight_disruption_markets/flights`. A flight is one nonstop leg: + a flight number that flies several legs in a day is several flights. + `carrier` and `flight_number` are the operating carrier's, which the + lookup returns even when you searched by a codeshare number. + + `delay_minutes` is a multiple of `delay_step_minutes`, up to + `max_delay_minutes`, both from + `GET /flight_disruption_markets/availability`. A `cancelled` market + takes neither `delay_basis` nor `delay_minutes`. + + An existing market is returned until it closes, even when new markets + are no longer offered. A new market's flight must be scheduled to + leave more than `min_lead_minutes` from now and within + `max_days_ahead` days, from an airport in one of + `departure_countries`. + + 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 or delay basis, a carrier, flight number or airport code of the wrong form, a `scheduled_date` that isn't YYYY-MM-DD, a `delayed` or `either` request without `delay_basis` and `delay_minutes`, a `cancelled` request with either of them, a `delay_minutes` that isn't a multiple of `delay_step_minutes` or is above `max_delay_minutes`, or a flight scheduled further ahead than `max_days_ahead`. | + | 404 | `not_found` | No such flight is scheduled on that date. | + | 409 | `flight_disruption_market_unavailable` | The request is valid but the market isn't offered: flight markets or the cover are switched off, the flight leaves too soon, departs from a country that isn't offered, or its market has closed. | + | 429 | `flight_disruption_market_limit_exceeded` | A limit on new flight markets 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/CreateFlightDisruptionMarketRequest' + responses: + '200': + description: Market returned or created successfully + content: + application/json: + schema: + $ref: '#/components/schemas/CreateFlightDisruptionMarketResponse' + '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' + '503': + $ref: '#/components/responses/ServiceUnavailableError' + + /flight_disruption_markets/availability: + get: + operationId: GetFlightDisruptionAvailability + # Hidden from the published docs until flight disruption markets launch. + x-excluded: true + summary: Get Flight Disruption Market Availability + description: | + Returns which on-request flight markets can be created: whether + creation is on, the covers and delay bases offered, the delay + thresholds a market may use, how soon and how far ahead a flight may + be scheduled, and the countries it may depart from. A cover missing + from `covers` can't be created. Existing markets are unaffected. + tags: + - markets + responses: + '200': + description: Availability retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetFlightDisruptionAvailabilityResponse' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + + /flight_disruption_markets/flights: + get: + operationId: GetFlights + # Hidden from the published docs until flight disruption markets launch. + x-excluded: true + summary: Get Flights + description: | + Looks up a flight number on a departure date and returns the flights + a disruption market can still be created for, in departure order. A + flight is one nonstop leg, so a number that flies several legs that + day returns several flights, and one that flies none returns an empty + list. + + `carrier` and `flight_number` may be the operating carrier's or a + codeshare number. Each flight returned is the operating flight, with + the number you asked for in `requested_carrier` and + `requested_flight_number` when it differs. + + Each flight carries the five fields + `POST /flight_disruption_markets` takes, and the series and event + tickers it has or would get for each offered cover. A ticker listed + here names an event or market that may not exist yet: create the + market before sending an RFQ. + + Lookups can be limited across all users. When the limit is reached + the request returns 429 `flight_lookup_limit_exceeded`; retry later. + tags: + - markets + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + parameters: + - name: carrier + in: query + required: true + description: The airline's 2-character code, such as `AA`. The operating carrier's or a codeshare partner's. + schema: + type: string + minLength: 2 + maxLength: 2 + x-oapi-codegen-extra-tags: + validate: required,alphanum,len=2 + - name: flight_number + in: query + required: true + description: The flight number without the airline code, 1 to 4 digits, such as `100`. + schema: + type: string + minLength: 1 + maxLength: 4 + x-oapi-codegen-extra-tags: + validate: required,number,max=4 + - name: date + in: query + required: true + description: The scheduled departure date at the departure airport, as YYYY-MM-DD. + schema: + type: string + x-oapi-codegen-extra-tags: + validate: required,datetime=2006-01-02 + responses: + '200': + description: Flights retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetFlightsResponse' + '400': + $ref: '#/components/responses/BadRequestError' + '401': + $ref: '#/components/responses/UnauthorizedError' + '404': + $ref: '#/components/responses/NotFoundError' + '409': + $ref: '#/components/responses/ConflictError' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + '503': + $ref: '#/components/responses/ServiceUnavailableError' /multivariate_event_collections/{collection_ticker}: get: @@ -4942,7 +5165,7 @@ paths: Returns the event-contract daily premium cap configured for an FCM member's subtrader, together with its live utilization. Executed utilization is the net premium deployed by fills today (sells and settlements credit back); resting and pending utilization reserve - open and in-flight orders at their full worst-case cost plus fees. Executed utilization + open orders and orders still being placed at their full worst-case cost plus fees. Executed utilization resets at midnight New York time on the returned cap date; resting and pending reservations persist for as long as their orders remain open, including across the reset. Returns 404 when the subtrader has no cap configured — in that state every order placed @@ -11434,6 +11657,12 @@ components: example: '2026-11-11' x-oapi-codegen-extra-tags: validate: required,datetime=2006-01-02 + end_date: + type: string + description: Local calendar date the window ends on, as YYYY-MM-DD in `timezone`. Leave it out, or repeat `date`, for a window within one day. Set it to the day after `date` for a window that crosses midnight, where availability returns `max_window_days` 2; `end_hour` is then read on this date, and the window is at most 24 hours long. Any other date is refused. + example: '2026-11-12' + x-oapi-codegen-extra-tags: + validate: omitempty,datetime=2006-01-02 start_hour: type: integer format: int32 @@ -11448,10 +11677,10 @@ components: format: int32 minimum: 1 maximum: 24 - description: Local hour the window ends at, exclusive (1-24, after `start_hour`). 24 is the following midnight, so 0 to 24 is the whole day. + description: Local hour the window ends at, exclusive (1-24). Within one day it must be after `start_hour`; 24 is the following midnight, so 0 to 24 is the whole day. With `end_date` the day after `date` it is an hour of that day and must not be after `start_hour`, so 23 to 3 is 11pm to 3am and 8 to 8 is 24 hours. x-go-type: '*int32' x-oapi-codegen-extra-tags: - validate: required,gte=1,lte=24,gtfield=StartHour + validate: required,gte=1,lte=24 timezone: type: string description: IANA time zone of the location, which the date and hours are read in. The window must start and end on whole UTC hours, so zones offset by a fraction of an hour are refused. @@ -11481,11 +11710,11 @@ components: latitude: type: number format: double - description: Latitude of the market's location, the center of the grid cell containing the request, to three decimal places. + description: Latitude of the market's location, the requested latitude to three decimal places. longitude: type: number format: double - description: Longitude of the market's location, the center of the grid cell containing the request, to three decimal places. + description: Longitude of the market's location, the requested longitude to three decimal places. WeatherPointDomain: type: object @@ -11536,6 +11765,8 @@ components: - enabled - domains - variables + - max_window_days + - max_window_hours properties: enabled: type: boolean @@ -11550,6 +11781,16 @@ components: items: $ref: '#/components/schemas/WeatherPointVariableAvailability' description: The variables on offer and where. A variable left out can't be created. + max_window_days: + type: integer + format: int32 + description: How many local calendar days a new market's window may touch. 2 means a window may cross midnight into the next day (`end_date` on the create request); anything less means it must start and end on one day. Every offered variable follows it. + example: 2 + max_window_hours: + type: integer + format: int32 + description: The longest window that crosses midnight, in hours. A window within one day can be the whole day, which lasts 25 hours when clocks go back. + example: 24 ConcertCover: type: string @@ -11653,7 +11894,10 @@ components: properties: enabled: type: boolean - description: Whether concert cancellation markets can be created at all. + description: >- + Whether concert cancellation markets are listed. It doesn't promise that they can be created: + where concerts are listed before markets are offered, it is true and every create request + returns 409. covers: type: array items: @@ -11783,6 +12027,289 @@ components: items: $ref: '#/components/schemas/Concert' + FlightCover: + type: string + enum: + - cancelled + - delayed + - either + # Named so the generated constants don't collide with status values. + x-enum-varnames: + - FlightCoverCancelled + - FlightCoverDelayed + - FlightCoverEither + description: | + What a flight disruption market pays on, read from the flight's + status after it was scheduled to arrive: + - `cancelled`: Yes when the flight is canceled. + - `delayed`: Yes when the flight operates and is at least + `delay_minutes` late on its `delay_basis`. A canceled flight + resolves to No. + - `either`: Yes in both of those cases. + + FlightDelayBasis: + type: string + enum: + - departure + - arrival + x-enum-varnames: + - FlightDelayBasisDeparture + - FlightDelayBasisArrival + description: | + Which gate time a delay is measured at: + - `departure`: the actual gate departure against the published + departure. + - `arrival`: the actual gate arrival against the published arrival. + + CreateFlightDisruptionMarketRequest: + type: object + required: + - carrier + - flight_number + - departure_airport + - arrival_airport + - scheduled_date + - cover + properties: + carrier: + type: string + description: The operating carrier's 2-character code, from the flight lookup. + example: AA + x-oapi-codegen-extra-tags: + validate: required,alphanum,len=2 + flight_number: + type: string + description: The operating carrier's flight number, 1 to 4 digits, from the flight lookup. + example: '100' + x-oapi-codegen-extra-tags: + validate: required,number,max=4 + departure_airport: + type: string + description: The departure airport's 3-letter code. + example: JFK + x-oapi-codegen-extra-tags: + validate: required,alpha,len=3 + arrival_airport: + type: string + description: The arrival airport's 3-letter code. + example: LHR + x-oapi-codegen-extra-tags: + validate: required,alpha,len=3 + scheduled_date: + type: string + description: The scheduled departure date at the departure airport, as YYYY-MM-DD. + example: '2026-11-25' + x-oapi-codegen-extra-tags: + validate: required,datetime=2006-01-02 + cover: + $ref: '#/components/schemas/FlightCover' + delay_basis: + $ref: '#/components/schemas/FlightDelayBasis' + delay_minutes: + type: integer + format: int32 + description: The delay, in minutes, at which the market pays. Required for the `delayed` and `either` covers and left out for `cancelled`. A multiple of the availability's `delay_step_minutes`, up to its `max_delay_minutes`. + example: 120 + x-oapi-codegen-extra-tags: + validate: omitempty,min=1 + + CreateFlightDisruptionMarketResponse: + type: object + required: + - cover + - event_ticker + - market_ticker + - created + properties: + cover: + $ref: '#/components/schemas/FlightCover' + delay_basis: + $ref: '#/components/schemas/FlightDelayBasis' + delay_minutes: + type: integer + format: int32 + description: The market's delay threshold in minutes. Left out for the `cancelled` cover. + example: 120 + event_ticker: + type: string + description: Event ticker of the market. + example: KXRFQFLIGHTD-AA100-JFKLHR-26NOV25 + market_ticker: + type: string + description: Market ticker of the market. + example: KXRFQFLIGHTD-AA100-JFKLHR-26NOV25-DEP120 + created: + type: boolean + description: False when a market for the same request already existed. + + GetFlightDisruptionAvailabilityResponse: + type: object + required: + - enabled + - covers + - delay_bases + - delay_step_minutes + - max_delay_minutes + - max_days_ahead + - min_lead_minutes + - departure_countries + properties: + enabled: + type: boolean + description: Whether flight disruption markets can be created at all. + covers: + type: array + items: + $ref: '#/components/schemas/FlightCover' + description: The covers on offer. A cover left out can't be created. + delay_bases: + type: array + items: + $ref: '#/components/schemas/FlightDelayBasis' + description: The delay bases on offer for the `delayed` and `either` covers. + delay_step_minutes: + type: integer + format: int32 + description: A market's `delay_minutes` is a multiple of this, from one step up to `max_delay_minutes`. + example: 30 + max_delay_minutes: + type: integer + format: int32 + description: The largest `delay_minutes` a market may use. + example: 360 + max_days_ahead: + type: integer + format: int32 + description: How many days ahead a flight may be scheduled for a new market. + min_lead_minutes: + type: integer + format: int32 + description: A new market's flight must be scheduled to leave more than this many minutes from now. + departure_countries: + type: array + items: + type: string + description: ISO country codes a flight must depart from, such as `US`. An empty list means every country is offered. + + FlightCoverEvent: + type: object + required: + - cover + - series_ticker + - event_ticker + properties: + cover: + $ref: '#/components/schemas/FlightCover' + series_ticker: + type: string + description: Series ticker of the cover. + example: KXRFQFLIGHTD + event_ticker: + type: string + description: Event ticker the flight has or would get for this cover. It holds every market of the cover for the flight. + example: KXRFQFLIGHTD-AA100-JFKLHR-26NOV25 + market_ticker: + type: string + description: Market ticker of the `cancelled` cover's one market. Left out for `delayed` and `either`, whose market tickers depend on the delay requested. The market may not exist yet. + example: KXRFQFLIGHTC-AA100-JFKLHR-26NOV25-CXL + + Flight: + type: object + required: + - carrier + - flight_number + - departure_airport + - arrival_airport + - scheduled_date + - events + properties: + carrier: + type: string + description: The operating carrier's 2-character code. + example: AA + flight_number: + type: string + description: The operating carrier's flight number. + example: '100' + airline_name: + type: string + description: The operating carrier's name. + departure_airport: + type: string + description: The departure airport's 3-letter code. + example: JFK + departure_airport_name: + type: string + description: The departure airport's name. + departure_city: + type: string + description: The departure airport's city. + departure_country: + type: string + description: The departure airport's ISO country code. + departure_timezone: + type: string + description: IANA time zone of the departure airport, which `scheduled_date` is local to. + example: America/New_York + arrival_airport: + type: string + description: The arrival airport's 3-letter code. + example: LHR + arrival_airport_name: + type: string + description: The arrival airport's name. + arrival_city: + type: string + description: The arrival airport's city. + arrival_country: + type: string + description: The arrival airport's ISO country code. + arrival_timezone: + type: string + description: IANA time zone of the arrival airport. + example: Europe/London + scheduled_date: + type: string + description: The scheduled departure date at the departure airport, as YYYY-MM-DD. + example: '2026-11-25' + scheduled_departure: + type: string + format: date-time + description: The published departure time, in UTC. + scheduled_arrival: + type: string + format: date-time + description: The published arrival time, in UTC. + close_time: + type: string + format: date-time + description: When the flight's markets close, which is its scheduled departure. + settle_after: + type: string + format: date-time + description: The earliest the flight's status is read to determine its markets. + events: + type: array + items: + $ref: '#/components/schemas/FlightCoverEvent' + description: One entry per offered cover. + requested_carrier: + type: string + description: The carrier code the lookup asked for, when it is a codeshare number and not the operating flight's. Left out otherwise. + requested_flight_number: + type: string + description: The flight number the lookup asked for, when it is a codeshare number and not the operating flight's. Left out otherwise. + + GetFlightsResponse: + type: object + required: + - flights + properties: + flights: + type: array + items: + $ref: '#/components/schemas/Flight' + # Market Orderbook schemas PriceLevelDollarsCountFp: type: array diff --git a/specs/perps_asyncapi.yaml b/specs/perps_asyncapi.yaml index d26d99a..ec5d7d1 100644 --- a/specs/perps_asyncapi.yaml +++ b/specs/perps_asyncapi.yaml @@ -760,6 +760,11 @@ components: enum: ["Decrease", "Amend", "MarginCancel", "SelfTradeCancel", "ExpiryCancel", "CloseCancel", "HaltCancel", "Trade", "PostOnlyCrossCancel", "ReduceOnlyCancel", "SettlementBoundsCancel"] description: Margin order update reason. The value ReduceOnlyCancel means reduce_only capped the order at placement, and SettlementBoundsCancel means the overnight settlement band canceled a resting order priced outside it. The field is omitted when no reason applies. + subaccountType: + type: string + enum: ["cross", "isolated", "managed_isolated"] + description: How the subaccount is margined. `cross` for the primary account and numbered subaccounts, `isolated` for a market's isolated subaccount, and `managed_isolated` for a managed isolated subaccount, whose number is the same as the market's isolated subaccount number. + tickerPrice: type: object required: ["price", "ts_ms"] @@ -1120,6 +1125,9 @@ components: It can decrease between deltas; follow the subscription's seq for delivery order. subaccount: type: integer + subaccount_type: + $ref: '#/components/schemas/subaccountType' + description: Present only when subaccount is. sending_ts_ms: $ref: '#/components/schemas/sendingTimestampMs' @@ -1422,6 +1430,9 @@ components: x-rust-serialize-with: ws::dto::serde_money::serialize_position_fixed_point_count subaccount: type: integer + subaccount_type: + $ref: '#/components/schemas/subaccountType' + description: Present only when subaccount is. order_source: type: string enum: ["user", "system"] @@ -1491,6 +1502,9 @@ components: description: Margin order update reason. The value ReduceOnlyCancel means reduce_only capped the order at placement. The field is omitted when no reason applies. subaccount_number: type: integer + subaccount_type: + $ref: '#/components/schemas/subaccountType' + description: Present only when subaccount_number is. order_source: type: string enum: ["user", "system"] diff --git a/specs/perps_openapi.yaml b/specs/perps_openapi.yaml index cc24194..94716cc 100644 --- a/specs/perps_openapi.yaml +++ b/specs/perps_openapi.yaml @@ -742,7 +742,7 @@ paths: get: operationId: GetMarginMarketSchedules summary: Get Market Schedules - description: Endpoint for retrieving Kalshi trading holiday closures for multiple margin markets. Returns a map keyed by market ticker. Regular daily and weekend closures are not included. + description: Endpoint for retrieving recurring Kalshi trading hours and holiday closures for multiple margin markets. Returns a map keyed by market ticker. tags: - market parameters: @@ -3520,6 +3520,31 @@ components: description: Kalshi trading holiday closures for the market. items: $ref: '#/components/schemas/MarginHolidayWindow' + kalshi_trading_schedule: + $ref: '#/components/schemas/MarginTradingCronSchedule' + + MarginTradingCronSchedule: + type: object + description: Recurring Kalshi trading hours, including market-specific overrides. Available after schedule synchronization. Empty cron arrays mean continuous trading except for closures in kalshi_trading_holidays. + required: + - timezone + - open_crons + - close_crons + properties: + timezone: + type: string + description: IANA timezone used to evaluate the cron expressions. + enum: [America/New_York] + open_crons: + type: array + description: Five-field cron expressions (minute, hour, day of month, month, day of week) for recurring trading session opens. Day of week 0 is Sunday. + items: + type: string + close_crons: + type: array + description: Five-field cron expressions (minute, hour, day of month, month, day of week) for recurring trading session closes. Day of week 0 is Sunday. + items: + type: string MarginHolidayWindow: type: object @@ -3595,7 +3620,7 @@ components: type: string enum: ['cross', 'isolated', 'auto_rebalance', 'managed_isolated'] x-enum-varnames: [SubaccountTypeCross, SubaccountTypeIsolated, SubaccountTypeAutoRebalance, SubaccountTypeManagedIsolated] - description: How the subaccount is margined. `cross` for the primary account and numbered subaccounts, `isolated` for a market's isolated subaccount, `auto_rebalance` for an auto-rebalanced isolated position, which shares its market's isolated subaccount number, and `managed_isolated` for a managed isolated position, whose subaccount number is its slot number rather than the market's isolated subaccount number. + description: How the subaccount is margined. `cross` for the primary account and numbered subaccounts, `isolated` for a market's isolated subaccount, `auto_rebalance` for an auto-rebalanced isolated position, which shares its market's isolated subaccount number, and `managed_isolated` for a managed isolated position, whose subaccount number is the same as the market's isolated subaccount number. LastUpdateReason: type: string @@ -4324,7 +4349,7 @@ components: $ref: '#/components/schemas/BidAskDistributionHistorical' description: Open, high, low, close (OHLC) data for buy offers on the market during the candlestick period. ask: - $ref: '#/components/schemas/BidAskDistributionHistorical' + $ref: '#/components/schemas/MarginAskDistributionHistorical' description: Open, high, low, close (OHLC) data for sell offers on the market during the candlestick period. price: $ref: '#/components/schemas/PriceDistributionHistorical' @@ -4364,6 +4389,36 @@ components: $ref: '#/components/schemas/FixedPointDollars' description: Quoted price at the end of the candlestick period (in dollars). + MarginAskDistributionHistorical: + type: object + required: + - open + - low + - high + - close + description: OHLC data for ask quotes during the candlestick period. These values reflect ask quotes, not executed trade prices. A value is null when the orderbook had no asks. + properties: + open: + allOf: + - $ref: '#/components/schemas/FixedPointDollars' + nullable: true + description: Ask at the start of the candlestick period (in dollars). Null if the orderbook had no asks at that time. + low: + allOf: + - $ref: '#/components/schemas/FixedPointDollars' + nullable: true + description: Lowest ask during the candlestick period (in dollars). Null if the orderbook had no asks during the period. + high: + allOf: + - $ref: '#/components/schemas/FixedPointDollars' + nullable: true + description: Highest ask during the candlestick period (in dollars). Null if the orderbook had no asks during the period. + close: + allOf: + - $ref: '#/components/schemas/FixedPointDollars' + nullable: true + description: Ask at the end of the candlestick period (in dollars). Null if the orderbook had no asks at that time. + PriceDistributionHistorical: type: object required: diff --git a/specs/perps_scm_openapi.yaml b/specs/perps_scm_openapi.yaml index 56d0823..9428ef7 100644 --- a/specs/perps_scm_openapi.yaml +++ b/specs/perps_scm_openapi.yaml @@ -225,16 +225,15 @@ paths: summary: Get Large Trader Positions description: >- Positions of the authenticated clearing member that meet the CFTC - large-trader reporting levels for a settlement day (17 CFR 15.03(b); - each row's reportable_threshold is its market's level), plus exit-day + large-trader reporting level for a settlement day (25 contracts in + every market; each row's reportable_threshold carries it), plus exit-day positions that were reportable on the prior settlement day and are now below the threshold. Members with reportable positions are subject to their own CFTC Part 17 large-trader reporting obligations; this endpoint provides the position data needed to meet them. Empty when no positions meet the reporting - levels and no prior-day reportable positions need exit reporting. See the - [CFTC's Large Trader Reporting Program](https://www.cftc.gov/IndustryOversight/MarketSurveillance/LargeTraderReportingProgram/index.htm) - and reporting levels at [17 CFR 15.03](https://www.ecfr.gov/current/title-17/chapter-I/part-15). + level and no prior-day reportable positions need exit reporting. See the + [CFTC's Large Trader Reporting Program](https://www.cftc.gov/IndustryOversight/MarketSurveillance/LargeTraderReportingProgram/index.htm). parameters: - { name: report_date, in: query, required: false, schema: { type: string, format: date }, description: "ET settlement day to report, YYYY-MM-DD. Defaults to the most recent ET settlement day whose settlement window has closed." } @@ -1007,7 +1006,7 @@ components: market_ticker: { type: string } position: { type: integer, description: "Signed contract count; positive long, negative short. Can be below the reportable threshold when exit_day is true." } exit_day: { type: boolean, description: True when this row is included because the same market was reportable on the prior settlement day but is now below the reportable threshold. } - 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.' } + reportable_threshold: { type: integer, format: int64, description: 'CFTC reporting level for this market, in contracts; 25 in every market. A position of at least this size in either direction is reportable.' } EstimatePortfolioMaintenanceMarginPosition: type: object required: [market_ticker] From 369a2e7e7d1fb6a1de5d0f4d10e086d60733a1fc Mon Sep 17 00:00:00 2001 From: Jeff West Date: Thu, 19 Nov 2026 09:42:49 -0600 Subject: [PATCH 2/2] =?UTF-8?q?feat(markets):=20flight=20disruption=20mark?= =?UTF-8?q?ets=20+=20weather/perps=20drift=20(#586)=20=E2=80=94=2022.15.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 64 +++ CLAUDE.md | 2 +- README.md | 2 +- docs/index.md | 4 +- docs/perps.md | 20 +- docs/resources/markets.md | 56 +- kalshi/__init__.py | 18 +- kalshi/_contract_map.py | 32 ++ kalshi/models/__init__.py | 16 + kalshi/models/markets.py | 121 ++++- kalshi/perps/__init__.py | 4 + kalshi/perps/models/__init__.py | 4 + kalshi/perps/models/common.py | 2 +- kalshi/perps/models/markets.py | 47 +- kalshi/perps/resources/markets.py | 5 +- kalshi/perps/ws/models/fill.py | 5 +- kalshi/perps/ws/models/orderbook.py | 3 + kalshi/perps/ws/models/user_orders.py | 8 +- kalshi/resources/markets.py | 236 ++++++++- pyproject.toml | 2 +- tests/_contract_support.py | 38 ++ tests/perps/test_markets.py | 89 +++- tests/perps/ws/test_perps_ws_models.py | 70 +++ tests/test_contracts.py | 3 + tests/test_flight_disruption_markets.py | 646 ++++++++++++++++++++++++ tests/test_weather_point_markets.py | 66 ++- 26 files changed, 1526 insertions(+), 37 deletions(-) create mode 100644 tests/test_flight_disruption_markets.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 84cb098..49343e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,70 @@ All notable changes to kalshi-sdk will be documented in this file. +## 22.15.0 — 2026-11-19 + +Adds on-request flight disruption markets (#586) against OpenAPI v3.37.0 +and reconciles weather-window, perps schedule, and perps candlestick/WS +drift. Additive only. No breaking changes. + +### Added + +- **`markets.create_flight_disruption_market(...)`** (sync and async) — + `POST /flight_disruption_markets`, 200 `CreateFlightDisruptionMarketResponse`. + Authenticated. Returns the flight disruption market for a flight, cover + and optional delay, creating it if it does not exist. `created` is false + when a market for the same request already existed. Required: `carrier`, + `flight_number`, `departure_airport`, `arrival_airport`, `scheduled_date` + (YYYY-MM-DD), `cover` (`FlightCoverLiteral`: `"cancelled"` / `"delayed"` / + `"either"`). Optional: `delay_basis` (`FlightDelayBasisLiteral`: + `"departure"` / `"arrival"`), `delay_minutes`. Accepts + `request=CreateFlightDisruptionMarketRequest(...)` or keyword fields. + POST is never retried. +- **`markets.flight_disruption_availability()`** (sync and async) — + `GET /flight_disruption_markets/availability`, 200 + `GetFlightDisruptionAvailabilityResponse`. Public. These three endpoints + are marked `x-excluded` in the spec; they may not be launched yet. +- **`markets.list_flights(*, carrier, flight_number, date)`** (sync and + async) — `GET /flight_disruption_markets/flights`, 200 `GetFlightsResponse`. + Authenticated. Looks up a flight number on a departure date. (Closes #586). +- Optional **`end_date`** (`str | None`) on + `CreateWeatherPointMarketRequest` and both sync and async + `create_weather_point_market` overloads. Omitted when unset; existing + callers are unchanged. The spec marks this field optional. +- Perps **`MarginMarketScheduleDetails.kalshi_trading_schedule`** optional + `MarginTradingCronSchedule` (`timezone` is `"America/New_York"`; + `open_crons` / `close_crons` lists). +- Perps WS optional **`subaccount_type`** on `MarginOrderbookDeltaPayload`, + `MarginFillPayload`, and `MarginUserOrderPayload`, typed with REST + `SubaccountTypeLiteral` (also accepts `"auto_rebalance"`). + +### Changed + +- **`GetWeatherPointAvailabilityResponse.max_window_days`** / + **`max_window_hours`** are optional (`int | None`). Spec 3.37.0 marks + both required; the SDK keeps them optional so payloads that omit the + keys still parse (`server_omits_despite_required`). +- Perps **`MarginMarketCandlestick.ask`** is now + `MarginAskDistributionHistorical`: required keys, JSON-nullable + `open` / `low` / `high` / `close` (`DollarDecimal | None`, + `AliasChoices(foo_dollars, foo)`), so candlesticks from periods with no + asks parse instead of failing validation. Bid OHLC stays non-null + `BidAskDistributionHistorical`. Strict-mypy code doing arithmetic on ask + values may need a `None` check. + +### Docs + +- Weather point: coordinates rounded to three decimals; `end_date` can + cross midnight (at most 24 hours) when `max_window_days == 2`. +- Concert `enabled` lists concerts; it does not promise that create will + succeed. +- Perps market schedules include recurring trading hours, not only + holiday closures. +- Perps `managed_isolated` uses the same subaccount number as the + market's isolated subaccount. +- AsyncAPI orderbook snapshot `market_id` may now be `""` (already accepted + as `str`). Snapshot parsing is unchanged and still requires both book sides. + ## 22.14.0 — 2026-11-13 Adds on-request concert cancellation markets (#582) against OpenAPI v3.36.0 diff --git a/CLAUDE.md b/CLAUDE.md index 4464427..a43dee9 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, 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) +- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.37.0, 145 operations; 144 mapped in the core SDK — `POST /portfolio/intra_exchange_instance_transfer` is implemented on `PerpsClient.transfers.transfer_instance` and left unimplemented on the core client) - AsyncAPI spec: https://docs.kalshi.com/asyncapi.yaml (16 WebSocket channels; 13 typed `subscribe_*` + escape-hatch) - 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 b42ffdc..c848a28 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 (141 mapped of 142 operations across 19 resources, OpenAPI v3.36.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch). +- **Full coverage** of the Kalshi REST API (144 mapped of 145 operations across 19 resources, OpenAPI v3.37.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 7fbb49b..b4ca370 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,8 +3,8 @@ A professional, spec-first Python SDK for the [Kalshi](https://kalshi.com) prediction markets API. -- **Full REST coverage** — 141 mapped of 142 operations across 19 resources - (OpenAPI v3.36.0), every kwarg drift-tested against the spec. +- **Full REST coverage** — 144 mapped of 145 operations across 19 resources + (OpenAPI v3.37.0), every kwarg drift-tested against the spec. - **V2 event-market orders** — new `create_v2` / `amend_v2` / `decrease_v2` / `cancel_v2` / `cancel_all_v2` family on `/portfolio/events/orders/*`. Legacy `/portfolio/orders` keeps working; deprecation no earlier than May 6, 2026. diff --git a/docs/perps.md b/docs/perps.md index f31fae4..b50bc94 100644 --- a/docs/perps.md +++ b/docs/perps.md @@ -83,12 +83,15 @@ for ticker, details in schedules.items(): print(ticker, len(details.kalshi_trading_holidays)) ``` -`markets.schedules(*, tickers)` returns Kalshi trading-holiday closures -(`GET /margin/markets/schedules`) as a ticker → `MarginMarketScheduleDetails` -map. `tickers` is required (1–100, each 1–200 characters) and serializes as a -comma-separated query string. Regular daily and weekend closures are not -included. Each holiday window's spec field `from` is `start` on -`MarginHolidayWindow` (`until` is the exclusive end). +`markets.schedules(*, tickers)` returns recurring Kalshi trading hours and +holiday closures (`GET /margin/markets/schedules`) as a ticker → +`MarginMarketScheduleDetails` map. `tickers` is required (1–100, each 1–200 +characters) and serializes as a comma-separated query string. Optional +`kalshi_trading_schedule` is a `MarginTradingCronSchedule` (`timezone` is +`America/New_York`; `open_crons` / `close_crons` are five-field cron lists). +Empty cron arrays mean continuous trading except for +`kalshi_trading_holidays`. Each holiday window's spec field `from` is +`start` on `MarginHolidayWindow` (`until` is the exclusive end). The margin order side is `bid` / `ask` (not the prediction API's `yes` / `no`). Orders create/cancel/decrease/amend are POSTs/DELETEs and are **never retried**. @@ -231,8 +234,9 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id) (`"cross"` / `"isolated"` / `"auto_rebalance"` / `"managed_isolated"`, or `None` when the key is absent) is optional on `MarginPosition`, `MarginSubaccountBalance`, `MarginRiskPosition`, and - `MarginFundingHistoryEntry`. The spec marks it required; the SDK keeps it - optional so older payloads still parse. + `MarginFundingHistoryEntry`. `managed_isolated` uses the same subaccount + number as the market's isolated subaccount. The spec marks it required; the + SDK keeps it optional so older payloads still parse. - **Portfolio hedging** (since the v3.23.0 spec sync) — `MarginPosition` and `MarginRiskPosition` carry a **required** `is_portfolio` (`bool`), `True` when the position is hedged within a portfolio so its margin is computed at the diff --git a/docs/resources/markets.md b/docs/resources/markets.md index 7bedaa9..977593d 100644 --- a/docs/resources/markets.md +++ b/docs/resources/markets.md @@ -23,6 +23,9 @@ recent trades. | `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** | +| `create_flight_disruption_market(...)` | `POST /flight_disruption_markets` | **yes** | +| `flight_disruption_availability()` | `GET /flight_disruption_markets/availability` | no | +| `list_flights(*, carrier, flight_number, date)` | `GET /flight_disruption_markets/flights` | **yes** | !!! warning "Orderbook endpoints require auth" `orderbook()` and `bulk_orderbooks()` raise `AuthRequiredError` on an @@ -155,7 +158,7 @@ Creation is authenticated; availability is public. POST is never retried. ```python avail = client.markets.weather_point_availability() -print(avail.enabled, [d.name for d in avail.domains]) +print(avail.enabled, [d.name for d in avail.domains], avail.max_window_days) resp = client.markets.create_weather_point_market( latitude=40.785, @@ -167,6 +170,7 @@ resp = client.markets.create_weather_point_market( end_hour=24, timezone="America/New_York", floor_value=2, + end_date="2026-11-12", # optional; omit for a same-day window ) print(resp.market_ticker, resp.created, resp.latitude, resp.longitude) ``` @@ -175,7 +179,10 @@ print(resp.market_ticker, resp.created, resp.latitude, resp.longitude) `cap_value` for `"less"` and `"between"`. The SDK does not enforce that — 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. +Coordinates are rounded to three decimal places; requests that agree to +three decimals share a market. Optional `end_date` (the day after `date`) +opens a window that crosses midnight, at most 24 hours, where availability +returns `max_window_days == 2`. ## Concert cancellation markets @@ -201,12 +208,51 @@ 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`. +`search_concerts`. A cover missing from `avail.covers` cannot be created. +`enabled` means concerts are listed; it does not promise that a create will +succeed — where listing is on before markets are offered, create returns 409. +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. +## Flight disruption markets + +On-request markets on whether a flight is canceled or delayed. Creation and +flight lookup are authenticated; availability is public. POST is never +retried. These endpoints are marked `x-excluded` in the spec; they may not +be launched yet. + +```python +avail = client.markets.flight_disruption_availability() +print(avail.enabled, avail.covers, avail.delay_bases, avail.delay_step_minutes) + +flights = client.markets.list_flights( + carrier="AA", + flight_number="100", + date="2026-11-25", # YYYY-MM-DD +) +leg = flights.flights[0] + +resp = client.markets.create_flight_disruption_market( + carrier=leg.carrier, + flight_number=leg.flight_number, + departure_airport=leg.departure_airport, + arrival_airport=leg.arrival_airport, + scheduled_date=leg.scheduled_date, + cover="cancelled", # FlightCoverLiteral: "cancelled" / "delayed" / "either" +) +print(resp.market_ticker, resp.created, resp.cover) +``` + +Take the five flight fields from `list_flights`. For `"delayed"` and +`"either"`, also pass `delay_basis` (`"departure"` / `"arrival"`) and +`delay_minutes` (a multiple of `avail.delay_step_minutes`, up to +`avail.max_delay_minutes`); leave both out for `"cancelled"`. 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`. + ## Reference ::: kalshi.resources.markets.MarketsResource diff --git a/kalshi/__init__.py b/kalshi/__init__.py index c0bb211..384d5ad 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -69,6 +69,8 @@ CreateFCMPositionTransferResponse, CreateFCMSubtraderRequest, CreateFCMSubtraderResponse, + CreateFlightDisruptionMarketRequest, + CreateFlightDisruptionMarketResponse, CreateMarketInMultivariateEventCollectionRequest, CreateMarketResponse, CreateOrderGroupRequest, @@ -116,6 +118,10 @@ FcmFill, FCMSubtrader, Fill, + Flight, + FlightCoverEvent, + FlightCoverLiteral, + FlightDelayBasisLiteral, ForecastPercentilesPoint, GenerateApiKeyRequest, GenerateApiKeyResponse, @@ -130,6 +136,8 @@ GetFcmFillsResponse, GetFCMSubtraderBlockedCategoriesResponse, GetFiltersBySportsResponse, + GetFlightDisruptionAvailabilityResponse, + GetFlightsResponse, GetGameStatsResponse, GetIncentiveProgramsResponse, GetIncentiveSchedulesResponse, @@ -323,6 +331,8 @@ "CreateFCMPositionTransferResponse", "CreateFCMSubtraderRequest", "CreateFCMSubtraderResponse", + "CreateFlightDisruptionMarketRequest", + "CreateFlightDisruptionMarketResponse", "CreateMarketInMultivariateEventCollectionRequest", "CreateMarketResponse", "CreateOrderGroupRequest", @@ -374,6 +384,10 @@ "FixConfig", "FixEnvironment", "FixSessionType", + "Flight", + "FlightCoverEvent", + "FlightCoverLiteral", + "FlightDelayBasisLiteral", "ForecastPercentilesPoint", "GenerateApiKeyRequest", "GenerateApiKeyResponse", @@ -388,6 +402,8 @@ "GetFCMSubtraderBlockedCategoriesResponse", "GetFcmFillsResponse", "GetFiltersBySportsResponse", + "GetFlightDisruptionAvailabilityResponse", + "GetFlightsResponse", "GetGameStatsResponse", "GetIncentiveProgramsResponse", "GetIncentiveSchedulesResponse", @@ -537,4 +553,4 @@ "Withdrawal", ] -__version__ = "22.14.0" +__version__ = "22.15.0" diff --git a/kalshi/_contract_map.py b/kalshi/_contract_map.py index dc0f7bd..82afdea 100644 --- a/kalshi/_contract_map.py +++ b/kalshi/_contract_map.py @@ -548,6 +548,30 @@ class ContractEntry: sdk_model="kalshi.models.markets.SearchConcertsResponse", spec_schema="SearchConcertsResponse", ), + ContractEntry( + sdk_model="kalshi.models.markets.CreateFlightDisruptionMarketRequest", + spec_schema="CreateFlightDisruptionMarketRequest", + ), + ContractEntry( + sdk_model="kalshi.models.markets.CreateFlightDisruptionMarketResponse", + spec_schema="CreateFlightDisruptionMarketResponse", + ), + ContractEntry( + sdk_model="kalshi.models.markets.GetFlightDisruptionAvailabilityResponse", + spec_schema="GetFlightDisruptionAvailabilityResponse", + ), + ContractEntry( + sdk_model="kalshi.models.markets.FlightCoverEvent", + spec_schema="FlightCoverEvent", + ), + ContractEntry( + sdk_model="kalshi.models.markets.Flight", + spec_schema="Flight", + ), + ContractEntry( + sdk_model="kalshi.models.markets.GetFlightsResponse", + spec_schema="GetFlightsResponse", + ), # -- orders V2 family (#171) ----------------------------------------- ContractEntry( sdk_model="kalshi.models.orders.CreateOrderV2Request", @@ -898,6 +922,10 @@ class ContractEntry: sdk_model="kalshi.perps.models.markets.MarginMarketScheduleDetails", spec_schema="MarginMarketScheduleDetails", ), + ContractEntry( + sdk_model="kalshi.perps.models.markets.MarginTradingCronSchedule", + spec_schema="MarginTradingCronSchedule", + ), ContractEntry( sdk_model="kalshi.perps.models.markets.MarginMarketCandlestick", spec_schema="MarginMarketCandlestick", @@ -906,6 +934,10 @@ class ContractEntry: sdk_model="kalshi.perps.models.markets.BidAskDistributionHistorical", spec_schema="BidAskDistributionHistorical", ), + ContractEntry( + sdk_model="kalshi.perps.models.markets.MarginAskDistributionHistorical", + spec_schema="MarginAskDistributionHistorical", + ), ContractEntry( sdk_model="kalshi.perps.models.markets.PriceDistributionHistorical", spec_schema="PriceDistributionHistorical", diff --git a/kalshi/models/__init__.py b/kalshi/models/__init__.py index 096a2be..282f98e 100644 --- a/kalshi/models/__init__.py +++ b/kalshi/models/__init__.py @@ -129,10 +129,18 @@ ConcertMetro, CreateConcertCancellationMarketRequest, CreateConcertCancellationMarketResponse, + CreateFlightDisruptionMarketRequest, + CreateFlightDisruptionMarketResponse, CreateWeatherPointMarketRequest, CreateWeatherPointMarketResponse, + Flight, + FlightCoverEvent, + FlightCoverLiteral, + FlightDelayBasisLiteral, GetConcertCancellationAvailabilityResponse, GetConcertsResponse, + GetFlightDisruptionAvailabilityResponse, + GetFlightsResponse, GetWeatherPointAvailabilityResponse, Market, MarketCandlesticks, @@ -300,6 +308,8 @@ "CreateFCMPositionTransferResponse", "CreateFCMSubtraderRequest", "CreateFCMSubtraderResponse", + "CreateFlightDisruptionMarketRequest", + "CreateFlightDisruptionMarketResponse", "CreateMarketInMultivariateEventCollectionRequest", "CreateMarketResponse", "CreateOrderGroupRequest", @@ -347,6 +357,10 @@ "FCMSubtrader", "FcmFill", "Fill", + "Flight", + "FlightCoverEvent", + "FlightCoverLiteral", + "FlightDelayBasisLiteral", "ForecastPercentilesPoint", "GenerateApiKeyRequest", "GenerateApiKeyResponse", @@ -361,6 +375,8 @@ "GetFCMSubtraderBlockedCategoriesResponse", "GetFcmFillsResponse", "GetFiltersBySportsResponse", + "GetFlightDisruptionAvailabilityResponse", + "GetFlightsResponse", "GetGameStatsResponse", "GetIncentiveProgramsResponse", "GetIncentiveSchedulesResponse", diff --git a/kalshi/models/markets.py b/kalshi/models/markets.py index 95f41da..5a08c7f 100644 --- a/kalshi/models/markets.py +++ b/kalshi/models/markets.py @@ -322,7 +322,7 @@ class CreateWeatherPointMarketRequest(BaseModel): Matches spec ``components.schemas.CreateWeatherPointMarketRequest``. Required: ``latitude``, ``longitude``, ``variable``, ``strike_type``, ``date``, ``start_hour``, ``end_hour``, ``timezone``. Optional: - ``floor_value``, ``cap_value``. + ``end_date``, ``floor_value``, ``cap_value``. """ latitude: float @@ -330,6 +330,7 @@ class CreateWeatherPointMarketRequest(BaseModel): variable: WeatherPointVariableLiteral strike_type: Literal["greater", "less", "between"] date: str + end_date: str | None = None start_hour: int end_hour: int timezone: str @@ -373,11 +374,17 @@ class WeatherPointVariableAvailability(BaseModel): class GetWeatherPointAvailabilityResponse(BaseModel): - """Response from GET /weather_point_markets/availability.""" + """Response from GET /weather_point_markets/availability. + + ``max_window_days`` / ``max_window_hours`` are spec-required; the SDK + keeps them optional so payloads that omit the keys still parse. + """ enabled: bool domains: NullableList[WeatherPointDomain] variables: NullableList[WeatherPointVariableAvailability] + max_window_days: int | None = None + max_window_hours: int | None = None model_config = {"extra": "allow"} @@ -424,7 +431,12 @@ class ConcertMetro(BaseModel): class GetConcertCancellationAvailabilityResponse(BaseModel): - """Response from GET /concert_cancellation_markets/availability.""" + """Response from GET /concert_cancellation_markets/availability. + + ``enabled`` is whether concerts are listed. It does not promise that + markets can be created: where concerts are listed before markets are + offered, it is true and every create request returns 409. + """ enabled: bool covers: NullableList[ConcertCoverLiteral] @@ -482,3 +494,106 @@ class SearchConcertsResponse(BaseModel): concerts: NullableList[Concert] model_config = {"extra": "allow"} + + +FlightCoverLiteral = Literal["cancelled", "delayed", "either"] +"""What a flight disruption market pays on. Spec: FlightCover enum.""" + +FlightDelayBasisLiteral = Literal["departure", "arrival"] +"""Which gate time a delay is measured at. Spec: FlightDelayBasis enum.""" + + +class CreateFlightDisruptionMarketRequest(BaseModel): + """Body for POST /flight_disruption_markets. + + Matches spec ``components.schemas.CreateFlightDisruptionMarketRequest``. + Required: ``carrier``, ``flight_number``, ``departure_airport``, + ``arrival_airport``, ``scheduled_date``, ``cover``. Optional: + ``delay_basis``, ``delay_minutes``. + """ + + carrier: str + flight_number: str + departure_airport: str + arrival_airport: str + scheduled_date: str + cover: FlightCoverLiteral + delay_basis: FlightDelayBasisLiteral | None = None + delay_minutes: int | None = None + + model_config = {"extra": "forbid"} + + +class CreateFlightDisruptionMarketResponse(BaseModel): + """Response from POST /flight_disruption_markets.""" + + cover: FlightCoverLiteral + event_ticker: str + market_ticker: str + created: bool + delay_basis: FlightDelayBasisLiteral | None = None + delay_minutes: int | None = None + + model_config = {"extra": "allow"} + + +class GetFlightDisruptionAvailabilityResponse(BaseModel): + """Response from GET /flight_disruption_markets/availability.""" + + enabled: bool + covers: NullableList[FlightCoverLiteral] + delay_bases: NullableList[FlightDelayBasisLiteral] + delay_step_minutes: int + max_delay_minutes: int + max_days_ahead: int + min_lead_minutes: int + departure_countries: NullableList[str] + + model_config = {"extra": "allow"} + + +class FlightCoverEvent(BaseModel): + """Event and market tickers a flight has or would get for one cover.""" + + cover: FlightCoverLiteral + series_ticker: str + event_ticker: str + market_ticker: str | None = None + + model_config = {"extra": "allow"} + + +class Flight(BaseModel): + """A flight listing that a disruption market can still be created for.""" + + carrier: str + flight_number: str + departure_airport: str + arrival_airport: str + scheduled_date: str + events: NullableList[FlightCoverEvent] + airline_name: str | None = None + departure_airport_name: str | None = None + departure_city: str | None = None + departure_country: str | None = None + departure_timezone: str | None = None + arrival_airport_name: str | None = None + arrival_city: str | None = None + arrival_country: str | None = None + arrival_timezone: str | None = None + scheduled_departure: AwareDatetime | None = None + scheduled_arrival: AwareDatetime | None = None + close_time: AwareDatetime | None = None + settle_after: AwareDatetime | None = None + requested_carrier: str | None = None + requested_flight_number: str | None = None + + model_config = {"extra": "allow"} + + +class GetFlightsResponse(BaseModel): + """Response from GET /flight_disruption_markets/flights.""" + + flights: NullableList[Flight] + + model_config = {"extra": "allow"} diff --git a/kalshi/perps/__init__.py b/kalshi/perps/__init__.py index e1c39d4..1159cbe 100644 --- a/kalshi/perps/__init__.py +++ b/kalshi/perps/__init__.py @@ -120,6 +120,7 @@ ) from kalshi.perps.models.markets import ( BidAskDistributionHistorical, + MarginAskDistributionHistorical, MarginHolidayWindow, MarginMarket, MarginMarketCandlestick, @@ -128,6 +129,7 @@ MarginMarketStatusLiteral, MarginOrderbook, MarginOrderbookLevel, + MarginTradingCronSchedule, PriceDistributionHistorical, ) from kalshi.perps.models.order_groups import ( @@ -336,6 +338,7 @@ "LastUpdateReasonLiteral", "MaintenanceMarginDetail", "MarginAccountResource", + "MarginAskDistributionHistorical", "MarginCorporateAction", "MarginCorporateActionCashTerms", "MarginCorporateActionFinalSettlementTerms", @@ -381,6 +384,7 @@ "MarginTrade", "MarginTradeMessage", "MarginTradePayload", + "MarginTradingCronSchedule", "MarginUserOrderMessage", "MarginUserOrderPayload", "MarketSettlementEstimate", diff --git a/kalshi/perps/models/__init__.py b/kalshi/perps/models/__init__.py index 3a2bdc3..886b6a0 100644 --- a/kalshi/perps/models/__init__.py +++ b/kalshi/perps/models/__init__.py @@ -66,6 +66,7 @@ ) from kalshi.perps.models.markets import ( BidAskDistributionHistorical, + MarginAskDistributionHistorical, MarginHolidayWindow, MarginMarket, MarginMarketCandlestick, @@ -74,6 +75,7 @@ MarginMarketStatusLiteral, MarginOrderbook, MarginOrderbookLevel, + MarginTradingCronSchedule, PriceDistributionHistorical, ) from kalshi.perps.models.order_groups import ( @@ -178,6 +180,7 @@ "IntraExchangeInstanceTransferResponse", "LastUpdateReason", "LastUpdateReasonLiteral", + "MarginAskDistributionHistorical", "MarginCorporateAction", "MarginCorporateActionCashTerms", "MarginCorporateActionFinalSettlementTerms", @@ -206,6 +209,7 @@ "MarginRiskPosition", "MarginSubaccountBalance", "MarginTrade", + "MarginTradingCronSchedule", "NotionalRiskLimitResponse", "OrderGroup", "OrderSource", diff --git a/kalshi/perps/models/common.py b/kalshi/perps/models/common.py index 318623d..95da43e 100644 --- a/kalshi/perps/models/common.py +++ b/kalshi/perps/models/common.py @@ -110,7 +110,7 @@ class ExchangeInstance(StrEnum): a market's isolated subaccount, ``auto_rebalance`` for an auto-rebalanced isolated position (shares its market's isolated subaccount number), and ``managed_isolated`` for a managed isolated position (subaccount number is -its slot number rather than the market's isolated subaccount number). +the same as the market's isolated subaccount number). """ diff --git a/kalshi/perps/models/markets.py b/kalshi/perps/models/markets.py index 7d49f6f..81c9d29 100644 --- a/kalshi/perps/models/markets.py +++ b/kalshi/perps/models/markets.py @@ -207,7 +207,7 @@ class MarginOrderbook(BaseModel): class BidAskDistributionHistorical(BaseModel): - """Spec ``BidAskDistributionHistorical`` — OHLC for quoted bid/ask prices. + """Spec ``BidAskDistributionHistorical`` — OHLC for quoted bid prices. All four fields are required and non-null per spec. """ @@ -228,6 +228,29 @@ class BidAskDistributionHistorical(BaseModel): model_config = {"extra": "allow", "populate_by_name": True} +class MarginAskDistributionHistorical(BaseModel): + """Spec ``MarginAskDistributionHistorical`` — OHLC for ask quotes. + + All four fields are required keys and JSON-nullable when the orderbook + had no asks. + """ + + open: DollarDecimal | None = Field( + validation_alias=AliasChoices("open_dollars", "open"), + ) + high: DollarDecimal | None = Field( + validation_alias=AliasChoices("high_dollars", "high"), + ) + low: DollarDecimal | None = Field( + validation_alias=AliasChoices("low_dollars", "low"), + ) + close: DollarDecimal | None = Field( + validation_alias=AliasChoices("close_dollars", "close"), + ) + + model_config = {"extra": "allow", "populate_by_name": True} + + class PriceDistributionHistorical(BaseModel): """Spec ``PriceDistributionHistorical`` — OHLC for executed trade prices. @@ -261,7 +284,7 @@ class MarginMarketCandlestick(BaseModel): end_period_ts: int bid: BidAskDistributionHistorical - ask: BidAskDistributionHistorical + ask: MarginAskDistributionHistorical price: PriceDistributionHistorical volume: FixedPointCount = Field( validation_alias=AliasChoices("volume_fp", "volume"), @@ -344,13 +367,27 @@ class MarginHolidayWindow(BaseModel): model_config = {"extra": "allow", "populate_by_name": True} +class MarginTradingCronSchedule(BaseModel): + """Recurring Kalshi trading hours, including market-specific overrides. + + Empty cron arrays mean continuous trading except for closures in + ``kalshi_trading_holidays``. + """ + + timezone: Literal["America/New_York"] + open_crons: NullableList[str] + close_crons: NullableList[str] + + model_config = {"extra": "allow"} + + class MarginMarketScheduleDetails(BaseModel): - """Holiday closures for one margin market. + """Recurring Kalshi trading hours and holiday closures for one margin market. - Regular daily and weekend closures are not included. The schedules - endpoint returns a ticker → details map; this is one value. + The schedules endpoint returns a ticker → details map; this is one value. """ kalshi_trading_holidays: list[MarginHolidayWindow] + kalshi_trading_schedule: MarginTradingCronSchedule | None = None model_config = {"extra": "allow"} diff --git a/kalshi/perps/resources/markets.py b/kalshi/perps/resources/markets.py index 787b957..55e906a 100644 --- a/kalshi/perps/resources/markets.py +++ b/kalshi/perps/resources/markets.py @@ -217,12 +217,11 @@ def schedules( tickers: builtins.list[str], extra_headers: dict[str, str] | None = None, ) -> dict[str, MarginMarketScheduleDetails]: - """``GET /margin/markets/schedules`` — holiday closures for up to 100 tickers. + """``GET /margin/markets/schedules`` — recurring hours and holiday closures. Public market data (no auth). ``tickers`` is required (1-100, each 1-200 characters) and serializes as a comma-separated query string. - The body is a map keyed by market ticker. Regular daily and weekend - closures are not included. + The body is a map keyed by market ticker. """ params = _schedules_params(tickers=tickers) data = self._get( diff --git a/kalshi/perps/ws/models/fill.py b/kalshi/perps/ws/models/fill.py index 4808f90..aaf267b 100644 --- a/kalshi/perps/ws/models/fill.py +++ b/kalshi/perps/ws/models/fill.py @@ -10,6 +10,7 @@ from pydantic import BaseModel +from kalshi.perps.models.common import SubaccountTypeLiteral from kalshi.perps.ws.models._common import PerpsBookSide, PerpsOrderSource from kalshi.types import DollarDecimal, FixedPointCount @@ -21,7 +22,8 @@ class MarginFillPayload(BaseModel): ``is_taker``, ``side`` (``bid``/``ask``), ``ts_ms`` (epoch ms), ``price`` (dollar-decimal), ``count``/``post_position`` (fixed-point counts), ``fee_cost`` (dollar-decimal), and ``order_source`` (``user``/``system``). - ``client_order_id`` and ``subaccount`` are optional. + ``client_order_id``, ``subaccount``, and ``subaccount_type`` are optional. + ``subaccount_type`` is present only when ``subaccount`` is. """ trade_id: str @@ -37,6 +39,7 @@ class MarginFillPayload(BaseModel): order_source: PerpsOrderSource client_order_id: str | None = None subaccount: int | None = None + subaccount_type: SubaccountTypeLiteral | None = None model_config = {"extra": "allow", "populate_by_name": True} diff --git a/kalshi/perps/ws/models/orderbook.py b/kalshi/perps/ws/models/orderbook.py index 4229be5..75a3cf4 100644 --- a/kalshi/perps/ws/models/orderbook.py +++ b/kalshi/perps/ws/models/orderbook.py @@ -15,6 +15,7 @@ from pydantic import BaseModel, BeforeValidator, Field +from kalshi.perps.models.common import SubaccountTypeLiteral from kalshi.perps.ws.models._common import ( PerpsBookSide, PerpsLastUpdateReason, @@ -95,6 +96,7 @@ class MarginOrderbookDeltaPayload(BaseModel): Single-sided incremental update. ``price`` is a dollar-decimal string, ``delta`` is a fixed-point count string (may be negative), ``side`` is ``bid``/``ask``. ``ts_ms`` is epoch milliseconds (``int``), NOT RFC3339. + ``subaccount_type`` is present only when ``subaccount`` is. """ market_ticker: str @@ -104,6 +106,7 @@ class MarginOrderbookDeltaPayload(BaseModel): last_update_reason: PerpsLastUpdateReason | None = None client_order_id: str | None = None subaccount: int | None = None + subaccount_type: SubaccountTypeLiteral | None = None ts_ms: int | None = None model_config = {"extra": "allow", "populate_by_name": True} diff --git a/kalshi/perps/ws/models/user_orders.py b/kalshi/perps/ws/models/user_orders.py index b1dcc7d..fc9cae7 100644 --- a/kalshi/perps/ws/models/user_orders.py +++ b/kalshi/perps/ws/models/user_orders.py @@ -13,6 +13,7 @@ from pydantic import BaseModel +from kalshi.perps.models.common import SubaccountTypeLiteral from kalshi.perps.ws.models._common import ( PerpsBookSide, PerpsOrderSource, @@ -28,8 +29,10 @@ class MarginUserOrderPayload(BaseModel): ``ticker`` (note: ``ticker``, NOT ``market_ticker``), ``side`` (``bid``/ ``ask``), ``price`` (dollar-decimal), ``fill_count``/``remaining_count`` (fixed-point counts), ``created_ts_ms`` (epoch ms), and ``order_source`` - (``user``/``system``). The remaining fields — STP type, order-group id, and - the ``*_ts_ms`` timestamps — are optional. + (``user``/``system``). The remaining fields — STP type, order-group id, + the ``*_ts_ms`` timestamps, ``subaccount_number``, and ``subaccount_type`` + — are optional. ``subaccount_type`` is present only when + ``subaccount_number`` is. """ order_id: str @@ -47,6 +50,7 @@ class MarginUserOrderPayload(BaseModel): expiration_ts_ms: int | None = None last_updated_ts_ms: int | None = None subaccount_number: int | None = None + subaccount_type: SubaccountTypeLiteral | None = None model_config = {"extra": "allow", "populate_by_name": True} diff --git a/kalshi/resources/markets.py b/kalshi/resources/markets.py index 91f7180..384e2b0 100644 --- a/kalshi/resources/markets.py +++ b/kalshi/resources/markets.py @@ -17,10 +17,16 @@ ConcertCoverLiteral, CreateConcertCancellationMarketRequest, CreateConcertCancellationMarketResponse, + CreateFlightDisruptionMarketRequest, + CreateFlightDisruptionMarketResponse, CreateWeatherPointMarketRequest, CreateWeatherPointMarketResponse, + FlightCoverLiteral, + FlightDelayBasisLiteral, GetConcertCancellationAvailabilityResponse, GetConcertsResponse, + GetFlightDisruptionAvailabilityResponse, + GetFlightsResponse, GetMarketCandlesticksResponse, GetMarketOrderbooksResponse, GetWeatherPointAvailabilityResponse, @@ -237,6 +243,7 @@ def _build_create_weather_point_market_body( variable: WeatherPointVariableLiteral | None, strike_type: Literal["greater", "less", "between"] | None, date: str | None, + end_date: str | None, start_hour: int | None, end_hour: int | None, timezone: str | None, @@ -250,6 +257,7 @@ def _build_create_weather_point_market_body( variable=variable, strike_type=strike_type, date=date, + end_date=end_date, start_hour=start_hour, end_hour=end_hour, timezone=timezone, @@ -278,6 +286,7 @@ def _build_create_weather_point_market_body( variable=variable, strike_type=strike_type, date=date, + end_date=end_date, start_hour=start_hour, end_hour=end_hour, timezone=timezone, @@ -314,6 +323,56 @@ def _build_create_concert_cancellation_market_body( return request.model_dump(exclude_none=True, by_alias=True, mode="json") +def _build_create_flight_disruption_market_body( + request: CreateFlightDisruptionMarketRequest | None, + *, + carrier: str | None, + flight_number: str | None, + departure_airport: str | None, + arrival_airport: str | None, + scheduled_date: str | None, + cover: FlightCoverLiteral | None, + delay_basis: FlightDelayBasisLiteral | None, + delay_minutes: int | None, +) -> dict[str, Any]: + _check_request_exclusive( + request, + carrier=carrier, + flight_number=flight_number, + departure_airport=departure_airport, + arrival_airport=arrival_airport, + scheduled_date=scheduled_date, + cover=cover, + delay_basis=delay_basis, + delay_minutes=delay_minutes, + ) + if request is None: + if ( + carrier is None + or flight_number is None + or departure_airport is None + or arrival_airport is None + or scheduled_date is None + or cover is None + ): + raise TypeError( + "create_flight_disruption_market() requires `carrier`, " + "`flight_number`, `departure_airport`, `arrival_airport`, " + "`scheduled_date`, and `cover` (or pass `request=...`)" + ) + request = CreateFlightDisruptionMarketRequest( + carrier=carrier, + flight_number=flight_number, + departure_airport=departure_airport, + arrival_airport=arrival_airport, + scheduled_date=scheduled_date, + cover=cover, + delay_basis=delay_basis, + delay_minutes=delay_minutes, + ) + return request.model_dump(exclude_none=True, by_alias=True, mode="json") + + class MarketsResource(SyncResource): """Sync markets API.""" @@ -582,6 +641,7 @@ def create_weather_point_market( start_hour: int, end_hour: int, timezone: str, + end_date: str | None = ..., floor_value: int | None = ..., cap_value: int | None = ..., extra_headers: dict[str, str] | None = None, @@ -595,6 +655,7 @@ def create_weather_point_market( variable: WeatherPointVariableLiteral | None = None, strike_type: Literal["greater", "less", "between"] | None = None, date: str | None = None, + end_date: str | None = None, start_hour: int | None = None, end_hour: int | None = None, timezone: str | None = None, @@ -606,7 +667,8 @@ def create_weather_point_market( Returns the on-request weather market for a location, time window and threshold, creating it if it does not exist. ``created`` is false when - a market for the same request already existed. + a market for the same request already existed. Optional ``end_date`` + (YYYY-MM-DD) is omitted when unset. """ self._require_auth() body = _build_create_weather_point_market_body( @@ -616,6 +678,7 @@ def create_weather_point_market( variable=variable, strike_type=strike_type, date=date, + end_date=end_date, start_hour=start_hour, end_hour=end_hour, timezone=timezone, @@ -726,6 +789,94 @@ def search_concerts( ) return SearchConcertsResponse.model_validate(data) + @overload + def create_flight_disruption_market( + self, + *, + request: CreateFlightDisruptionMarketRequest, + extra_headers: dict[str, str] | None = None, + ) -> CreateFlightDisruptionMarketResponse: ... + @overload + def create_flight_disruption_market( + self, + *, + carrier: str, + flight_number: str, + departure_airport: str, + arrival_airport: str, + scheduled_date: str, + cover: FlightCoverLiteral, + delay_basis: FlightDelayBasisLiteral | None = ..., + delay_minutes: int | None = ..., + extra_headers: dict[str, str] | None = None, + ) -> CreateFlightDisruptionMarketResponse: ... + def create_flight_disruption_market( + self, + *, + request: CreateFlightDisruptionMarketRequest | None = None, + carrier: str | None = None, + flight_number: str | None = None, + departure_airport: str | None = None, + arrival_airport: str | None = None, + scheduled_date: str | None = None, + cover: FlightCoverLiteral | None = None, + delay_basis: FlightDelayBasisLiteral | None = None, + delay_minutes: int | None = None, + extra_headers: dict[str, str] | None = None, + ) -> CreateFlightDisruptionMarketResponse: + """``POST /flight_disruption_markets``. Not retried. + + Returns the on-request flight disruption market for a flight, cover + and optional delay, creating it if it does not exist. ``created`` is + false when a market for the same request already existed. Marked + x-excluded in the spec; availability may not be launched. + """ + self._require_auth() + body = _build_create_flight_disruption_market_body( + request, + carrier=carrier, + flight_number=flight_number, + departure_airport=departure_airport, + arrival_airport=arrival_airport, + scheduled_date=scheduled_date, + cover=cover, + delay_basis=delay_basis, + delay_minutes=delay_minutes, + ) + data = self._post("/flight_disruption_markets", json=body, extra_headers=extra_headers) + return CreateFlightDisruptionMarketResponse.model_validate(data) + + def flight_disruption_availability( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetFlightDisruptionAvailabilityResponse: + """``GET /flight_disruption_markets/availability``. Public. + + Marked x-excluded in the spec; availability may not be launched. + """ + data = self._get("/flight_disruption_markets/availability", extra_headers=extra_headers) + return GetFlightDisruptionAvailabilityResponse.model_validate(data) + + def list_flights( + self, + *, + carrier: str, + flight_number: str, + date: str, + extra_headers: dict[str, str] | None = None, + ) -> GetFlightsResponse: + """``GET /flight_disruption_markets/flights``. Authenticated. + + Marked x-excluded in the spec; availability may not be launched. + """ + self._require_auth() + params = _params(carrier=carrier, flight_number=flight_number, date=date) + data = self._get( + "/flight_disruption_markets/flights", + params=params, + extra_headers=extra_headers, + ) + return GetFlightsResponse.model_validate(data) + class AsyncMarketsResource(AsyncResource): """Async markets API.""" @@ -1001,6 +1152,7 @@ async def create_weather_point_market( start_hour: int, end_hour: int, timezone: str, + end_date: str | None = ..., floor_value: int | None = ..., cap_value: int | None = ..., extra_headers: dict[str, str] | None = None, @@ -1014,6 +1166,7 @@ async def create_weather_point_market( variable: WeatherPointVariableLiteral | None = None, strike_type: Literal["greater", "less", "between"] | None = None, date: str | None = None, + end_date: str | None = None, start_hour: int | None = None, end_hour: int | None = None, timezone: str | None = None, @@ -1030,6 +1183,7 @@ async def create_weather_point_market( variable=variable, strike_type=strike_type, date=date, + end_date=end_date, start_hour=start_hour, end_hour=end_hour, timezone=timezone, @@ -1136,3 +1290,83 @@ async def search_concerts( extra_headers=extra_headers, ) return SearchConcertsResponse.model_validate(data) + + @overload + async def create_flight_disruption_market( + self, + *, + request: CreateFlightDisruptionMarketRequest, + extra_headers: dict[str, str] | None = None, + ) -> CreateFlightDisruptionMarketResponse: ... + @overload + async def create_flight_disruption_market( + self, + *, + carrier: str, + flight_number: str, + departure_airport: str, + arrival_airport: str, + scheduled_date: str, + cover: FlightCoverLiteral, + delay_basis: FlightDelayBasisLiteral | None = ..., + delay_minutes: int | None = ..., + extra_headers: dict[str, str] | None = None, + ) -> CreateFlightDisruptionMarketResponse: ... + async def create_flight_disruption_market( + self, + *, + request: CreateFlightDisruptionMarketRequest | None = None, + carrier: str | None = None, + flight_number: str | None = None, + departure_airport: str | None = None, + arrival_airport: str | None = None, + scheduled_date: str | None = None, + cover: FlightCoverLiteral | None = None, + delay_basis: FlightDelayBasisLiteral | None = None, + delay_minutes: int | None = None, + extra_headers: dict[str, str] | None = None, + ) -> CreateFlightDisruptionMarketResponse: + """Async :meth:`MarketsResource.create_flight_disruption_market`.""" + self._require_auth() + body = _build_create_flight_disruption_market_body( + request, + carrier=carrier, + flight_number=flight_number, + departure_airport=departure_airport, + arrival_airport=arrival_airport, + scheduled_date=scheduled_date, + cover=cover, + delay_basis=delay_basis, + delay_minutes=delay_minutes, + ) + data = await self._post( + "/flight_disruption_markets", json=body, extra_headers=extra_headers + ) + return CreateFlightDisruptionMarketResponse.model_validate(data) + + async def flight_disruption_availability( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetFlightDisruptionAvailabilityResponse: + """Async :meth:`MarketsResource.flight_disruption_availability`.""" + data = await self._get( + "/flight_disruption_markets/availability", extra_headers=extra_headers + ) + return GetFlightDisruptionAvailabilityResponse.model_validate(data) + + async def list_flights( + self, + *, + carrier: str, + flight_number: str, + date: str, + extra_headers: dict[str, str] | None = None, + ) -> GetFlightsResponse: + """Async :meth:`MarketsResource.list_flights`.""" + self._require_auth() + params = _params(carrier=carrier, flight_number=flight_number, date=date) + data = await self._get( + "/flight_disruption_markets/flights", + params=params, + extra_headers=extra_headers, + ) + return GetFlightsResponse.model_validate(data) diff --git a/pyproject.toml b/pyproject.toml index 0ce9aeb..7a78dcd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "22.14.0" +version = "22.15.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 ea1e5b8..b991c2e 100644 --- a/tests/_contract_support.py +++ b/tests/_contract_support.py @@ -183,6 +183,22 @@ class Exclusion: http_method="GET", path_template="/concert_cancellation_markets/concerts/search", ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.create_flight_disruption_market", + http_method="POST", + path_template="/flight_disruption_markets", + request_body_schema="#/components/schemas/CreateFlightDisruptionMarketRequest", + ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.flight_disruption_availability", + http_method="GET", + path_template="/flight_disruption_markets/availability", + ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.list_flights", + http_method="GET", + path_template="/flight_disruption_markets/flights", + ), # ── account ───────────────────────────────────────────────────────────── MethodEndpointEntry( sdk_method="kalshi.resources.account.AccountResource.limits", @@ -1526,6 +1542,28 @@ class Exclusion: ), kind="server_omits_despite_required", ), + ( + "kalshi.models.markets.GetWeatherPointAvailabilityResponse", + "max_window_days", + ): Exclusion( + reason=( + "spec 3.37.0 marks max_window_days required; the SDK keeps it " + "optional (None when absent) so payloads and fixtures predating the " + "field still validate and the change ships as a minor release (22.15.0)." + ), + kind="server_omits_despite_required", + ), + ( + "kalshi.models.markets.GetWeatherPointAvailabilityResponse", + "max_window_hours", + ): Exclusion( + reason=( + "spec 3.37.0 marks max_window_hours required; the SDK keeps it " + "optional (None when absent) so payloads and fixtures predating the " + "field still validate and the change ships as a minor release (22.15.0)." + ), + kind="server_omits_despite_required", + ), # --- server_omits_despite_required (#183, post-#172 nightly findings) --- # Fields the OpenAPI spec marks `required: true` but the live demo server # omits in practice. Each entry MUST cite a demo+prod observation in diff --git a/tests/perps/test_markets.py b/tests/perps/test_markets.py index 4209cc0..78209a3 100644 --- a/tests/perps/test_markets.py +++ b/tests/perps/test_markets.py @@ -19,12 +19,14 @@ from kalshi.perps import AsyncPerpsClient, PerpsClient, PerpsConfig from kalshi.perps.models.markets import ( BidAskDistributionHistorical, + MarginAskDistributionHistorical, MarginHolidayWindow, MarginMarket, MarginMarketCandlestick, MarginMarketSchedule, MarginMarketScheduleDetails, MarginOrderbook, + MarginTradingCronSchedule, PriceDistributionHistorical, ) @@ -597,6 +599,7 @@ def test_happy(self, perps_client: PerpsClient) -> None: assert isinstance(c.bid, BidAskDistributionHistorical) assert c.bid.open == Decimal("0.5500") assert c.bid.close == Decimal("0.5550") + assert isinstance(c.ask, MarginAskDistributionHistorical) assert c.ask.high == Decimal("0.5800") assert isinstance(c.price, PriceDistributionHistorical) assert c.price.open == Decimal("0.5600") @@ -636,9 +639,43 @@ def test_all_null_trade_prices(self, perps_client: PerpsClient) -> None: assert c.price.close is None assert c.price.mean is None assert c.price.previous is None - # bid/ask OHLC are still required + present. + # bid OHLC are still required + present; ask may be null. assert c.bid.open == Decimal("0.5500") + def test_nullable_ask_prices(self) -> None: + frame = _candle_dict( + ask={"open": None, "high": None, "low": None, "close": None}, + ) + c = MarginMarketCandlestick.model_validate(frame) + assert isinstance(c.ask, MarginAskDistributionHistorical) + assert c.ask.open is None + assert c.ask.high is None + assert c.ask.low is None + assert c.ask.close is None + assert c.bid.open == Decimal("0.5500") + + def test_ask_dollars_alias_and_partial_null(self) -> None: + frame = _candle_dict( + ask={ + "open_dollars": None, + "high_dollars": "0.5800", + "low_dollars": None, + "close_dollars": "0.5750", + } + ) + c = MarginMarketCandlestick.model_validate(frame) + assert c.ask.open is None + assert c.ask.high == Decimal("0.5800") + assert c.ask.low is None + assert c.ask.close == Decimal("0.5750") + + def test_bid_still_rejects_null(self) -> None: + frame = _candle_dict( + bid={"open": None, "high": "0.5600", "low": "0.5400", "close": "0.5550"}, + ) + with pytest.raises((ValidationError, TypeError)): + MarginMarketCandlestick.model_validate(frame) + def test_notional_value_required_on_candlestick(self) -> None: # Spec lists both notional fields under `required`; the model enforces it # (unlike the live MarginTickerPayload, where they are optional). @@ -751,6 +788,56 @@ def test_parses_holiday_map(self, perps_client: PerpsClient) -> None: assert window.reason == "Christmas" assert window.start.year == 2026 assert window.until.day == 26 + assert details["BTC-PERP"].kalshi_trading_schedule is None + + @respx.mock + def test_parses_cron_schedule(self, perps_client: PerpsClient) -> None: + respx.get(f"{BASE}/margin/markets/schedules").mock( + return_value=httpx.Response( + 200, + json={ + "BTC-PERP": { + "kalshi_trading_holidays": [], + "kalshi_trading_schedule": { + "timezone": "America/New_York", + "open_crons": ["0 9 * * 1-5"], + "close_crons": ["0 16 * * 1-5"], + }, + } + }, + ) + ) + details = perps_client.markets.schedules(tickers=["BTC-PERP"]) + schedule = details["BTC-PERP"].kalshi_trading_schedule + assert isinstance(schedule, MarginTradingCronSchedule) + assert schedule.timezone == "America/New_York" + assert schedule.open_crons == ["0 9 * * 1-5"] + assert schedule.close_crons == ["0 16 * * 1-5"] + + def test_cron_empty_arrays_and_null_lists(self) -> None: + parsed = MarginMarketScheduleDetails.model_validate( + { + "kalshi_trading_holidays": [], + "kalshi_trading_schedule": { + "timezone": "America/New_York", + "open_crons": [], + "close_crons": None, + }, + } + ) + assert parsed.kalshi_trading_schedule is not None + assert parsed.kalshi_trading_schedule.open_crons == [] + assert parsed.kalshi_trading_schedule.close_crons == [] + + def test_cron_rejects_other_timezone(self) -> None: + with pytest.raises(ValidationError): + MarginTradingCronSchedule.model_validate( + { + "timezone": "UTC", + "open_crons": [], + "close_crons": [], + } + ) def test_rejects_empty_blank_long_and_over_max(self, perps_client: PerpsClient) -> None: with pytest.raises(ValueError, match="non-empty"): diff --git a/tests/perps/ws/test_perps_ws_models.py b/tests/perps/ws/test_perps_ws_models.py index 2f4b844..cf90aa4 100644 --- a/tests/perps/ws/test_perps_ws_models.py +++ b/tests/perps/ws/test_perps_ws_models.py @@ -335,6 +335,45 @@ def test_delta_last_update_reason_settlement_bounds_cancel(self) -> None: msg = MarginOrderbookDeltaMessage.model_validate(frame) assert msg.msg.last_update_reason == "SettlementBoundsCancel" + def test_delta_subaccount_type_optional(self) -> None: + frame = { + "type": "orderbook_delta", + "sid": 1, + "seq": 2, + "msg": { + "market_ticker": "BTC-PERP", + "price": "100.5000", + "delta": "3.00", + "side": "ask", + "subaccount": 3, + "subaccount_type": "isolated", + }, + } + msg = MarginOrderbookDeltaMessage.model_validate(frame) + assert msg.msg.subaccount == 3 + assert msg.msg.subaccount_type == "isolated" + omitted = MarginOrderbookDeltaMessage.model_validate( + { + "type": "orderbook_delta", + "sid": 1, + "seq": 2, + "msg": { + "market_ticker": "BTC-PERP", + "price": "100.5000", + "delta": "3.00", + "side": "ask", + }, + } + ) + assert omitted.msg.subaccount_type is None + for value in ("cross", "isolated", "managed_isolated", "auto_rebalance"): + frame["msg"]["subaccount_type"] = value + parsed = MarginOrderbookDeltaMessage.model_validate(frame) + assert parsed.msg.subaccount_type == value + frame["msg"]["subaccount_type"] = "nope" + with pytest.raises(ValidationError): + MarginOrderbookDeltaMessage.model_validate(frame) + class TestTicker: def _full_frame(self) -> dict[str, Any]: @@ -531,6 +570,21 @@ def test_optional_fields_present(self) -> None: msg = MarginFillMessage.model_validate(frame) assert msg.msg.client_order_id == "coid-1" assert msg.msg.subaccount == 7 + assert msg.msg.subaccount_type is None + + def test_subaccount_type_optional(self) -> None: + frame = self._frame() + frame["msg"]["subaccount"] = 7 + frame["msg"]["subaccount_type"] = "cross" + msg = MarginFillMessage.model_validate(frame) + assert msg.msg.subaccount_type == "cross" + for value in ("cross", "isolated", "managed_isolated", "auto_rebalance"): + frame["msg"]["subaccount_type"] = value + parsed = MarginFillMessage.model_validate(frame) + assert parsed.msg.subaccount_type == value + frame["msg"]["subaccount_type"] = "nope" + with pytest.raises(ValidationError): + MarginFillMessage.model_validate(frame) def test_missing_post_position_raises(self) -> None: frame = self._frame() @@ -585,6 +639,22 @@ def test_rejects_bad_stp(self) -> None: with pytest.raises(ValidationError): MarginUserOrderMessage.model_validate(frame) + def test_subaccount_type_optional(self) -> None: + frame = self._frame() + assert MarginUserOrderMessage.model_validate(frame).msg.subaccount_type is None + frame["msg"]["subaccount_number"] = 4 + frame["msg"]["subaccount_type"] = "managed_isolated" + msg = MarginUserOrderMessage.model_validate(frame) + assert msg.msg.subaccount_number == 4 + assert msg.msg.subaccount_type == "managed_isolated" + for value in ("cross", "isolated", "managed_isolated", "auto_rebalance"): + frame["msg"]["subaccount_type"] = value + parsed = MarginUserOrderMessage.model_validate(frame) + assert parsed.msg.subaccount_type == value + frame["msg"]["subaccount_type"] = "nope" + with pytest.raises(ValidationError): + MarginUserOrderMessage.model_validate(frame) + class TestOrderGroup: def test_limit_updated_with_contracts_limit(self) -> None: diff --git a/tests/test_contracts.py b/tests/test_contracts.py index 1488ed1..8eaceac 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -1463,6 +1463,9 @@ def _assert_params_match( "#/components/schemas/CreateConcertCancellationMarketRequest": ( "kalshi.models.markets.CreateConcertCancellationMarketRequest" ), + "#/components/schemas/CreateFlightDisruptionMarketRequest": ( + "kalshi.models.markets.CreateFlightDisruptionMarketRequest" + ), "#/components/schemas/CreateOrderGroupRequest": ( "kalshi.models.order_groups.CreateOrderGroupRequest" ), diff --git a/tests/test_flight_disruption_markets.py b/tests/test_flight_disruption_markets.py new file mode 100644 index 0000000..c871b3c --- /dev/null +++ b/tests/test_flight_disruption_markets.py @@ -0,0 +1,646 @@ +"""Tests for flight disruption market endpoints on MarketsResource (#586).""" + +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, + KalshiNotFoundError, + KalshiRateLimitError, + KalshiServerError, + KalshiValidationError, +) +from kalshi.models.markets import CreateFlightDisruptionMarketRequest +from kalshi.resources.markets import AsyncMarketsResource, MarketsResource + +BASE = "https://test.kalshi.com/trade-api/v2" + +_CREATE_KWARGS: dict[str, object] = { + "carrier": "AA", + "flight_number": "100", + "departure_airport": "JFK", + "arrival_airport": "LHR", + "scheduled_date": "2026-11-25", + "cover": "cancelled", +} + +_CREATE_BODY = { + "carrier": "AA", + "flight_number": "100", + "departure_airport": "JFK", + "arrival_airport": "LHR", + "scheduled_date": "2026-11-25", + "cover": "cancelled", +} + +_CREATE_RESPONSE = { + "cover": "cancelled", + "event_ticker": "KXRFQFLIGHTC-AA100-JFKLHR-26NOV25", + "market_ticker": "KXRFQFLIGHTC-AA100-JFKLHR-26NOV25-CXL", + "created": True, +} + +_DELAY_KWARGS: dict[str, object] = { + **_CREATE_KWARGS, + "cover": "delayed", + "delay_basis": "departure", + "delay_minutes": 120, +} + +_DELAY_BODY = { + **_CREATE_BODY, + "cover": "delayed", + "delay_basis": "departure", + "delay_minutes": 120, +} + +_DELAY_RESPONSE = { + "cover": "delayed", + "delay_basis": "departure", + "delay_minutes": 120, + "event_ticker": "KXRFQFLIGHTD-AA100-JFKLHR-26NOV25", + "market_ticker": "KXRFQFLIGHTD-AA100-JFKLHR-26NOV25-DEP120", + "created": True, +} + +_FLIGHT = { + "carrier": "AA", + "flight_number": "100", + "airline_name": "American Airlines", + "departure_airport": "JFK", + "departure_airport_name": "John F. Kennedy International", + "departure_city": "New York", + "departure_country": "US", + "departure_timezone": "America/New_York", + "arrival_airport": "LHR", + "arrival_airport_name": "London Heathrow", + "arrival_city": "London", + "arrival_country": "GB", + "arrival_timezone": "Europe/London", + "scheduled_date": "2026-11-25", + "scheduled_departure": "2026-11-25T10:00:00Z", + "scheduled_arrival": "2026-11-25T22:00:00Z", + "close_time": "2026-11-25T10:00:00Z", + "settle_after": "2026-11-25T22:00:00Z", + "events": [ + { + "cover": "cancelled", + "series_ticker": "KXRFQFLIGHTC", + "event_ticker": "KXRFQFLIGHTC-AA100-JFKLHR-26NOV25", + "market_ticker": "KXRFQFLIGHTC-AA100-JFKLHR-26NOV25-CXL", + } + ], +} + +_AVAIL_RESPONSE = { + "enabled": True, + "covers": ["cancelled", "delayed", "either"], + "delay_bases": ["departure", "arrival"], + "delay_step_minutes": 30, + "max_delay_minutes": 360, + "max_days_ahead": 30, + "min_lead_minutes": 60, + "departure_countries": ["US"], +} + +_FLIGHTS_RESPONSE = { + "flights": [_FLIGHT], +} + + +@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 TestCreateFlightDisruptionMarket: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + resp = markets.create_flight_disruption_market(**_CREATE_KWARGS) + assert route.calls[0].request.method == "POST" + assert str(route.calls[0].request.url) == f"{BASE}/flight_disruption_markets" + body = json.loads(route.calls[0].request.content) + assert body == _CREATE_BODY + assert "delay_basis" not in body + assert "delay_minutes" not in body + assert resp.cover == "cancelled" + assert resp.event_ticker == _CREATE_RESPONSE["event_ticker"] + assert resp.market_ticker == _CREATE_RESPONSE["market_ticker"] + assert resp.created is True + assert resp.delay_basis is None + assert resp.delay_minutes is None + + @respx.mock + def test_delay_optionals_sent_when_set(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(200, json=_DELAY_RESPONSE) + ) + resp = markets.create_flight_disruption_market(**_DELAY_KWARGS) + body = json.loads(route.calls[0].request.content) + assert body == _DELAY_BODY + assert resp.cover == "delayed" + assert resp.delay_basis == "departure" + assert resp.delay_minutes == 120 + + @respx.mock + def test_request_model_form(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + req = CreateFlightDisruptionMarketRequest(**_CREATE_KWARGS) + resp = markets.create_flight_disruption_market(request=req) + assert json.loads(route.calls[0].request.content) == _CREATE_BODY + assert resp.created is True + + @respx.mock + def test_request_model_form_with_delay(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(200, json=_DELAY_RESPONSE) + ) + req = CreateFlightDisruptionMarketRequest(**_DELAY_KWARGS) + markets.create_flight_disruption_market(request=req) + assert json.loads(route.calls[0].request.content) == _DELAY_BODY + + def test_request_and_kwargs_exclusive(self, markets: MarketsResource) -> None: + req = CreateFlightDisruptionMarketRequest(**_CREATE_KWARGS) + with pytest.raises(TypeError, match="not both"): + markets.create_flight_disruption_market(request=req, cover="delayed") + + def test_missing_required_kwargs(self, markets: MarketsResource) -> None: + with pytest.raises(TypeError, match="create_flight_disruption_market"): + markets.create_flight_disruption_market() # type: ignore[call-overload] + + def test_extra_field_rejected_by_forbid(self) -> None: + with pytest.raises(ValidationError): + CreateFlightDisruptionMarketRequest( + **_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_flight_disruption_market(**_CREATE_KWARGS) + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response( + 400, + json={"error": {"code": "invalid_parameters"}}, + ) + ) + with pytest.raises(KalshiValidationError): + markets.create_flight_disruption_market(**_CREATE_KWARGS) + + @respx.mock + def test_404_not_found(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(404, json={"error": {"code": "not_found"}}) + ) + with pytest.raises(KalshiNotFoundError): + markets.create_flight_disruption_market(**_CREATE_KWARGS) + + @respx.mock + def test_409_flight_disruption_market_unavailable(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response( + 409, + json={"error": {"code": "flight_disruption_market_unavailable"}}, + ) + ) + with pytest.raises(KalshiConflictError): + markets.create_flight_disruption_market(**_CREATE_KWARGS) + + @respx.mock + def test_429_rate_limit(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response( + 429, + json={"error": {"code": "flight_disruption_market_limit_exceeded"}}, + ) + ) + with pytest.raises(KalshiRateLimitError): + markets.create_flight_disruption_market(**_CREATE_KWARGS) + + @respx.mock + def test_not_retried_on_503(self, retrying_markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(503, json={"error": {"code": "unavailable"}}) + ) + with pytest.raises(KalshiServerError): + retrying_markets.create_flight_disruption_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}/flight_disruption_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + resp = await async_markets.create_flight_disruption_market(**_CREATE_KWARGS) + assert route.calls[0].request.method == "POST" + body = json.loads(route.calls[0].request.content) + assert body == _CREATE_BODY + assert "delay_basis" not in body + assert resp.created is True + + @respx.mock + @pytest.mark.asyncio + async def test_async_delay_optionals_sent_when_set( + self, async_markets: AsyncMarketsResource + ) -> None: + route = respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(200, json=_DELAY_RESPONSE) + ) + await async_markets.create_flight_disruption_market(**_DELAY_KWARGS) + assert json.loads(route.calls[0].request.content) == _DELAY_BODY + + @respx.mock + @pytest.mark.asyncio + async def test_async_request_model_form(self, async_markets: AsyncMarketsResource) -> None: + route = respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + req = CreateFlightDisruptionMarketRequest(**_CREATE_KWARGS) + await async_markets.create_flight_disruption_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 = CreateFlightDisruptionMarketRequest(**_CREATE_KWARGS) + with pytest.raises(TypeError, match="not both"): + await async_markets.create_flight_disruption_market(request=req, cover="delayed") + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response( + 400, + json={"error": {"code": "invalid_parameters"}}, + ) + ) + with pytest.raises(KalshiValidationError): + await async_markets.create_flight_disruption_market(**_CREATE_KWARGS) + + @respx.mock + @pytest.mark.asyncio + async def test_async_404(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response(404, json={"error": {"code": "not_found"}}) + ) + with pytest.raises(KalshiNotFoundError): + await async_markets.create_flight_disruption_market(**_CREATE_KWARGS) + + @respx.mock + @pytest.mark.asyncio + async def test_async_409(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response( + 409, + json={"error": {"code": "flight_disruption_market_unavailable"}}, + ) + ) + with pytest.raises(KalshiConflictError): + await async_markets.create_flight_disruption_market(**_CREATE_KWARGS) + + @respx.mock + @pytest.mark.asyncio + async def test_async_429(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/flight_disruption_markets").mock( + return_value=httpx.Response( + 429, + json={"error": {"code": "flight_disruption_market_limit_exceeded"}}, + ) + ) + with pytest.raises(KalshiRateLimitError): + await async_markets.create_flight_disruption_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}/flight_disruption_markets").mock( + return_value=httpx.Response(503, json={"error": {"code": "unavailable"}}) + ) + with pytest.raises(KalshiServerError): + await retrying.create_flight_disruption_market(**_CREATE_KWARGS) + assert route.call_count == 1 + + +class TestFlightDisruptionAvailability: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + resp = markets.flight_disruption_availability() + assert route.calls[0].request.method == "GET" + assert str(route.calls[0].request.url) == f"{BASE}/flight_disruption_markets/availability" + assert resp.enabled is True + assert resp.covers == ["cancelled", "delayed", "either"] + assert resp.delay_bases == ["departure", "arrival"] + assert resp.delay_step_minutes == 30 + assert resp.max_delay_minutes == 360 + assert resp.max_days_ahead == 30 + assert resp.min_lead_minutes == 60 + assert resp.departure_countries == ["US"] + + @respx.mock + def test_empty_lists(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response( + 200, + json={ + "enabled": False, + "covers": [], + "delay_bases": [], + "delay_step_minutes": 30, + "max_delay_minutes": 360, + "max_days_ahead": 0, + "min_lead_minutes": 0, + "departure_countries": [], + }, + ) + ) + resp = markets.flight_disruption_availability() + assert resp.enabled is False + assert resp.covers == [] + assert resp.delay_bases == [] + assert resp.departure_countries == [] + + @respx.mock + def test_null_lists_coerced_to_empty(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response( + 200, + json={ + "enabled": True, + "covers": None, + "delay_bases": None, + "delay_step_minutes": 30, + "max_delay_minutes": 360, + "max_days_ahead": 30, + "min_lead_minutes": 60, + "departure_countries": None, + }, + ) + ) + resp = markets.flight_disruption_availability() + assert resp.covers == [] + assert resp.delay_bases == [] + assert resp.departure_countries == [] + + @respx.mock + def test_works_without_auth(self, unauth_markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + resp = unauth_markets.flight_disruption_availability() + assert resp.enabled is True + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + markets.flight_disruption_availability() + + @respx.mock + def test_429_rate_limit(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response(429, json={"error": {"code": "too_many_requests"}}) + ) + with pytest.raises(KalshiRateLimitError): + markets.flight_disruption_availability() + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> None: + route = respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + resp = await async_markets.flight_disruption_availability() + assert route.calls[0].request.method == "GET" + assert resp.enabled is True + assert resp.covers[0] == "cancelled" + + @respx.mock + @pytest.mark.asyncio + async def test_async_empty_lists(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response( + 200, + json={ + "enabled": False, + "covers": [], + "delay_bases": [], + "delay_step_minutes": 30, + "max_delay_minutes": 360, + "max_days_ahead": 0, + "min_lead_minutes": 0, + "departure_countries": [], + }, + ) + ) + resp = await async_markets.flight_disruption_availability() + assert resp.enabled is False + assert resp.covers == [] + assert resp.delay_bases == [] + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/availability").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + await async_markets.flight_disruption_availability() + + +class TestListFlights: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response(200, json=_FLIGHTS_RESPONSE) + ) + resp = markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") + assert route.calls[0].request.method == "GET" + params = dict(route.calls[0].request.url.params) + assert params == {"carrier": "AA", "flight_number": "100", "date": "2026-11-25"} + assert len(resp.flights) == 1 + flight = resp.flights[0] + assert flight.carrier == "AA" + assert flight.flight_number == "100" + assert flight.departure_airport == "JFK" + assert flight.arrival_airport == "LHR" + assert flight.scheduled_date == "2026-11-25" + assert flight.airline_name == "American Airlines" + assert flight.events[0].cover == "cancelled" + assert flight.events[0].series_ticker == "KXRFQFLIGHTC" + assert flight.events[0].market_ticker == "KXRFQFLIGHTC-AA100-JFKLHR-26NOV25-CXL" + assert flight.scheduled_departure is not None + assert flight.requested_carrier is None + + def test_missing_required_kwargs(self, markets: MarketsResource) -> None: + with pytest.raises(TypeError, match="list_flights"): + markets.list_flights() # type: ignore[call-arg] + + def test_requires_auth(self, unauth_markets: MarketsResource) -> None: + with pytest.raises(AuthRequiredError): + unauth_markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") + + @respx.mock + def test_null_lists_coerced_to_empty(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response( + 200, + json={ + "flights": [ + { + "carrier": "AA", + "flight_number": "100", + "departure_airport": "JFK", + "arrival_airport": "LHR", + "scheduled_date": "2026-11-25", + "events": None, + } + ] + }, + ) + ) + resp = markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") + assert resp.flights[0].events == [] + + @respx.mock + def test_null_flights_coerced_to_empty(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response(200, json={"flights": None}) + ) + resp = markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") + assert resp.flights == [] + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") + + @respx.mock + def test_404_not_found(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response(404, json={"error": {"code": "not_found"}}) + ) + with pytest.raises(KalshiNotFoundError): + markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") + + @respx.mock + def test_409_conflict(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response(409, json={"error": {"code": "conflict"}}) + ) + with pytest.raises(KalshiConflictError): + markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") + + @respx.mock + def test_429_rate_limit(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response( + 429, json={"error": {"code": "flight_lookup_limit_exceeded"}} + ) + ) + with pytest.raises(KalshiRateLimitError): + markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> None: + route = respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response(200, json=_FLIGHTS_RESPONSE) + ) + resp = await async_markets.list_flights( + carrier="AA", flight_number="100", date="2026-11-25" + ) + assert route.calls[0].request.method == "GET" + params = dict(route.calls[0].request.url.params) + assert params == {"carrier": "AA", "flight_number": "100", "date": "2026-11-25"} + assert resp.flights[0].departure_airport == "JFK" + + @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_flights(carrier="AA", flight_number="100", date="2026-11-25") + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/flight_disruption_markets/flights").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + await async_markets.list_flights(carrier="AA", flight_number="100", date="2026-11-25") diff --git a/tests/test_weather_point_markets.py b/tests/test_weather_point_markets.py index 211178e..d58b56a 100644 --- a/tests/test_weather_point_markets.py +++ b/tests/test_weather_point_markets.py @@ -117,6 +117,7 @@ def test_happy_path(self, markets: MarketsResource) -> None: assert body == _CREATE_BODY assert "floor_value" not in body assert "cap_value" not in body + assert "end_date" not in body assert body["latitude"] == 0.0 assert resp.event_ticker == "KXRFQ-E" assert resp.market_ticker == _CREATE_RESPONSE["market_ticker"] @@ -131,9 +132,32 @@ def test_request_model_form(self, markets: MarketsResource) -> None: ) req = CreateWeatherPointMarketRequest(**_CREATE_KWARGS) resp = markets.create_weather_point_market(request=req) - assert json.loads(route.calls[0].request.content) == _CREATE_BODY + body = json.loads(route.calls[0].request.content) + assert body == _CREATE_BODY + assert "end_date" not in body assert resp.created is True + @respx.mock + def test_end_date_sent_when_set(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + markets.create_weather_point_market(**_CREATE_KWARGS, end_date="2026-11-12") + body = json.loads(route.calls[0].request.content) + assert body["end_date"] == "2026-11-12" + for key, value in _CREATE_BODY.items(): + assert body[key] == value + + @respx.mock + def test_request_model_end_date(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + req = CreateWeatherPointMarketRequest(**_CREATE_KWARGS, end_date="2026-11-12") + markets.create_weather_point_market(request=req) + body = json.loads(route.calls[0].request.content) + assert body["end_date"] == "2026-11-12" + def test_request_and_kwargs_exclusive(self, markets: MarketsResource) -> None: req = CreateWeatherPointMarketRequest(**_CREATE_KWARGS) with pytest.raises(TypeError, match="not both"): @@ -196,9 +220,22 @@ async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> No body = json.loads(route.calls[0].request.content) assert body == _CREATE_BODY assert "floor_value" not in body + assert "end_date" not in body assert body["latitude"] == 0.0 assert resp.created is True + @respx.mock + @pytest.mark.asyncio + async def test_async_end_date_sent_when_set( + self, async_markets: AsyncMarketsResource + ) -> None: + route = respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + await async_markets.create_weather_point_market(**_CREATE_KWARGS, end_date="2026-11-12") + body = json.loads(route.calls[0].request.content) + assert body["end_date"] == "2026-11-12" + @respx.mock @pytest.mark.asyncio async def test_async_request_model_form(self, async_markets: AsyncMarketsResource) -> None: @@ -279,6 +316,19 @@ def test_happy_path(self, markets: MarketsResource) -> None: assert resp.domains[0].north == 49.0 assert resp.variables[0].variable == "precip_hours" assert resp.variables[0].domains == ["conus"] + assert resp.max_window_days is None + assert resp.max_window_hours is None + + @respx.mock + def test_window_fields_set(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response( + 200, json={**_AVAIL_RESPONSE, "max_window_days": 2, "max_window_hours": 24} + ) + ) + resp = markets.weather_point_availability() + assert resp.max_window_days == 2 + assert resp.max_window_hours == 24 @respx.mock def test_empty_lists(self, markets: MarketsResource) -> None: @@ -326,6 +376,20 @@ async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> No assert route.calls[0].request.method == "GET" assert resp.enabled is True assert resp.domains[0].name == "conus" + assert resp.max_window_days is None + assert resp.max_window_hours is None + + @respx.mock + @pytest.mark.asyncio + async def test_async_window_fields_set(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response( + 200, json={**_AVAIL_RESPONSE, "max_window_days": 2, "max_window_hours": 24} + ) + ) + resp = await async_markets.weather_point_availability() + assert resp.max_window_days == 2 + assert resp.max_window_hours == 24 @respx.mock @pytest.mark.asyncio