From 65657da7c9acf8201e9fab7ba43d1bf235b4d072 Mon Sep 17 00:00:00 2001 From: Jeff West Date: Wed, 11 Nov 2026 09:17:11 -0600 Subject: [PATCH 1/2] chore(spec): sync core + perps_scm specs (#578) --- specs/openapi.yaml | 296 +++++++++++++++++++++++++++++++++++ specs/perps_scm_openapi.yaml | 6 +- 2 files changed, 298 insertions(+), 4 deletions(-) diff --git a/specs/openapi.yaml b/specs/openapi.yaml index 9b8e2d4..519bd50 100644 --- a/specs/openapi.yaml +++ b/specs/openapi.yaml @@ -4184,6 +4184,104 @@ paths: description: Internal Server Error # Communications endpoints + /weather_point_markets: + post: + operationId: CreateWeatherPointMarket + summary: Create Weather Point Market + description: | + Returns the on-request weather market for a location, time window and + threshold, creating it if it doesn't exist yet. The same request always + returns the same market, so call this before sending an RFQ for a + market you haven't seen. `created` tells you whether the market is new. + An existing market is returned until its window ends, even where new + markets like it are no longer offered. The exception is when weather + markets are switched off (`enabled` is false in the availability + response) or the variable has been withdrawn entirely: the request is + then refused whether or not the market exists. + + 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. + + 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, 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. | + | 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: + - markets + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateWeatherPointMarketRequest' + responses: + '200': + description: Market returned or created successfully + content: + application/json: + schema: + $ref: '#/components/schemas/CreateWeatherPointMarketResponse' + '400': + $ref: '#/components/responses/BadRequestError' + '401': + $ref: '#/components/responses/UnauthorizedError' + '403': + $ref: '#/components/responses/ForbiddenError' + '409': + $ref: '#/components/responses/ConflictError' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + + /weather_point_markets/availability: + get: + operationId: GetWeatherPointAvailability + summary: Get Weather Point Market Availability + description: | + 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. + + A location inside an offered domain can still be refused at creation + when it is over open water. + tags: + - markets + responses: + '200': + description: Availability retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetWeatherPointAvailabilityResponse' + '429': + $ref: '#/components/responses/RateLimitError' + '500': + $ref: '#/components/responses/InternalServerError' + /multivariate_event_collections/{collection_ticker}: get: operationId: GetMultivariateEventCollection @@ -10860,6 +10958,204 @@ components: market: $ref: '#/components/schemas/Market' description: Market payload of the created market. + WeatherPointVariable: + type: string + enum: + - precip_hours + - precip_total + - max_temp + - min_temp + description: | + What a weather point market measures over its window, and the unit + and allowed range of its thresholds: + - `precip_hours`: number of whole hours with at least 0.01 inch of + precipitation. Whole hours, 0 to the length of the window. + - `precip_total`: total precipitation. Hundredths of an inch, 0 to + 2000 (so 25 is 0.25 inch). + - `max_temp`: highest temperature. Whole °F, -80 to 140. + - `min_temp`: lowest temperature. Whole °F, -80 to 140. + + CreateWeatherPointMarketRequest: + type: object + required: + - latitude + - longitude + - variable + - strike_type + - date + - start_hour + - end_hour + - timezone + properties: + latitude: + type: number + format: double + description: Latitude of the location in degrees. + example: 40.785 + # A pointer, so that 0 is told apart from a missing field. + x-go-type: '*float64' + x-oapi-codegen-extra-tags: + validate: required,gte=-90,lte=90 + longitude: + type: number + format: double + description: Longitude of the location in degrees. + example: -73.965 + x-go-type: '*float64' + x-oapi-codegen-extra-tags: + validate: required,gte=-180,lte=180 + variable: + $ref: '#/components/schemas/WeatherPointVariable' + strike_type: + type: string + enum: + - greater + - less + - between + # Named so the generated constants don't collide with Market's + # strike_type values. + x-enum-varnames: + - WeatherPointStrikeGreater + - WeatherPointStrikeLess + - WeatherPointStrikeBetween + description: | + How the measured value is compared to the thresholds: + `greater` settles Yes strictly above `floor_value`, `less` + strictly below `cap_value`, and `between` from `floor_value` to + `cap_value` inclusive. + x-oapi-codegen-extra-tags: + validate: required,oneof=greater less between + floor_value: + type: integer + format: int32 + description: Lower threshold, in the variable's unit. Required for `greater` and `between`, and must be left out for `less`. For `precip_hours` with `greater` it must be below the number of hours in the window. + cap_value: + type: integer + format: int32 + description: Upper threshold, in the variable's unit. Required for `less` and `between`, and must be left out for `greater`. For the precipitation variables with `less` it must be above 0. For `between` it must not be below `floor_value`. + date: + type: string + description: Local calendar date the window starts on, as YYYY-MM-DD in `timezone`. + example: '2026-11-11' + x-oapi-codegen-extra-tags: + validate: required,datetime=2006-01-02 + start_hour: + type: integer + format: int32 + minimum: 0 + maximum: 23 + description: First local hour of the window (0-23). + x-go-type: '*int32' + x-oapi-codegen-extra-tags: + validate: required,gte=0,lte=23 + end_hour: + type: integer + 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. + x-go-type: '*int32' + x-oapi-codegen-extra-tags: + validate: required,gte=1,lte=24,gtfield=StartHour + 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. + example: America/New_York + x-oapi-codegen-extra-tags: + validate: required + + CreateWeatherPointMarketResponse: + type: object + required: + - event_ticker + - market_ticker + - created + - latitude + - longitude + properties: + event_ticker: + type: string + description: Event ticker of the market. + market_ticker: + type: string + description: Market ticker of the market. + example: KXRFQRAINHOURS-40785N73965W-26NOV1105Z-24H-G2 + created: + type: boolean + description: False when a market for the same request already existed. + 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. + 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. + + WeatherPointDomain: + type: object + required: + - name + - north + - south + - west + - east + properties: + name: + type: string + description: Domain name, such as `conus`. + north: + type: number + format: double + description: Northernmost grid cell center, in degrees latitude. + south: + type: number + format: double + description: Southernmost grid cell center, in degrees latitude. + west: + type: number + format: double + description: Westernmost grid cell center, in degrees longitude. + east: + type: number + format: double + description: Easternmost grid cell center, in degrees longitude. + + WeatherPointVariableAvailability: + type: object + required: + - variable + - domains + properties: + variable: + $ref: '#/components/schemas/WeatherPointVariable' + domains: + type: array + items: + type: string + description: Names of the domains new markets of this variable may be created in. + + GetWeatherPointAvailabilityResponse: + type: object + required: + - enabled + - domains + - variables + properties: + enabled: + type: boolean + description: Whether weather point markets can be created at all. + domains: + type: array + items: + $ref: '#/components/schemas/WeatherPointDomain' + description: The NOAA MRMS domains a location may lie in. + variables: + type: array + items: + $ref: '#/components/schemas/WeatherPointVariableAvailability' + description: The variables on offer and where. A variable left out can't be created. + # Market Orderbook schemas PriceLevelDollarsCountFp: type: array diff --git a/specs/perps_scm_openapi.yaml b/specs/perps_scm_openapi.yaml index 79f57bd..7fe8c65 100644 --- a/specs/perps_scm_openapi.yaml +++ b/specs/perps_scm_openapi.yaml @@ -233,10 +233,8 @@ paths: 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). + [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). 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." } From 1c4326b210fe9730163937be7d5bce949511ba78 Mon Sep 17 00:00:00 2001 From: Jeff West Date: Wed, 11 Nov 2026 09:58:42 -0600 Subject: [PATCH 2/2] =?UTF-8?q?feat(markets):=20weather=20point=20markets?= =?UTF-8?q?=20create=20+=20availability=20(#578)=20=E2=80=94=2022.12.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 25 ++ CLAUDE.md | 2 +- README.md | 2 +- docs/index.md | 4 +- docs/resources/markets.md | 31 +++ kalshi/__init__.py | 14 +- kalshi/_contract_map.py | 20 ++ kalshi/models/__init__.py | 12 + kalshi/models/markets.py | 70 ++++++ kalshi/resources/markets.py | 198 +++++++++++++++- pyproject.toml | 2 +- tests/_contract_support.py | 11 + tests/test_contracts.py | 3 + tests/test_weather_point_markets.py | 350 ++++++++++++++++++++++++++++ 14 files changed, 737 insertions(+), 7 deletions(-) create mode 100644 tests/test_weather_point_markets.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bcc2e49..92c7af8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ All notable changes to kalshi-sdk will be documented in this file. +## 22.12.0 — 2026-11-11 + +Adds on-request weather point markets (#578) against OpenAPI v3.36.0. +Additive only. No breaking changes. + +### Added + +- **`markets.create_weather_point_market(...)`** (sync and async) — + `POST /weather_point_markets`, 200 `CreateWeatherPointMarketResponse`. + Authenticated. Returns the 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. Required: `latitude`, + `longitude`, `variable` (`WeatherPointVariableLiteral`: `"precip_hours"` / + `"precip_total"` / `"max_temp"` / `"min_temp"`), `strike_type` + (`"greater"` / `"less"` / `"between"`), `date` (YYYY-MM-DD), `start_hour`, + `end_hour`, `timezone` (IANA). Optional: `floor_value`, `cap_value`. + Accepts `request=CreateWeatherPointMarketRequest(...)` or keyword fields. + POST is never retried. (Closes #578). +- **`markets.weather_point_availability()`** (sync and async) — + `GET /weather_point_markets/availability`, 200 + `GetWeatherPointAvailabilityResponse` (`enabled`, `domains` as + `WeatherPointDomain`, `variables` as `WeatherPointVariableAvailability`). + Public. Whether creation is on, the NOAA MRMS domains a location may lie + in, and which variables are offered in which domains. + ## 22.11.0 — 2026-11-10 Reconciles nightly spec drift (#575) against the latest AsyncAPI (new diff --git a/CLAUDE.md b/CLAUDE.md index 0315165..13e7e90 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -122,7 +122,7 @@ tests/ ## API Reference -- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.35.0, 133 operations; 132 mapped in the core SDK — `POST /portfolio/intra_exchange_instance_transfer` is implemented on `PerpsClient.transfers.transfer_instance` and left unimplemented on the core client) +- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.36.0, 137 operations; 136 mapped in the core SDK — `POST /portfolio/intra_exchange_instance_transfer` is implemented on `PerpsClient.transfers.transfer_instance` and left unimplemented on the core client) - 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 9f58f25..575215c 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 (132 mapped of 133 operations across 19 resources, OpenAPI v3.35.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch). +- **Full coverage** of the Kalshi REST API (136 mapped of 137 operations across 19 resources, OpenAPI v3.36.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch). - **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 a2378f0..66a7a1b 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** — 132 mapped of 133 operations across 19 resources - (OpenAPI v3.35.0), every kwarg drift-tested against the spec. +- **Full REST coverage** — 136 mapped of 137 operations across 19 resources + (OpenAPI v3.36.0), every kwarg drift-tested against the spec. - **V2 event-market orders** — new `create_v2` / `amend_v2` / `decrease_v2` / `cancel_v2` / `cancel_all_v2` family on `/portfolio/events/orders/*`. Legacy `/portfolio/orders` keeps working; deprecation no earlier than May 6, 2026. diff --git a/docs/resources/markets.md b/docs/resources/markets.md index a9381df..bc8018a 100644 --- a/docs/resources/markets.md +++ b/docs/resources/markets.md @@ -17,6 +17,8 @@ recent trades. | `bulk_orderbooks(*, tickers)` | `GET /markets/orderbooks` | **yes** | | `list_trades(...)` | `GET /markets/trades` | no | | `list_all_trades(...)` | walks `list_trades` | no | +| `create_weather_point_market(...)` | `POST /weather_point_markets` | **yes** | +| `weather_point_availability()` | `GET /weather_point_markets/availability` | no | !!! warning "Orderbook endpoints require auth" `orderbook()` and `bulk_orderbooks()` raise `AuthRequiredError` on an @@ -142,6 +144,35 @@ block trade. Omit it to return all trades. Each `Trade` also carries an [issue-349]: https://github.com/TexasCoding/kalshi-python-sdk/issues/349 +## Weather point markets + +On-request weather markets for a location, time window, and threshold. +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]) + +resp = client.markets.create_weather_point_market( + latitude=40.785, + longitude=-73.965, + variable="precip_hours", # WeatherPointVariableLiteral + strike_type="greater", # "greater" / "less" / "between" + date="2026-11-11", # YYYY-MM-DD in timezone + start_hour=0, + end_hour=24, + timezone="America/New_York", + floor_value=2, +) +print(resp.market_ticker, resp.created, resp.latitude, resp.longitude) +``` + +`floor_value` is required by the server for `"greater"` and `"between"`; +`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. + ## Reference ::: kalshi.resources.markets.MarketsResource diff --git a/kalshi/__init__.py b/kalshi/__init__.py index 630d50d..16c76cb 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -81,6 +81,8 @@ CreateRFQResponse, CreateSubaccountRequest, CreateSubaccountResponse, + CreateWeatherPointMarketRequest, + CreateWeatherPointMarketResponse, CreditHistory, CreditStatusLiteral, DailySchedule, @@ -143,6 +145,7 @@ GetTargetBalanceAllocationResponse, GetWeatherIndexCalibrationsResponse, GetWeatherIndexResponse, + GetWeatherPointAvailabilityResponse, HistoricalCutoff, IncentiveProgram, IncentiveProgramStatusLiteral, @@ -226,6 +229,9 @@ WeatherIndexCalibrationStation, WeatherIndexPoint, WeatherIndexStationReading, + WeatherPointDomain, + WeatherPointVariableAvailability, + WeatherPointVariableLiteral, WeeklySchedule, Withdrawal, ) @@ -318,6 +324,8 @@ "CreateRFQResponse", "CreateSubaccountRequest", "CreateSubaccountResponse", + "CreateWeatherPointMarketRequest", + "CreateWeatherPointMarketResponse", "CreditHistory", "CreditStatusLiteral", "DailySchedule", @@ -384,6 +392,7 @@ "GetTargetBalanceAllocationResponse", "GetWeatherIndexCalibrationsResponse", "GetWeatherIndexResponse", + "GetWeatherPointAvailabilityResponse", "HistoricalCutoff", "IncentiveProgram", "IncentiveProgramStatusLiteral", @@ -499,8 +508,11 @@ "WeatherIndexCalibrationStation", "WeatherIndexPoint", "WeatherIndexStationReading", + "WeatherPointDomain", + "WeatherPointVariableAvailability", + "WeatherPointVariableLiteral", "WeeklySchedule", "Withdrawal", ] -__version__ = "22.11.0" +__version__ = "22.12.0" diff --git a/kalshi/_contract_map.py b/kalshi/_contract_map.py index 9bb8213..2da6b78 100644 --- a/kalshi/_contract_map.py +++ b/kalshi/_contract_map.py @@ -487,6 +487,26 @@ class ContractEntry: sdk_model="kalshi.models.markets.GetMarketOrderbooksResponse", spec_schema="GetMarketOrderbooksResponse", ), + ContractEntry( + sdk_model="kalshi.models.markets.CreateWeatherPointMarketRequest", + spec_schema="CreateWeatherPointMarketRequest", + ), + ContractEntry( + sdk_model="kalshi.models.markets.CreateWeatherPointMarketResponse", + spec_schema="CreateWeatherPointMarketResponse", + ), + ContractEntry( + sdk_model="kalshi.models.markets.WeatherPointDomain", + spec_schema="WeatherPointDomain", + ), + ContractEntry( + sdk_model="kalshi.models.markets.WeatherPointVariableAvailability", + spec_schema="WeatherPointVariableAvailability", + ), + ContractEntry( + sdk_model="kalshi.models.markets.GetWeatherPointAvailabilityResponse", + spec_schema="GetWeatherPointAvailabilityResponse", + ), # -- orders V2 family (#171) ----------------------------------------- ContractEntry( sdk_model="kalshi.models.orders.CreateOrderV2Request", diff --git a/kalshi/models/__init__.py b/kalshi/models/__init__.py index b809dbd..16b29f3 100644 --- a/kalshi/models/__init__.py +++ b/kalshi/models/__init__.py @@ -121,6 +121,9 @@ from kalshi.models.markets import ( BidAskDistribution, Candlestick, + CreateWeatherPointMarketRequest, + CreateWeatherPointMarketResponse, + GetWeatherPointAvailabilityResponse, Market, MarketCandlesticks, MarketStatusLiteral, @@ -128,6 +131,9 @@ Orderbook, OrderbookLevel, PriceDistribution, + WeatherPointDomain, + WeatherPointVariableAvailability, + WeatherPointVariableLiteral, ) from kalshi.models.milestones import ( GetMilestoneResponse, @@ -295,6 +301,8 @@ "CreateRFQResponse", "CreateSubaccountRequest", "CreateSubaccountResponse", + "CreateWeatherPointMarketRequest", + "CreateWeatherPointMarketResponse", "CreditHistory", "CreditStatusLiteral", "DailySchedule", @@ -357,6 +365,7 @@ "GetTargetBalanceAllocationResponse", "GetWeatherIndexCalibrationsResponse", "GetWeatherIndexResponse", + "GetWeatherPointAvailabilityResponse", "HistoricalCutoff", "IncentiveProgram", "IncentiveProgramStatusLiteral", @@ -440,6 +449,9 @@ "WeatherIndexCalibrationStation", "WeatherIndexPoint", "WeatherIndexStationReading", + "WeatherPointDomain", + "WeatherPointVariableAvailability", + "WeatherPointVariableLiteral", "WeeklySchedule", "Withdrawal", ] diff --git a/kalshi/models/markets.py b/kalshi/models/markets.py index 7029507..706a4be 100644 --- a/kalshi/models/markets.py +++ b/kalshi/models/markets.py @@ -310,3 +310,73 @@ class GetMarketOrderbooksResponse(BaseModel): orderbooks: NullableList[dict[str, Any]] model_config = {"extra": "allow"} + + +WeatherPointVariableLiteral = Literal["precip_hours", "precip_total", "max_temp", "min_temp"] +"""What a weather point market measures. Spec: WeatherPointVariable enum.""" + + +class CreateWeatherPointMarketRequest(BaseModel): + """Body for POST /weather_point_markets. + + Matches spec ``components.schemas.CreateWeatherPointMarketRequest``. + Required: ``latitude``, ``longitude``, ``variable``, ``strike_type``, + ``date``, ``start_hour``, ``end_hour``, ``timezone``. Optional: + ``floor_value``, ``cap_value``. + """ + + latitude: float + longitude: float + variable: WeatherPointVariableLiteral + strike_type: Literal["greater", "less", "between"] + date: str + start_hour: int + end_hour: int + timezone: str + floor_value: int | None = None + cap_value: int | None = None + + model_config = {"extra": "forbid"} + + +class CreateWeatherPointMarketResponse(BaseModel): + """Response from POST /weather_point_markets.""" + + event_ticker: str + market_ticker: str + created: bool + latitude: float + longitude: float + + model_config = {"extra": "allow"} + + +class WeatherPointDomain(BaseModel): + """A NOAA MRMS domain a weather-point location may lie in.""" + + name: str + north: float + south: float + west: float + east: float + + model_config = {"extra": "allow"} + + +class WeatherPointVariableAvailability(BaseModel): + """Where new markets of one weather-point variable may be created.""" + + variable: WeatherPointVariableLiteral + domains: NullableList[str] + + model_config = {"extra": "allow"} + + +class GetWeatherPointAvailabilityResponse(BaseModel): + """Response from GET /weather_point_markets/availability.""" + + enabled: bool + domains: NullableList[WeatherPointDomain] + variables: NullableList[WeatherPointVariableAvailability] + + model_config = {"extra": "allow"} diff --git a/kalshi/resources/markets.py b/kalshi/resources/markets.py index 3872dc9..0c005e6 100644 --- a/kalshi/resources/markets.py +++ b/kalshi/resources/markets.py @@ -4,7 +4,7 @@ import builtins from collections.abc import AsyncIterator, Iterator -from typing import Any +from typing import Any, Literal, overload from typing_extensions import deprecated @@ -14,19 +14,24 @@ from kalshi.models.markets import ( BatchGetMarketCandlesticksResponse, Candlestick, + CreateWeatherPointMarketRequest, + CreateWeatherPointMarketResponse, GetMarketCandlesticksResponse, GetMarketOrderbooksResponse, + GetWeatherPointAvailabilityResponse, Market, MarketCandlesticks, MarketStatusLiteral, MveFilterLiteral, Orderbook, OrderbookLevel, + WeatherPointVariableLiteral, ) from kalshi.resources._base import ( AsyncResource, SyncResource, _bool_param, + _check_request_exclusive, _join_tickers, _params, _seg, @@ -218,6 +223,64 @@ def _orderbook_from_item(item: dict[str, Any]) -> Orderbook: return Orderbook(ticker=ticker, yes=yes_levels, no=no_levels) +def _build_create_weather_point_market_body( + request: CreateWeatherPointMarketRequest | None, + *, + latitude: float | None, + longitude: float | None, + variable: WeatherPointVariableLiteral | None, + strike_type: Literal["greater", "less", "between"] | None, + date: str | None, + start_hour: int | None, + end_hour: int | None, + timezone: str | None, + floor_value: int | None, + cap_value: int | None, +) -> dict[str, Any]: + _check_request_exclusive( + request, + latitude=latitude, + longitude=longitude, + variable=variable, + strike_type=strike_type, + date=date, + start_hour=start_hour, + end_hour=end_hour, + timezone=timezone, + floor_value=floor_value, + cap_value=cap_value, + ) + if request is None: + if ( + latitude is None + or longitude is None + or variable is None + or strike_type is None + or date is None + or start_hour is None + or end_hour is None + or timezone is None + ): + raise TypeError( + "create_weather_point_market() requires `latitude`, `longitude`, " + "`variable`, `strike_type`, `date`, `start_hour`, `end_hour`, " + "and `timezone` (or pass `request=...`)" + ) + request = CreateWeatherPointMarketRequest( + latitude=latitude, + longitude=longitude, + variable=variable, + strike_type=strike_type, + date=date, + start_hour=start_hour, + end_hour=end_hour, + timezone=timezone, + floor_value=floor_value, + cap_value=cap_value, + ) + return request.model_dump(exclude_none=True, by_alias=True, mode="json") + + class MarketsResource(SyncResource): """Sync markets API.""" @@ -467,6 +530,75 @@ def bulk_orderbooks( raw = GetMarketOrderbooksResponse.model_validate(data).orderbooks return [_orderbook_from_item(item) for item in raw] + @overload + def create_weather_point_market( + self, + *, + request: CreateWeatherPointMarketRequest, + extra_headers: dict[str, str] | None = None, + ) -> CreateWeatherPointMarketResponse: ... + @overload + def create_weather_point_market( + self, + *, + latitude: float, + longitude: float, + variable: WeatherPointVariableLiteral, + strike_type: Literal["greater", "less", "between"], + date: str, + start_hour: int, + end_hour: int, + timezone: str, + floor_value: int | None = ..., + cap_value: int | None = ..., + extra_headers: dict[str, str] | None = None, + ) -> CreateWeatherPointMarketResponse: ... + def create_weather_point_market( + self, + *, + request: CreateWeatherPointMarketRequest | None = None, + latitude: float | None = None, + longitude: float | None = None, + variable: WeatherPointVariableLiteral | None = None, + strike_type: Literal["greater", "less", "between"] | None = None, + date: str | None = None, + start_hour: int | None = None, + end_hour: int | None = None, + timezone: str | None = None, + floor_value: int | None = None, + cap_value: int | None = None, + extra_headers: dict[str, str] | None = None, + ) -> CreateWeatherPointMarketResponse: + """``POST /weather_point_markets``. Not retried. + + 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. + """ + self._require_auth() + body = _build_create_weather_point_market_body( + request, + latitude=latitude, + longitude=longitude, + variable=variable, + strike_type=strike_type, + date=date, + start_hour=start_hour, + end_hour=end_hour, + timezone=timezone, + floor_value=floor_value, + cap_value=cap_value, + ) + data = self._post("/weather_point_markets", json=body, extra_headers=extra_headers) + return CreateWeatherPointMarketResponse.model_validate(data) + + def weather_point_availability( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetWeatherPointAvailabilityResponse: + """``GET /weather_point_markets/availability``. Public.""" + data = self._get("/weather_point_markets/availability", extra_headers=extra_headers) + return GetWeatherPointAvailabilityResponse.model_validate(data) + class AsyncMarketsResource(AsyncResource): """Async markets API.""" @@ -722,3 +854,67 @@ async def bulk_orderbooks( data = await self._get("/markets/orderbooks", params=params, extra_headers=extra_headers) raw = GetMarketOrderbooksResponse.model_validate(data).orderbooks return [_orderbook_from_item(item) for item in raw] + + @overload + async def create_weather_point_market( + self, + *, + request: CreateWeatherPointMarketRequest, + extra_headers: dict[str, str] | None = None, + ) -> CreateWeatherPointMarketResponse: ... + @overload + async def create_weather_point_market( + self, + *, + latitude: float, + longitude: float, + variable: WeatherPointVariableLiteral, + strike_type: Literal["greater", "less", "between"], + date: str, + start_hour: int, + end_hour: int, + timezone: str, + floor_value: int | None = ..., + cap_value: int | None = ..., + extra_headers: dict[str, str] | None = None, + ) -> CreateWeatherPointMarketResponse: ... + async def create_weather_point_market( + self, + *, + request: CreateWeatherPointMarketRequest | None = None, + latitude: float | None = None, + longitude: float | None = None, + variable: WeatherPointVariableLiteral | None = None, + strike_type: Literal["greater", "less", "between"] | None = None, + date: str | None = None, + start_hour: int | None = None, + end_hour: int | None = None, + timezone: str | None = None, + floor_value: int | None = None, + cap_value: int | None = None, + extra_headers: dict[str, str] | None = None, + ) -> CreateWeatherPointMarketResponse: + """Async :meth:`MarketsResource.create_weather_point_market`.""" + self._require_auth() + body = _build_create_weather_point_market_body( + request, + latitude=latitude, + longitude=longitude, + variable=variable, + strike_type=strike_type, + date=date, + start_hour=start_hour, + end_hour=end_hour, + timezone=timezone, + floor_value=floor_value, + cap_value=cap_value, + ) + data = await self._post("/weather_point_markets", json=body, extra_headers=extra_headers) + return CreateWeatherPointMarketResponse.model_validate(data) + + async def weather_point_availability( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetWeatherPointAvailabilityResponse: + """Async :meth:`MarketsResource.weather_point_availability`.""" + data = await self._get("/weather_point_markets/availability", extra_headers=extra_headers) + return GetWeatherPointAvailabilityResponse.model_validate(data) diff --git a/pyproject.toml b/pyproject.toml index 96dbaf0..397b20d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "22.11.0" +version = "22.12.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 f20db80..2451a82 100644 --- a/tests/_contract_support.py +++ b/tests/_contract_support.py @@ -151,6 +151,17 @@ class Exclusion: http_method="GET", path_template="/markets/orderbooks", ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.create_weather_point_market", + http_method="POST", + path_template="/weather_point_markets", + request_body_schema="#/components/schemas/CreateWeatherPointMarketRequest", + ), + MethodEndpointEntry( + sdk_method="kalshi.resources.markets.MarketsResource.weather_point_availability", + http_method="GET", + path_template="/weather_point_markets/availability", + ), # ── account ───────────────────────────────────────────────────────────── MethodEndpointEntry( sdk_method="kalshi.resources.account.AccountResource.limits", diff --git a/tests/test_contracts.py b/tests/test_contracts.py index 6effa99..f6ccb72 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -1457,6 +1457,9 @@ def _assert_params_match( "#/components/schemas/CreateMarketInMultivariateEventCollectionRequest": ( "kalshi.models.multivariate.CreateMarketInMultivariateEventCollectionRequest" ), + "#/components/schemas/CreateWeatherPointMarketRequest": ( + "kalshi.models.markets.CreateWeatherPointMarketRequest" + ), "#/components/schemas/CreateOrderGroupRequest": ( "kalshi.models.order_groups.CreateOrderGroupRequest" ), diff --git a/tests/test_weather_point_markets.py b/tests/test_weather_point_markets.py new file mode 100644 index 0000000..211178e --- /dev/null +++ b/tests/test_weather_point_markets.py @@ -0,0 +1,350 @@ +"""Tests for weather point market endpoints on MarketsResource (#578).""" + +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, + KalshiServerError, + KalshiValidationError, +) +from kalshi.models.markets import CreateWeatherPointMarketRequest +from kalshi.resources.markets import AsyncMarketsResource, MarketsResource + +BASE = "https://test.kalshi.com/trade-api/v2" + +_CREATE_KWARGS: dict[str, object] = { + "latitude": 0.0, + "longitude": -73.965, + "variable": "precip_hours", + "strike_type": "greater", + "date": "2026-11-11", + "start_hour": 0, + "end_hour": 24, + "timezone": "America/New_York", +} + +_CREATE_BODY = { + "latitude": 0.0, + "longitude": -73.965, + "variable": "precip_hours", + "strike_type": "greater", + "date": "2026-11-11", + "start_hour": 0, + "end_hour": 24, + "timezone": "America/New_York", +} + +_CREATE_RESPONSE = { + "event_ticker": "KXRFQ-E", + "market_ticker": "KXRFQRAINHOURS-00000N73965W-26NOV1100Z-24H-G2", + "created": True, + "latitude": 0.0, + "longitude": -73.965, +} + +_AVAIL_RESPONSE = { + "enabled": True, + "domains": [ + {"name": "conus", "north": 49.0, "south": 24.0, "west": -125.0, "east": -66.0}, + ], + "variables": [ + {"variable": "precip_hours", "domains": ["conus"]}, + ], +} + + +@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 TestCreateWeatherPointMarket: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + resp = markets.create_weather_point_market(**_CREATE_KWARGS) + assert route.calls[0].request.method == "POST" + assert str(route.calls[0].request.url) == f"{BASE}/weather_point_markets" + body = json.loads(route.calls[0].request.content) + assert body == _CREATE_BODY + assert "floor_value" not in body + assert "cap_value" not in body + assert body["latitude"] == 0.0 + assert resp.event_ticker == "KXRFQ-E" + assert resp.market_ticker == _CREATE_RESPONSE["market_ticker"] + assert resp.created is True + assert resp.latitude == 0.0 + assert resp.longitude == -73.965 + + @respx.mock + def test_request_model_form(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) + resp = markets.create_weather_point_market(request=req) + assert json.loads(route.calls[0].request.content) == _CREATE_BODY + assert resp.created is True + + def test_request_and_kwargs_exclusive(self, markets: MarketsResource) -> None: + req = CreateWeatherPointMarketRequest(**_CREATE_KWARGS) + with pytest.raises(TypeError, match="not both"): + markets.create_weather_point_market(request=req, latitude=40.785) + + def test_missing_required_kwargs(self, markets: MarketsResource) -> None: + with pytest.raises(TypeError, match="create_weather_point_market"): + markets.create_weather_point_market() # type: ignore[call-overload] + + def test_extra_field_rejected_by_forbid(self) -> None: + with pytest.raises(ValidationError): + CreateWeatherPointMarketRequest( + **_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_weather_point_market(**_CREATE_KWARGS) + + @respx.mock + def test_409_weather_point_market_unavailable(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response( + 409, + json={"error": {"code": "weather_point_market_unavailable"}}, + ) + ) + with pytest.raises(KalshiConflictError): + markets.create_weather_point_market(**_CREATE_KWARGS) + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response( + 400, + json={"error": {"code": "invalid_parameters"}}, + ) + ) + with pytest.raises(KalshiValidationError): + markets.create_weather_point_market(**_CREATE_KWARGS) + + @respx.mock + def test_not_retried_on_503(self, retrying_markets: MarketsResource) -> None: + route = respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response(503, json={"error": {"code": "unavailable"}}) + ) + with pytest.raises(KalshiServerError): + retrying_markets.create_weather_point_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}/weather_point_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + resp = await async_markets.create_weather_point_market(**_CREATE_KWARGS) + assert route.calls[0].request.method == "POST" + body = json.loads(route.calls[0].request.content) + assert body == _CREATE_BODY + assert "floor_value" not in body + assert body["latitude"] == 0.0 + assert resp.created is True + + @respx.mock + @pytest.mark.asyncio + async def test_async_request_model_form(self, async_markets: AsyncMarketsResource) -> None: + route = respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response(200, json=_CREATE_RESPONSE) + ) + req = CreateWeatherPointMarketRequest(**_CREATE_KWARGS) + await async_markets.create_weather_point_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 = CreateWeatherPointMarketRequest(**_CREATE_KWARGS) + with pytest.raises(TypeError, match="not both"): + await async_markets.create_weather_point_market(request=req, latitude=40.785) + + @respx.mock + @pytest.mark.asyncio + async def test_async_409(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response( + 409, + json={"error": {"code": "weather_point_market_unavailable"}}, + ) + ) + with pytest.raises(KalshiConflictError): + await async_markets.create_weather_point_market(**_CREATE_KWARGS) + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.post(f"{BASE}/weather_point_markets").mock( + return_value=httpx.Response( + 400, + json={"error": {"code": "invalid_parameters"}}, + ) + ) + with pytest.raises(KalshiValidationError): + await async_markets.create_weather_point_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}/weather_point_markets").mock( + return_value=httpx.Response(503, json={"error": {"code": "unavailable"}}) + ) + with pytest.raises(KalshiServerError): + await retrying.create_weather_point_market(**_CREATE_KWARGS) + assert route.call_count == 1 + + +class TestWeatherPointAvailability: + @respx.mock + def test_happy_path(self, markets: MarketsResource) -> None: + route = respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + resp = markets.weather_point_availability() + assert route.calls[0].request.method == "GET" + assert str(route.calls[0].request.url) == f"{BASE}/weather_point_markets/availability" + assert resp.enabled is True + assert len(resp.domains) == 1 + assert resp.domains[0].name == "conus" + assert resp.domains[0].north == 49.0 + assert resp.variables[0].variable == "precip_hours" + assert resp.variables[0].domains == ["conus"] + + @respx.mock + def test_empty_lists(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response( + 200, json={"enabled": False, "domains": [], "variables": []} + ) + ) + resp = markets.weather_point_availability() + assert resp.enabled is False + assert resp.domains == [] + assert resp.variables == [] + + @respx.mock + def test_null_lists_coerced_to_empty(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response( + 200, + json={ + "enabled": True, + "domains": None, + "variables": [{"variable": "max_temp", "domains": None}], + }, + ) + ) + resp = markets.weather_point_availability() + assert resp.domains == [] + assert resp.variables[0].domains == [] + + @respx.mock + def test_400_validation_error(self, markets: MarketsResource) -> None: + respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + markets.weather_point_availability() + + @respx.mock + @pytest.mark.asyncio + async def test_async_happy_path(self, async_markets: AsyncMarketsResource) -> None: + route = respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response(200, json=_AVAIL_RESPONSE) + ) + resp = await async_markets.weather_point_availability() + assert route.calls[0].request.method == "GET" + assert resp.enabled is True + assert resp.domains[0].name == "conus" + + @respx.mock + @pytest.mark.asyncio + async def test_async_empty_lists(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response( + 200, json={"enabled": False, "domains": [], "variables": []} + ) + ) + resp = await async_markets.weather_point_availability() + assert resp.enabled is False + assert resp.domains == [] + assert resp.variables == [] + + @respx.mock + @pytest.mark.asyncio + async def test_async_400(self, async_markets: AsyncMarketsResource) -> None: + respx.get(f"{BASE}/weather_point_markets/availability").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + await async_markets.weather_point_availability()